clang 20.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"
20#include "clang/AST/Attr.h"
22#include "clang/AST/CharUnits.h"
23#include "clang/AST/Comment.h"
24#include "clang/AST/Decl.h"
25#include "clang/AST/DeclBase.h"
26#include "clang/AST/DeclCXX.h"
28#include "clang/AST/DeclObjC.h"
33#include "clang/AST/Expr.h"
34#include "clang/AST/ExprCXX.h"
36#include "clang/AST/Mangle.h"
42#include "clang/AST/Stmt.h"
45#include "clang/AST/Type.h"
46#include "clang/AST/TypeLoc.h"
54#include "clang/Basic/LLVM.h"
56#include "clang/Basic/Linkage.h"
57#include "clang/Basic/Module.h"
67#include "llvm/ADT/APFixedPoint.h"
68#include "llvm/ADT/APInt.h"
69#include "llvm/ADT/APSInt.h"
70#include "llvm/ADT/ArrayRef.h"
71#include "llvm/ADT/DenseMap.h"
72#include "llvm/ADT/DenseSet.h"
73#include "llvm/ADT/FoldingSet.h"
74#include "llvm/ADT/PointerUnion.h"
75#include "llvm/ADT/STLExtras.h"
76#include "llvm/ADT/SmallPtrSet.h"
77#include "llvm/ADT/SmallVector.h"
78#include "llvm/ADT/StringExtras.h"
79#include "llvm/ADT/StringRef.h"
80#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
81#include "llvm/Support/Capacity.h"
82#include "llvm/Support/Compiler.h"
83#include "llvm/Support/ErrorHandling.h"
84#include "llvm/Support/MD5.h"
85#include "llvm/Support/MathExtras.h"
86#include "llvm/Support/SipHash.h"
87#include "llvm/Support/raw_ostream.h"
88#include "llvm/TargetParser/AArch64TargetParser.h"
89#include "llvm/TargetParser/Triple.h"
90#include <algorithm>
91#include <cassert>
92#include <cstddef>
93#include <cstdint>
94#include <cstdlib>
95#include <map>
96#include <memory>
97#include <optional>
98#include <string>
99#include <tuple>
100#include <utility>
101
102using namespace clang;
103
114
115template <> struct llvm::DenseMapInfo<llvm::FoldingSetNodeID> {
116 static FoldingSetNodeID getEmptyKey() { return FoldingSetNodeID{}; }
117
118 static FoldingSetNodeID getTombstoneKey() {
119 FoldingSetNodeID id;
120 for (size_t i = 0; i < sizeof(id) / sizeof(unsigned); ++i) {
121 id.AddInteger(std::numeric_limits<unsigned>::max());
122 }
123 return id;
124 }
125
126 static unsigned getHashValue(const FoldingSetNodeID &Val) {
127 return Val.ComputeHash();
128 }
129
130 static bool isEqual(const FoldingSetNodeID &LHS,
131 const FoldingSetNodeID &RHS) {
132 return LHS == RHS;
133 }
134};
135
136/// \returns The locations that are relevant when searching for Doc comments
137/// related to \p D.
140 assert(D);
141
142 // User can not attach documentation to implicit declarations.
143 if (D->isImplicit())
144 return {};
145
146 // User can not attach documentation to implicit instantiations.
147 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
148 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
149 return {};
150 }
151
152 if (const auto *VD = dyn_cast<VarDecl>(D)) {
153 if (VD->isStaticDataMember() &&
154 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
155 return {};
156 }
157
158 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
159 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
160 return {};
161 }
162
163 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
164 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
165 if (TSK == TSK_ImplicitInstantiation ||
166 TSK == TSK_Undeclared)
167 return {};
168 }
169
170 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
171 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
172 return {};
173 }
174 if (const auto *TD = dyn_cast<TagDecl>(D)) {
175 // When tag declaration (but not definition!) is part of the
176 // decl-specifier-seq of some other declaration, it doesn't get comment
177 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
178 return {};
179 }
180 // TODO: handle comments for function parameters properly.
181 if (isa<ParmVarDecl>(D))
182 return {};
183
184 // TODO: we could look up template parameter documentation in the template
185 // documentation.
186 if (isa<TemplateTypeParmDecl>(D) ||
187 isa<NonTypeTemplateParmDecl>(D) ||
188 isa<TemplateTemplateParmDecl>(D))
189 return {};
190
192 // Find declaration location.
193 // For Objective-C declarations we generally don't expect to have multiple
194 // declarators, thus use declaration starting location as the "declaration
195 // location".
196 // For all other declarations multiple declarators are used quite frequently,
197 // so we use the location of the identifier as the "declaration location".
198 SourceLocation BaseLocation;
199 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
200 isa<ObjCPropertyDecl>(D) || isa<RedeclarableTemplateDecl>(D) ||
201 isa<ClassTemplateSpecializationDecl>(D) ||
202 // Allow association with Y across {} in `typedef struct X {} Y`.
203 isa<TypedefDecl>(D))
204 BaseLocation = D->getBeginLoc();
205 else
206 BaseLocation = D->getLocation();
207
208 if (!D->getLocation().isMacroID()) {
209 Locations.emplace_back(BaseLocation);
210 } else {
211 const auto *DeclCtx = D->getDeclContext();
212
213 // When encountering definitions generated from a macro (that are not
214 // contained by another declaration in the macro) we need to try and find
215 // the comment at the location of the expansion but if there is no comment
216 // there we should retry to see if there is a comment inside the macro as
217 // well. To this end we return first BaseLocation to first look at the
218 // expansion site, the second value is the spelling location of the
219 // beginning of the declaration defined inside the macro.
220 if (!(DeclCtx &&
221 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
222 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
223 }
224
225 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
226 // we don't refer to the macro argument location at the expansion site (this
227 // can happen if the name's spelling is provided via macro argument), and
228 // always to the declaration itself.
229 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
230 }
231
232 return Locations;
233}
234
236 const Decl *D, const SourceLocation RepresentativeLocForDecl,
237 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
238 // If the declaration doesn't map directly to a location in a file, we
239 // can't find the comment.
240 if (RepresentativeLocForDecl.isInvalid() ||
241 !RepresentativeLocForDecl.isFileID())
242 return nullptr;
243
244 // If there are no comments anywhere, we won't find anything.
245 if (CommentsInTheFile.empty())
246 return nullptr;
247
248 // Decompose the location for the declaration and find the beginning of the
249 // file buffer.
250 const std::pair<FileID, unsigned> DeclLocDecomp =
251 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
252
253 // Slow path.
254 auto OffsetCommentBehindDecl =
255 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
256
257 // First check whether we have a trailing comment.
258 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
259 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
260 if ((CommentBehindDecl->isDocumentation() ||
261 LangOpts.CommentOpts.ParseAllComments) &&
262 CommentBehindDecl->isTrailingComment() &&
263 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
264 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
265
266 // Check that Doxygen trailing comment comes after the declaration, starts
267 // on the same line and in the same file as the declaration.
268 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
269 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
270 OffsetCommentBehindDecl->first)) {
271 return CommentBehindDecl;
272 }
273 }
274 }
275
276 // The comment just after the declaration was not a trailing comment.
277 // Let's look at the previous comment.
278 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
279 return nullptr;
280
281 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
282 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
283
284 // Check that we actually have a non-member Doxygen comment.
285 if (!(CommentBeforeDecl->isDocumentation() ||
286 LangOpts.CommentOpts.ParseAllComments) ||
287 CommentBeforeDecl->isTrailingComment())
288 return nullptr;
289
290 // Decompose the end of the comment.
291 const unsigned CommentEndOffset =
292 Comments.getCommentEndOffset(CommentBeforeDecl);
293
294 // Get the corresponding buffer.
295 bool Invalid = false;
296 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
297 &Invalid).data();
298 if (Invalid)
299 return nullptr;
300
301 // Extract text between the comment and declaration.
302 StringRef Text(Buffer + CommentEndOffset,
303 DeclLocDecomp.second - CommentEndOffset);
304
305 // There should be no other declarations or preprocessor directives between
306 // comment and declaration.
307 if (Text.find_last_of(";{}#@") != StringRef::npos)
308 return nullptr;
309
310 return CommentBeforeDecl;
311}
312
314 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
315
316 for (const auto DeclLoc : DeclLocs) {
317 // If the declaration doesn't map directly to a location in a file, we
318 // can't find the comment.
319 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
320 continue;
321
324 CommentsLoaded = true;
325 }
326
327 if (Comments.empty())
328 continue;
329
330 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
331 if (!File.isValid())
332 continue;
333
334 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
335 if (!CommentsInThisFile || CommentsInThisFile->empty())
336 continue;
337
338 if (RawComment *Comment =
339 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile))
340 return Comment;
341 }
342
343 return nullptr;
344}
345
347 assert(LangOpts.RetainCommentsFromSystemHeaders ||
348 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
349 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
350}
351
352/// If we have a 'templated' declaration for a template, adjust 'D' to
353/// refer to the actual template.
354/// If we have an implicit instantiation, adjust 'D' to refer to template.
355static const Decl &adjustDeclToTemplate(const Decl &D) {
356 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
357 // Is this function declaration part of a function template?
358 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
359 return *FTD;
360
361 // Nothing to do if function is not an implicit instantiation.
362 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
363 return D;
364
365 // Function is an implicit instantiation of a function template?
366 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
367 return *FTD;
368
369 // Function is instantiated from a member definition of a class template?
370 if (const FunctionDecl *MemberDecl =
372 return *MemberDecl;
373
374 return D;
375 }
376 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
377 // Static data member is instantiated from a member definition of a class
378 // template?
379 if (VD->isStaticDataMember())
380 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
381 return *MemberDecl;
382
383 return D;
384 }
385 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
386 // Is this class declaration part of a class template?
387 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
388 return *CTD;
389
390 // Class is an implicit instantiation of a class template or partial
391 // specialization?
392 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
393 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
394 return D;
395 llvm::PointerUnion<ClassTemplateDecl *,
398 return isa<ClassTemplateDecl *>(PU)
399 ? *static_cast<const Decl *>(cast<ClassTemplateDecl *>(PU))
400 : *static_cast<const Decl *>(
401 cast<ClassTemplatePartialSpecializationDecl *>(PU));
402 }
403
404 // Class is instantiated from a member definition of a class template?
405 if (const MemberSpecializationInfo *Info =
406 CRD->getMemberSpecializationInfo())
407 return *Info->getInstantiatedFrom();
408
409 return D;
410 }
411 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
412 // Enum is instantiated from a member definition of a class template?
413 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
414 return *MemberDecl;
415
416 return D;
417 }
418 // FIXME: Adjust alias templates?
419 return D;
420}
421
423 const Decl *D,
424 const Decl **OriginalDecl) const {
425 if (!D) {
426 if (OriginalDecl)
427 OriginalDecl = nullptr;
428 return nullptr;
429 }
430
432
433 // Any comment directly attached to D?
434 {
435 auto DeclComment = DeclRawComments.find(D);
436 if (DeclComment != DeclRawComments.end()) {
437 if (OriginalDecl)
438 *OriginalDecl = D;
439 return DeclComment->second;
440 }
441 }
442
443 // Any comment attached to any redeclaration of D?
444 const Decl *CanonicalD = D->getCanonicalDecl();
445 if (!CanonicalD)
446 return nullptr;
447
448 {
449 auto RedeclComment = RedeclChainComments.find(CanonicalD);
450 if (RedeclComment != RedeclChainComments.end()) {
451 if (OriginalDecl)
452 *OriginalDecl = RedeclComment->second;
453 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
454 assert(CommentAtRedecl != DeclRawComments.end() &&
455 "This decl is supposed to have comment attached.");
456 return CommentAtRedecl->second;
457 }
458 }
459
460 // Any redeclarations of D that we haven't checked for comments yet?
461 const Decl *LastCheckedRedecl = [&]() {
462 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
463 bool CanUseCommentlessCache = false;
464 if (LastChecked) {
465 for (auto *Redecl : CanonicalD->redecls()) {
466 if (Redecl == D) {
467 CanUseCommentlessCache = true;
468 break;
469 }
470 if (Redecl == LastChecked)
471 break;
472 }
473 }
474 // FIXME: This could be improved so that even if CanUseCommentlessCache
475 // is false, once we've traversed past CanonicalD we still skip ahead
476 // LastChecked.
477 return CanUseCommentlessCache ? LastChecked : nullptr;
478 }();
479
480 for (const Decl *Redecl : D->redecls()) {
481 assert(Redecl);
482 // Skip all redeclarations that have been checked previously.
483 if (LastCheckedRedecl) {
484 if (LastCheckedRedecl == Redecl) {
485 LastCheckedRedecl = nullptr;
486 }
487 continue;
488 }
489 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
490 if (RedeclComment) {
491 cacheRawCommentForDecl(*Redecl, *RedeclComment);
492 if (OriginalDecl)
493 *OriginalDecl = Redecl;
494 return RedeclComment;
495 }
496 CommentlessRedeclChains[CanonicalD] = Redecl;
497 }
498
499 if (OriginalDecl)
500 *OriginalDecl = nullptr;
501 return nullptr;
502}
503
505 const RawComment &Comment) const {
506 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
507 DeclRawComments.try_emplace(&OriginalD, &Comment);
508 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
509 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
510 CommentlessRedeclChains.erase(CanonicalDecl);
511}
512
513static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
515 const DeclContext *DC = ObjCMethod->getDeclContext();
516 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
517 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
518 if (!ID)
519 return;
520 // Add redeclared method here.
521 for (const auto *Ext : ID->known_extensions()) {
522 if (ObjCMethodDecl *RedeclaredMethod =
523 Ext->getMethod(ObjCMethod->getSelector(),
524 ObjCMethod->isInstanceMethod()))
525 Redeclared.push_back(RedeclaredMethod);
526 }
527 }
528}
529
531 const Preprocessor *PP) {
532 if (Comments.empty() || Decls.empty())
533 return;
534
535 FileID File;
536 for (const Decl *D : Decls) {
537 if (D->isInvalidDecl())
538 continue;
539
542 if (Loc.isValid()) {
543 // See if there are any new comments that are not attached to a decl.
544 // The location doesn't have to be precise - we care only about the file.
545 File = SourceMgr.getDecomposedLoc(Loc).first;
546 break;
547 }
548 }
549
550 if (File.isInvalid())
551 return;
552
553 auto CommentsInThisFile = Comments.getCommentsInFile(File);
554 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
555 CommentsInThisFile->rbegin()->second->isAttached())
556 return;
557
558 // There is at least one comment not attached to a decl.
559 // Maybe it should be attached to one of Decls?
560 //
561 // Note that this way we pick up not only comments that precede the
562 // declaration, but also comments that *follow* the declaration -- thanks to
563 // the lookahead in the lexer: we've consumed the semicolon and looked
564 // ahead through comments.
565 for (const Decl *D : Decls) {
566 assert(D);
567 if (D->isInvalidDecl())
568 continue;
569
571
572 if (DeclRawComments.count(D) > 0)
573 continue;
574
575 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
576
577 for (const auto DeclLoc : DeclLocs) {
578 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
579 continue;
580
581 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
582 D, DeclLoc, *CommentsInThisFile)) {
583 cacheRawCommentForDecl(*D, *DocComment);
584 comments::FullComment *FC = DocComment->parse(*this, PP, D);
586 break;
587 }
588 }
589 }
590}
591
593 const Decl *D) const {
594 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
595 ThisDeclInfo->CommentDecl = D;
596 ThisDeclInfo->IsFilled = false;
597 ThisDeclInfo->fill();
598 ThisDeclInfo->CommentDecl = FC->getDecl();
599 if (!ThisDeclInfo->TemplateParameters)
600 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
602 new (*this) comments::FullComment(FC->getBlocks(),
603 ThisDeclInfo);
604 return CFC;
605}
606
609 return RC ? RC->parse(*this, nullptr, D) : nullptr;
610}
611
613 const Decl *D,
614 const Preprocessor *PP) const {
615 if (!D || D->isInvalidDecl())
616 return nullptr;
618
619 const Decl *Canonical = D->getCanonicalDecl();
620 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
621 ParsedComments.find(Canonical);
622
623 if (Pos != ParsedComments.end()) {
624 if (Canonical != D) {
625 comments::FullComment *FC = Pos->second;
627 return CFC;
628 }
629 return Pos->second;
630 }
631
632 const Decl *OriginalDecl = nullptr;
633
634 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
635 if (!RC) {
636 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
638 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
639 if (OMD && OMD->isPropertyAccessor())
640 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
641 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
642 return cloneFullComment(FC, D);
643 if (OMD)
644 addRedeclaredMethods(OMD, Overridden);
645 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
646 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
647 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
648 return cloneFullComment(FC, D);
649 }
650 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
651 // Attach any tag type's documentation to its typedef if latter
652 // does not have one of its own.
653 QualType QT = TD->getUnderlyingType();
654 if (const auto *TT = QT->getAs<TagType>())
655 if (const Decl *TD = TT->getDecl())
657 return cloneFullComment(FC, D);
658 }
659 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
660 while (IC->getSuperClass()) {
661 IC = IC->getSuperClass();
663 return cloneFullComment(FC, D);
664 }
665 }
666 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
667 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
669 return cloneFullComment(FC, D);
670 }
671 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
672 if (!(RD = RD->getDefinition()))
673 return nullptr;
674 // Check non-virtual bases.
675 for (const auto &I : RD->bases()) {
676 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
677 continue;
678 QualType Ty = I.getType();
679 if (Ty.isNull())
680 continue;
682 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
683 continue;
684
686 return cloneFullComment(FC, D);
687 }
688 }
689 // Check virtual bases.
690 for (const auto &I : RD->vbases()) {
691 if (I.getAccessSpecifier() != AS_public)
692 continue;
693 QualType Ty = I.getType();
694 if (Ty.isNull())
695 continue;
696 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
697 if (!(VirtualBase= VirtualBase->getDefinition()))
698 continue;
700 return cloneFullComment(FC, D);
701 }
702 }
703 }
704 return nullptr;
705 }
706
707 // If the RawComment was attached to other redeclaration of this Decl, we
708 // should parse the comment in context of that other Decl. This is important
709 // because comments can contain references to parameter names which can be
710 // different across redeclarations.
711 if (D != OriginalDecl && OriginalDecl)
712 return getCommentForDecl(OriginalDecl, PP);
713
714 comments::FullComment *FC = RC->parse(*this, PP, D);
715 ParsedComments[Canonical] = FC;
716 return FC;
717}
718
719void
720ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
721 const ASTContext &C,
723 ID.AddInteger(Parm->getDepth());
724 ID.AddInteger(Parm->getPosition());
725 ID.AddBoolean(Parm->isParameterPack());
726
728 ID.AddInteger(Params->size());
730 PEnd = Params->end();
731 P != PEnd; ++P) {
732 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
733 ID.AddInteger(0);
734 ID.AddBoolean(TTP->isParameterPack());
735 if (TTP->isExpandedParameterPack()) {
736 ID.AddBoolean(true);
737 ID.AddInteger(TTP->getNumExpansionParameters());
738 } else
739 ID.AddBoolean(false);
740 continue;
741 }
742
743 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
744 ID.AddInteger(1);
745 ID.AddBoolean(NTTP->isParameterPack());
746 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
747 .getAsOpaquePtr());
748 if (NTTP->isExpandedParameterPack()) {
749 ID.AddBoolean(true);
750 ID.AddInteger(NTTP->getNumExpansionTypes());
751 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
752 QualType T = NTTP->getExpansionType(I);
753 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
754 }
755 } else
756 ID.AddBoolean(false);
757 continue;
758 }
759
760 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
761 ID.AddInteger(2);
762 Profile(ID, C, TTP);
763 }
764}
765
767ASTContext::getCanonicalTemplateTemplateParmDecl(
768 TemplateTemplateParmDecl *TTP) const {
769 // Check if we already have a canonical template template parameter.
770 llvm::FoldingSetNodeID ID;
771 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
772 void *InsertPos = nullptr;
773 CanonicalTemplateTemplateParm *Canonical
774 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
775 if (Canonical)
776 return Canonical->getParam();
777
778 // Build a canonical template parameter list.
780 SmallVector<NamedDecl *, 4> CanonParams;
781 CanonParams.reserve(Params->size());
783 PEnd = Params->end();
784 P != PEnd; ++P) {
785 // Note that, per C++20 [temp.over.link]/6, when determining whether
786 // template-parameters are equivalent, constraints are ignored.
787 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
790 TTP->getDepth(), TTP->getIndex(), nullptr, false,
791 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
793 ? std::optional<unsigned>(TTP->getNumExpansionParameters())
794 : std::nullopt);
795 CanonParams.push_back(NewTTP);
796 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
800 if (NTTP->isExpandedParameterPack()) {
801 SmallVector<QualType, 2> ExpandedTypes;
803 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
804 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
805 ExpandedTInfos.push_back(
806 getTrivialTypeSourceInfo(ExpandedTypes.back()));
807 }
808
812 NTTP->getDepth(),
813 NTTP->getPosition(), nullptr,
814 T,
815 TInfo,
816 ExpandedTypes,
817 ExpandedTInfos);
818 } else {
822 NTTP->getDepth(),
823 NTTP->getPosition(), nullptr,
824 T,
825 NTTP->isParameterPack(),
826 TInfo);
827 }
828 CanonParams.push_back(Param);
829 } else
830 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
831 cast<TemplateTemplateParmDecl>(*P)));
832 }
833
836 TTP->getPosition(), TTP->isParameterPack(), nullptr, /*Typename=*/false,
838 CanonParams, SourceLocation(),
839 /*RequiresClause=*/nullptr));
840
841 // Get the new insert position for the node we care about.
842 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
843 assert(!Canonical && "Shouldn't be in the map!");
844 (void)Canonical;
845
846 // Create the canonical template template parameter entry.
847 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
848 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
849 return CanonTTP;
850}
851
852/// Check if a type can have its sanitizer instrumentation elided based on its
853/// presence within an ignorelist.
855 const QualType &Ty) const {
856 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
857 return NoSanitizeL->containsType(Mask, TyName) &&
858 !NoSanitizeL->containsType(Mask, TyName, "sanitize");
859}
860
862 auto Kind = getTargetInfo().getCXXABI().getKind();
863 return getLangOpts().CXXABI.value_or(Kind);
864}
865
866CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
867 if (!LangOpts.CPlusPlus) return nullptr;
868
869 switch (getCXXABIKind()) {
870 case TargetCXXABI::AppleARM64:
871 case TargetCXXABI::Fuchsia:
872 case TargetCXXABI::GenericARM: // Same as Itanium at this level
873 case TargetCXXABI::iOS:
874 case TargetCXXABI::WatchOS:
875 case TargetCXXABI::GenericAArch64:
876 case TargetCXXABI::GenericMIPS:
877 case TargetCXXABI::GenericItanium:
878 case TargetCXXABI::WebAssembly:
879 case TargetCXXABI::XL:
880 return CreateItaniumCXXABI(*this);
881 case TargetCXXABI::Microsoft:
882 return CreateMicrosoftCXXABI(*this);
883 }
884 llvm_unreachable("Invalid CXXABI type!");
885}
886
888 if (!InterpContext) {
889 InterpContext.reset(new interp::Context(*this));
890 }
891 return *InterpContext.get();
892}
893
895 if (!ParentMapCtx)
896 ParentMapCtx.reset(new ParentMapContext(*this));
897 return *ParentMapCtx.get();
898}
899
901 const LangOptions &LangOpts) {
902 switch (LangOpts.getAddressSpaceMapMangling()) {
904 return TI.useAddressSpaceMapMangling();
906 return true;
908 return false;
909 }
910 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
911}
912
914 IdentifierTable &idents, SelectorTable &sels,
915 Builtin::Context &builtins, TranslationUnitKind TUKind)
916 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
917 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
918 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
919 DependentSizedMatrixTypes(this_()),
920 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
921 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
922 TemplateSpecializationTypes(this_()),
923 DependentTemplateSpecializationTypes(this_()),
924 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
925 DeducedTemplates(this_()), ArrayParameterTypes(this_()),
926 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
927 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
928 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
929 LangOpts.XRayNeverInstrumentFiles,
930 LangOpts.XRayAttrListFiles, SM)),
931 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
932 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
933 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
934 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
935 CompCategories(this_()), LastSDM(nullptr, 0) {
937}
938
940 // Release the DenseMaps associated with DeclContext objects.
941 // FIXME: Is this the ideal solution?
942 ReleaseDeclContextMaps();
943
944 // Call all of the deallocation functions on all of their targets.
945 for (auto &Pair : Deallocations)
946 (Pair.first)(Pair.second);
947 Deallocations.clear();
948
949 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
950 // because they can contain DenseMaps.
951 for (llvm::DenseMap<const ObjCContainerDecl*,
952 const ASTRecordLayout*>::iterator
953 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
954 // Increment in loop to prevent using deallocated memory.
955 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
956 R->Destroy(*this);
957 ObjCLayouts.clear();
958
959 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
960 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
961 // Increment in loop to prevent using deallocated memory.
962 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
963 R->Destroy(*this);
964 }
965 ASTRecordLayouts.clear();
966
967 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
968 AEnd = DeclAttrs.end();
969 A != AEnd; ++A)
970 A->second->~AttrVec();
971 DeclAttrs.clear();
972
973 for (const auto &Value : ModuleInitializers)
974 Value.second->~PerModuleInitializers();
975 ModuleInitializers.clear();
976}
977
979
980void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
981 TraversalScope = TopLevelDecls;
983}
984
985void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
986 Deallocations.push_back({Callback, Data});
987}
988
989void
991 ExternalSource = std::move(Source);
992}
993
995 llvm::errs() << "\n*** AST Context Stats:\n";
996 llvm::errs() << " " << Types.size() << " types total.\n";
997
998 unsigned counts[] = {
999#define TYPE(Name, Parent) 0,
1000#define ABSTRACT_TYPE(Name, Parent)
1001#include "clang/AST/TypeNodes.inc"
1002 0 // Extra
1003 };
1004
1005 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1006 Type *T = Types[i];
1007 counts[(unsigned)T->getTypeClass()]++;
1008 }
1009
1010 unsigned Idx = 0;
1011 unsigned TotalBytes = 0;
1012#define TYPE(Name, Parent) \
1013 if (counts[Idx]) \
1014 llvm::errs() << " " << counts[Idx] << " " << #Name \
1015 << " types, " << sizeof(Name##Type) << " each " \
1016 << "(" << counts[Idx] * sizeof(Name##Type) \
1017 << " bytes)\n"; \
1018 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1019 ++Idx;
1020#define ABSTRACT_TYPE(Name, Parent)
1021#include "clang/AST/TypeNodes.inc"
1022
1023 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1024
1025 // Implicit special member functions.
1026 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1028 << " implicit default constructors created\n";
1029 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1031 << " implicit copy constructors created\n";
1032 if (getLangOpts().CPlusPlus)
1033 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1035 << " implicit move constructors created\n";
1036 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1038 << " implicit copy assignment operators created\n";
1039 if (getLangOpts().CPlusPlus)
1040 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1042 << " implicit move assignment operators created\n";
1043 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1045 << " implicit destructors created\n";
1046
1047 if (ExternalSource) {
1048 llvm::errs() << "\n";
1050 }
1051
1052 BumpAlloc.PrintStats();
1053}
1054
1056 bool NotifyListeners) {
1057 if (NotifyListeners)
1058 if (auto *Listener = getASTMutationListener())
1060
1061 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1062}
1063
1065 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1066 if (It == MergedDefModules.end())
1067 return;
1068
1069 auto &Merged = It->second;
1070 llvm::DenseSet<Module*> Found;
1071 for (Module *&M : Merged)
1072 if (!Found.insert(M).second)
1073 M = nullptr;
1074 llvm::erase(Merged, nullptr);
1075}
1076
1079 auto MergedIt =
1080 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1081 if (MergedIt == MergedDefModules.end())
1082 return {};
1083 return MergedIt->second;
1084}
1085
1086void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1087 if (LazyInitializers.empty())
1088 return;
1089
1090 auto *Source = Ctx.getExternalSource();
1091 assert(Source && "lazy initializers but no external source");
1092
1093 auto LazyInits = std::move(LazyInitializers);
1094 LazyInitializers.clear();
1095
1096 for (auto ID : LazyInits)
1097 Initializers.push_back(Source->GetExternalDecl(ID));
1098
1099 assert(LazyInitializers.empty() &&
1100 "GetExternalDecl for lazy module initializer added more inits");
1101}
1102
1104 // One special case: if we add a module initializer that imports another
1105 // module, and that module's only initializer is an ImportDecl, simplify.
1106 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1107 auto It = ModuleInitializers.find(ID->getImportedModule());
1108
1109 // Maybe the ImportDecl does nothing at all. (Common case.)
1110 if (It == ModuleInitializers.end())
1111 return;
1112
1113 // Maybe the ImportDecl only imports another ImportDecl.
1114 auto &Imported = *It->second;
1115 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1116 Imported.resolve(*this);
1117 auto *OnlyDecl = Imported.Initializers.front();
1118 if (isa<ImportDecl>(OnlyDecl))
1119 D = OnlyDecl;
1120 }
1121 }
1122
1123 auto *&Inits = ModuleInitializers[M];
1124 if (!Inits)
1125 Inits = new (*this) PerModuleInitializers;
1126 Inits->Initializers.push_back(D);
1127}
1128
1131 auto *&Inits = ModuleInitializers[M];
1132 if (!Inits)
1133 Inits = new (*this) PerModuleInitializers;
1134 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1135 IDs.begin(), IDs.end());
1136}
1137
1139 auto It = ModuleInitializers.find(M);
1140 if (It == ModuleInitializers.end())
1141 return {};
1142
1143 auto *Inits = It->second;
1144 Inits->resolve(*this);
1145 return Inits->Initializers;
1146}
1147
1149 assert(M->isNamedModule());
1150 assert(!CurrentCXXNamedModule &&
1151 "We should set named module for ASTContext for only once");
1152 CurrentCXXNamedModule = M;
1153}
1154
1155bool ASTContext::isInSameModule(const Module *M1, const Module *M2) {
1156 if (!M1 != !M2)
1157 return false;
1158
1159 /// Get the representative module for M. The representative module is the
1160 /// first module unit for a specific primary module name. So that the module
1161 /// units have the same representative module belongs to the same module.
1162 ///
1163 /// The process is helpful to reduce the expensive string operations.
1164 auto GetRepresentativeModule = [this](const Module *M) {
1165 auto Iter = SameModuleLookupSet.find(M);
1166 if (Iter != SameModuleLookupSet.end())
1167 return Iter->second;
1168
1169 const Module *RepresentativeModule =
1170 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1171 .first->second;
1172 SameModuleLookupSet[M] = RepresentativeModule;
1173 return RepresentativeModule;
1174 };
1175
1176 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1177 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1178}
1179
1181 if (!ExternCContext)
1182 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1183
1184 return ExternCContext;
1185}
1186
1189 const IdentifierInfo *II) const {
1190 auto *BuiltinTemplate =
1192 BuiltinTemplate->setImplicit();
1193 getTranslationUnitDecl()->addDecl(BuiltinTemplate);
1194
1195 return BuiltinTemplate;
1196}
1197
1200 if (!MakeIntegerSeqDecl)
1203 return MakeIntegerSeqDecl;
1204}
1205
1208 if (!TypePackElementDecl)
1211 return TypePackElementDecl;
1212}
1213
1215 if (!BuiltinCommonTypeDecl)
1216 BuiltinCommonTypeDecl = buildBuiltinTemplateDecl(
1218 return BuiltinCommonTypeDecl;
1219}
1220
1222 RecordDecl::TagKind TK) const {
1224 RecordDecl *NewDecl;
1225 if (getLangOpts().CPlusPlus)
1226 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1227 Loc, &Idents.get(Name));
1228 else
1229 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1230 &Idents.get(Name));
1231 NewDecl->setImplicit();
1232 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1233 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1234 return NewDecl;
1235}
1236
1238 StringRef Name) const {
1241 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1242 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1243 NewDecl->setImplicit();
1244 return NewDecl;
1245}
1246
1248 if (!Int128Decl)
1249 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1250 return Int128Decl;
1251}
1252
1254 if (!UInt128Decl)
1255 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1256 return UInt128Decl;
1257}
1258
1259void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1260 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1262 Types.push_back(Ty);
1263}
1264
1266 const TargetInfo *AuxTarget) {
1267 assert((!this->Target || this->Target == &Target) &&
1268 "Incorrect target reinitialization");
1269 assert(VoidTy.isNull() && "Context reinitialized?");
1270
1271 this->Target = &Target;
1272 this->AuxTarget = AuxTarget;
1273
1274 ABI.reset(createCXXABI(Target));
1275 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1276
1277 // C99 6.2.5p19.
1278 InitBuiltinType(VoidTy, BuiltinType::Void);
1279
1280 // C99 6.2.5p2.
1281 InitBuiltinType(BoolTy, BuiltinType::Bool);
1282 // C99 6.2.5p3.
1283 if (LangOpts.CharIsSigned)
1284 InitBuiltinType(CharTy, BuiltinType::Char_S);
1285 else
1286 InitBuiltinType(CharTy, BuiltinType::Char_U);
1287 // C99 6.2.5p4.
1288 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1289 InitBuiltinType(ShortTy, BuiltinType::Short);
1290 InitBuiltinType(IntTy, BuiltinType::Int);
1291 InitBuiltinType(LongTy, BuiltinType::Long);
1292 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1293
1294 // C99 6.2.5p6.
1295 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1296 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1297 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1298 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1299 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1300
1301 // C99 6.2.5p10.
1302 InitBuiltinType(FloatTy, BuiltinType::Float);
1303 InitBuiltinType(DoubleTy, BuiltinType::Double);
1304 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1305
1306 // GNU extension, __float128 for IEEE quadruple precision
1307 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1308
1309 // __ibm128 for IBM extended precision
1310 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1311
1312 // C11 extension ISO/IEC TS 18661-3
1313 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1314
1315 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1316 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1317 InitBuiltinType(AccumTy, BuiltinType::Accum);
1318 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1319 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1320 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1321 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1322 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1323 InitBuiltinType(FractTy, BuiltinType::Fract);
1324 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1325 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1326 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1327 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1328 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1329 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1330 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1331 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1332 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1333 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1334 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1335 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1336 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1337 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1338 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1339 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1340
1341 // GNU extension, 128-bit integers.
1342 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1343 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1344
1345 // C++ 3.9.1p5
1346 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1347 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1348 else // -fshort-wchar makes wchar_t be unsigned.
1349 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1350 if (LangOpts.CPlusPlus && LangOpts.WChar)
1352 else {
1353 // C99 (or C++ using -fno-wchar).
1354 WideCharTy = getFromTargetType(Target.getWCharType());
1355 }
1356
1357 WIntTy = getFromTargetType(Target.getWIntType());
1358
1359 // C++20 (proposed)
1360 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1361
1362 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1363 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1364 else // C99
1365 Char16Ty = getFromTargetType(Target.getChar16Type());
1366
1367 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1368 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1369 else // C99
1370 Char32Ty = getFromTargetType(Target.getChar32Type());
1371
1372 // Placeholder type for type-dependent expressions whose type is
1373 // completely unknown. No code should ever check a type against
1374 // DependentTy and users should never see it; however, it is here to
1375 // help diagnose failures to properly check for type-dependent
1376 // expressions.
1377 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1378
1379 // Placeholder type for functions.
1380 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1381
1382 // Placeholder type for bound members.
1383 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1384
1385 // Placeholder type for unresolved templates.
1386 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1387
1388 // Placeholder type for pseudo-objects.
1389 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1390
1391 // "any" type; useful for debugger-like clients.
1392 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1393
1394 // Placeholder type for unbridged ARC casts.
1395 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1396
1397 // Placeholder type for builtin functions.
1398 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1399
1400 // Placeholder type for OMP array sections.
1401 if (LangOpts.OpenMP) {
1402 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1403 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1404 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1405 }
1406 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1407 // don't bother, as we're just using the same type as OMP.
1408 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1409 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1410 }
1411 if (LangOpts.MatrixTypes)
1412 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1413
1414 // Builtin types for 'id', 'Class', and 'SEL'.
1415 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1416 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1417 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1418
1419 if (LangOpts.OpenCL) {
1420#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1421 InitBuiltinType(SingletonId, BuiltinType::Id);
1422#include "clang/Basic/OpenCLImageTypes.def"
1423
1424 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1425 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1426 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1427 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1428 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1429
1430#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1431 InitBuiltinType(Id##Ty, BuiltinType::Id);
1432#include "clang/Basic/OpenCLExtensionTypes.def"
1433 }
1434
1435 if (LangOpts.HLSL) {
1436#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1437 InitBuiltinType(SingletonId, BuiltinType::Id);
1438#include "clang/Basic/HLSLIntangibleTypes.def"
1439 }
1440
1441 if (Target.hasAArch64SVETypes() ||
1442 (AuxTarget && AuxTarget->hasAArch64SVETypes())) {
1443#define SVE_TYPE(Name, Id, SingletonId) \
1444 InitBuiltinType(SingletonId, BuiltinType::Id);
1445#include "clang/Basic/AArch64SVEACLETypes.def"
1446 }
1447
1448 if (Target.getTriple().isPPC64()) {
1449#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1450 InitBuiltinType(Id##Ty, BuiltinType::Id);
1451#include "clang/Basic/PPCTypes.def"
1452#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1453 InitBuiltinType(Id##Ty, BuiltinType::Id);
1454#include "clang/Basic/PPCTypes.def"
1455 }
1456
1457 if (Target.hasRISCVVTypes()) {
1458#define RVV_TYPE(Name, Id, SingletonId) \
1459 InitBuiltinType(SingletonId, BuiltinType::Id);
1460#include "clang/Basic/RISCVVTypes.def"
1461 }
1462
1463 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1464#define WASM_TYPE(Name, Id, SingletonId) \
1465 InitBuiltinType(SingletonId, BuiltinType::Id);
1466#include "clang/Basic/WebAssemblyReferenceTypes.def"
1467 }
1468
1469 if (Target.getTriple().isAMDGPU() ||
1470 (AuxTarget && AuxTarget->getTriple().isAMDGPU())) {
1471#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1472 InitBuiltinType(SingletonId, BuiltinType::Id);
1473#include "clang/Basic/AMDGPUTypes.def"
1474 }
1475
1476 // Builtin type for __objc_yes and __objc_no
1477 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1479
1480 ObjCConstantStringType = QualType();
1481
1482 ObjCSuperType = QualType();
1483
1484 // void * type
1485 if (LangOpts.OpenCLGenericAddressSpace) {
1486 auto Q = VoidTy.getQualifiers();
1490 } else {
1492 }
1493
1494 // nullptr type (C++0x 2.14.7)
1495 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1496
1497 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1498 InitBuiltinType(HalfTy, BuiltinType::Half);
1499
1500 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1501
1502 // Builtin type used to help define __builtin_va_list.
1503 VaListTagDecl = nullptr;
1504
1505 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1506 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1509 }
1510}
1511
1513 return SourceMgr.getDiagnostics();
1514}
1515
1517 AttrVec *&Result = DeclAttrs[D];
1518 if (!Result) {
1519 void *Mem = Allocate(sizeof(AttrVec));
1520 Result = new (Mem) AttrVec;
1521 }
1522
1523 return *Result;
1524}
1525
1526/// Erase the attributes corresponding to the given declaration.
1528 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1529 if (Pos != DeclAttrs.end()) {
1530 Pos->second->~AttrVec();
1531 DeclAttrs.erase(Pos);
1532 }
1533}
1534
1535// FIXME: Remove ?
1538 assert(Var->isStaticDataMember() && "Not a static data member");
1540 .dyn_cast<MemberSpecializationInfo *>();
1541}
1542
1545 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1546 TemplateOrInstantiation.find(Var);
1547 if (Pos == TemplateOrInstantiation.end())
1548 return {};
1549
1550 return Pos->second;
1551}
1552
1553void
1556 SourceLocation PointOfInstantiation) {
1557 assert(Inst->isStaticDataMember() && "Not a static data member");
1558 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1560 Tmpl, TSK, PointOfInstantiation));
1561}
1562
1563void
1566 assert(!TemplateOrInstantiation[Inst] &&
1567 "Already noted what the variable was instantiated from");
1568 TemplateOrInstantiation[Inst] = TSI;
1569}
1570
1571NamedDecl *
1573 return InstantiatedFromUsingDecl.lookup(UUD);
1574}
1575
1576void
1578 assert((isa<UsingDecl>(Pattern) ||
1579 isa<UnresolvedUsingValueDecl>(Pattern) ||
1580 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1581 "pattern decl is not a using decl");
1582 assert((isa<UsingDecl>(Inst) ||
1583 isa<UnresolvedUsingValueDecl>(Inst) ||
1584 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1585 "instantiation did not produce a using decl");
1586 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1587 InstantiatedFromUsingDecl[Inst] = Pattern;
1588}
1589
1592 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1593}
1594
1596 UsingEnumDecl *Pattern) {
1597 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1598 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1599}
1600
1603 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1604}
1605
1606void
1608 UsingShadowDecl *Pattern) {
1609 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1610 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1611}
1612
1613FieldDecl *
1615 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1616}
1617
1619 FieldDecl *Tmpl) {
1620 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1621 "Instantiated field decl is not unnamed");
1622 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1623 "Template field decl is not unnamed");
1624 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1625 "Already noted what unnamed field was instantiated from");
1626
1627 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1628}
1629
1632 return overridden_methods(Method).begin();
1633}
1634
1637 return overridden_methods(Method).end();
1638}
1639
1640unsigned
1642 auto Range = overridden_methods(Method);
1643 return Range.end() - Range.begin();
1644}
1645
1648 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1649 OverriddenMethods.find(Method->getCanonicalDecl());
1650 if (Pos == OverriddenMethods.end())
1651 return overridden_method_range(nullptr, nullptr);
1652 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1653}
1654
1656 const CXXMethodDecl *Overridden) {
1657 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1658 OverriddenMethods[Method].push_back(Overridden);
1659}
1660
1662 const NamedDecl *D,
1663 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1664 assert(D);
1665
1666 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1667 Overridden.append(overridden_methods_begin(CXXMethod),
1668 overridden_methods_end(CXXMethod));
1669 return;
1670 }
1671
1672 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1673 if (!Method)
1674 return;
1675
1677 Method->getOverriddenMethods(OverDecls);
1678 Overridden.append(OverDecls.begin(), OverDecls.end());
1679}
1680
1682 assert(!Import->getNextLocalImport() &&
1683 "Import declaration already in the chain");
1684 assert(!Import->isFromASTFile() && "Non-local import declaration");
1685 if (!FirstLocalImport) {
1686 FirstLocalImport = Import;
1687 LastLocalImport = Import;
1688 return;
1689 }
1690
1691 LastLocalImport->setNextLocalImport(Import);
1692 LastLocalImport = Import;
1693}
1694
1695//===----------------------------------------------------------------------===//
1696// Type Sizing and Analysis
1697//===----------------------------------------------------------------------===//
1698
1699/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1700/// scalar floating point type.
1701const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1702 switch (T->castAs<BuiltinType>()->getKind()) {
1703 default:
1704 llvm_unreachable("Not a floating point type!");
1705 case BuiltinType::BFloat16:
1706 return Target->getBFloat16Format();
1707 case BuiltinType::Float16:
1708 return Target->getHalfFormat();
1709 case BuiltinType::Half:
1710 return Target->getHalfFormat();
1711 case BuiltinType::Float: return Target->getFloatFormat();
1712 case BuiltinType::Double: return Target->getDoubleFormat();
1713 case BuiltinType::Ibm128:
1714 return Target->getIbm128Format();
1715 case BuiltinType::LongDouble:
1716 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1717 return AuxTarget->getLongDoubleFormat();
1718 return Target->getLongDoubleFormat();
1719 case BuiltinType::Float128:
1720 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1721 return AuxTarget->getFloat128Format();
1722 return Target->getFloat128Format();
1723 }
1724}
1725
1726CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1727 unsigned Align = Target->getCharWidth();
1728
1729 const unsigned AlignFromAttr = D->getMaxAlignment();
1730 if (AlignFromAttr)
1731 Align = AlignFromAttr;
1732
1733 // __attribute__((aligned)) can increase or decrease alignment
1734 // *except* on a struct or struct member, where it only increases
1735 // alignment unless 'packed' is also specified.
1736 //
1737 // It is an error for alignas to decrease alignment, so we can
1738 // ignore that possibility; Sema should diagnose it.
1739 bool UseAlignAttrOnly;
1740 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1741 UseAlignAttrOnly =
1742 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1743 else
1744 UseAlignAttrOnly = AlignFromAttr != 0;
1745 // If we're using the align attribute only, just ignore everything
1746 // else about the declaration and its type.
1747 if (UseAlignAttrOnly) {
1748 // do nothing
1749 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1750 QualType T = VD->getType();
1751 if (const auto *RT = T->getAs<ReferenceType>()) {
1752 if (ForAlignof)
1753 T = RT->getPointeeType();
1754 else
1755 T = getPointerType(RT->getPointeeType());
1756 }
1757 QualType BaseT = getBaseElementType(T);
1758 if (T->isFunctionType())
1759 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1760 else if (!BaseT->isIncompleteType()) {
1761 // Adjust alignments of declarations with array type by the
1762 // large-array alignment on the target.
1763 if (const ArrayType *arrayType = getAsArrayType(T)) {
1764 unsigned MinWidth = Target->getLargeArrayMinWidth();
1765 if (!ForAlignof && MinWidth) {
1766 if (isa<VariableArrayType>(arrayType))
1767 Align = std::max(Align, Target->getLargeArrayAlign());
1768 else if (isa<ConstantArrayType>(arrayType) &&
1769 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1770 Align = std::max(Align, Target->getLargeArrayAlign());
1771 }
1772 }
1773 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1774 if (BaseT.getQualifiers().hasUnaligned())
1775 Align = Target->getCharWidth();
1776 }
1777
1778 // Ensure miminum alignment for global variables.
1779 if (const auto *VD = dyn_cast<VarDecl>(D))
1780 if (VD->hasGlobalStorage() && !ForAlignof) {
1781 uint64_t TypeSize =
1782 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1783 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1784 }
1785
1786 // Fields can be subject to extra alignment constraints, like if
1787 // the field is packed, the struct is packed, or the struct has a
1788 // a max-field-alignment constraint (#pragma pack). So calculate
1789 // the actual alignment of the field within the struct, and then
1790 // (as we're expected to) constrain that by the alignment of the type.
1791 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1792 const RecordDecl *Parent = Field->getParent();
1793 // We can only produce a sensible answer if the record is valid.
1794 if (!Parent->isInvalidDecl()) {
1795 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1796
1797 // Start with the record's overall alignment.
1798 unsigned FieldAlign = toBits(Layout.getAlignment());
1799
1800 // Use the GCD of that and the offset within the record.
1801 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1802 if (Offset > 0) {
1803 // Alignment is always a power of 2, so the GCD will be a power of 2,
1804 // which means we get to do this crazy thing instead of Euclid's.
1805 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1806 if (LowBitOfOffset < FieldAlign)
1807 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1808 }
1809
1810 Align = std::min(Align, FieldAlign);
1811 }
1812 }
1813 }
1814
1815 // Some targets have hard limitation on the maximum requestable alignment in
1816 // aligned attribute for static variables.
1817 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1818 const auto *VD = dyn_cast<VarDecl>(D);
1819 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1820 Align = std::min(Align, MaxAlignedAttr);
1821
1822 return toCharUnitsFromBits(Align);
1823}
1824
1826 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1827}
1828
1829// getTypeInfoDataSizeInChars - Return the size of a type, in
1830// chars. If the type is a record, its data size is returned. This is
1831// the size of the memcpy that's performed when assigning this type
1832// using a trivial copy/move assignment operator.
1835
1836 // In C++, objects can sometimes be allocated into the tail padding
1837 // of a base-class subobject. We decide whether that's possible
1838 // during class layout, so here we can just trust the layout results.
1839 if (getLangOpts().CPlusPlus) {
1840 if (const auto *RT = T->getAs<RecordType>();
1841 RT && !RT->getDecl()->isInvalidDecl()) {
1842 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1843 Info.Width = layout.getDataSize();
1844 }
1845 }
1846
1847 return Info;
1848}
1849
1850/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1851/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1854 const ConstantArrayType *CAT) {
1855 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1856 uint64_t Size = CAT->getZExtSize();
1857 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1858 (uint64_t)(-1)/Size) &&
1859 "Overflow in array type char size evaluation");
1860 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1861 unsigned Align = EltInfo.Align.getQuantity();
1862 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1864 Width = llvm::alignTo(Width, Align);
1867 EltInfo.AlignRequirement);
1868}
1869
1871 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1872 return getConstantArrayInfoInChars(*this, CAT);
1873 TypeInfo Info = getTypeInfo(T);
1876}
1877
1879 return getTypeInfoInChars(T.getTypePtr());
1880}
1881
1883 // HLSL doesn't promote all small integer types to int, it
1884 // just uses the rank-based promotion rules for all types.
1885 if (getLangOpts().HLSL)
1886 return false;
1887
1888 if (const auto *BT = T->getAs<BuiltinType>())
1889 switch (BT->getKind()) {
1890 case BuiltinType::Bool:
1891 case BuiltinType::Char_S:
1892 case BuiltinType::Char_U:
1893 case BuiltinType::SChar:
1894 case BuiltinType::UChar:
1895 case BuiltinType::Short:
1896 case BuiltinType::UShort:
1897 case BuiltinType::WChar_S:
1898 case BuiltinType::WChar_U:
1899 case BuiltinType::Char8:
1900 case BuiltinType::Char16:
1901 case BuiltinType::Char32:
1902 return true;
1903 default:
1904 return false;
1905 }
1906
1907 // Enumerated types are promotable to their compatible integer types
1908 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1909 if (const auto *ET = T->getAs<EnumType>()) {
1910 if (T->isDependentType() || ET->getDecl()->getPromotionType().isNull() ||
1911 ET->getDecl()->isScoped())
1912 return false;
1913
1914 return true;
1915 }
1916
1917 return false;
1918}
1919
1922}
1923
1925 return isAlignmentRequired(T.getTypePtr());
1926}
1927
1929 bool NeedsPreferredAlignment) const {
1930 // An alignment on a typedef overrides anything else.
1931 if (const auto *TT = T->getAs<TypedefType>())
1932 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1933 return Align;
1934
1935 // If we have an (array of) complete type, we're done.
1937 if (!T->isIncompleteType())
1938 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1939
1940 // If we had an array type, its element type might be a typedef
1941 // type with an alignment attribute.
1942 if (const auto *TT = T->getAs<TypedefType>())
1943 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1944 return Align;
1945
1946 // Otherwise, see if the declaration of the type had an attribute.
1947 if (const auto *TT = T->getAs<TagType>())
1948 return TT->getDecl()->getMaxAlignment();
1949
1950 return 0;
1951}
1952
1954 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1955 if (I != MemoizedTypeInfo.end())
1956 return I->second;
1957
1958 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1959 TypeInfo TI = getTypeInfoImpl(T);
1960 MemoizedTypeInfo[T] = TI;
1961 return TI;
1962}
1963
1964/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1965/// method does not work on incomplete types.
1966///
1967/// FIXME: Pointers into different addr spaces could have different sizes and
1968/// alignment requirements: getPointerInfo should take an AddrSpace, this
1969/// should take a QualType, &c.
1970TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1971 uint64_t Width = 0;
1972 unsigned Align = 8;
1975 switch (T->getTypeClass()) {
1976#define TYPE(Class, Base)
1977#define ABSTRACT_TYPE(Class, Base)
1978#define NON_CANONICAL_TYPE(Class, Base)
1979#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1980#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1981 case Type::Class: \
1982 assert(!T->isDependentType() && "should not see dependent types here"); \
1983 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1984#include "clang/AST/TypeNodes.inc"
1985 llvm_unreachable("Should not see dependent types");
1986
1987 case Type::FunctionNoProto:
1988 case Type::FunctionProto:
1989 // GCC extension: alignof(function) = 32 bits
1990 Width = 0;
1991 Align = 32;
1992 break;
1993
1994 case Type::IncompleteArray:
1995 case Type::VariableArray:
1996 case Type::ConstantArray:
1997 case Type::ArrayParameter: {
1998 // Model non-constant sized arrays as size zero, but track the alignment.
1999 uint64_t Size = 0;
2000 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2001 Size = CAT->getZExtSize();
2002
2003 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2004 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2005 "Overflow in array type bit size evaluation");
2006 Width = EltInfo.Width * Size;
2007 Align = EltInfo.Align;
2008 AlignRequirement = EltInfo.AlignRequirement;
2009 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2010 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2011 Width = llvm::alignTo(Width, Align);
2012 break;
2013 }
2014
2015 case Type::ExtVector:
2016 case Type::Vector: {
2017 const auto *VT = cast<VectorType>(T);
2018 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2019 Width = VT->isExtVectorBoolType() ? VT->getNumElements()
2020 : EltInfo.Width * VT->getNumElements();
2021 // Enforce at least byte size and alignment.
2022 Width = std::max<unsigned>(8, Width);
2023 Align = std::max<unsigned>(8, Width);
2024
2025 // If the alignment is not a power of 2, round up to the next power of 2.
2026 // This happens for non-power-of-2 length vectors.
2027 if (Align & (Align-1)) {
2028 Align = llvm::bit_ceil(Align);
2029 Width = llvm::alignTo(Width, Align);
2030 }
2031 // Adjust the alignment based on the target max.
2032 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2033 if (TargetVectorAlign && TargetVectorAlign < Align)
2034 Align = TargetVectorAlign;
2035 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2036 // Adjust the alignment for fixed-length SVE vectors. This is important
2037 // for non-power-of-2 vector lengths.
2038 Align = 128;
2039 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2040 // Adjust the alignment for fixed-length SVE predicates.
2041 Align = 16;
2042 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2043 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2044 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2045 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2046 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2047 // Adjust the alignment for fixed-length RVV vectors.
2048 Align = std::min<unsigned>(64, Width);
2049 break;
2050 }
2051
2052 case Type::ConstantMatrix: {
2053 const auto *MT = cast<ConstantMatrixType>(T);
2054 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2055 // The internal layout of a matrix value is implementation defined.
2056 // Initially be ABI compatible with arrays with respect to alignment and
2057 // size.
2058 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2059 Align = ElementInfo.Align;
2060 break;
2061 }
2062
2063 case Type::Builtin:
2064 switch (cast<BuiltinType>(T)->getKind()) {
2065 default: llvm_unreachable("Unknown builtin type!");
2066 case BuiltinType::Void:
2067 // GCC extension: alignof(void) = 8 bits.
2068 Width = 0;
2069 Align = 8;
2070 break;
2071 case BuiltinType::Bool:
2072 Width = Target->getBoolWidth();
2073 Align = Target->getBoolAlign();
2074 break;
2075 case BuiltinType::Char_S:
2076 case BuiltinType::Char_U:
2077 case BuiltinType::UChar:
2078 case BuiltinType::SChar:
2079 case BuiltinType::Char8:
2080 Width = Target->getCharWidth();
2081 Align = Target->getCharAlign();
2082 break;
2083 case BuiltinType::WChar_S:
2084 case BuiltinType::WChar_U:
2085 Width = Target->getWCharWidth();
2086 Align = Target->getWCharAlign();
2087 break;
2088 case BuiltinType::Char16:
2089 Width = Target->getChar16Width();
2090 Align = Target->getChar16Align();
2091 break;
2092 case BuiltinType::Char32:
2093 Width = Target->getChar32Width();
2094 Align = Target->getChar32Align();
2095 break;
2096 case BuiltinType::UShort:
2097 case BuiltinType::Short:
2098 Width = Target->getShortWidth();
2099 Align = Target->getShortAlign();
2100 break;
2101 case BuiltinType::UInt:
2102 case BuiltinType::Int:
2103 Width = Target->getIntWidth();
2104 Align = Target->getIntAlign();
2105 break;
2106 case BuiltinType::ULong:
2107 case BuiltinType::Long:
2108 Width = Target->getLongWidth();
2109 Align = Target->getLongAlign();
2110 break;
2111 case BuiltinType::ULongLong:
2112 case BuiltinType::LongLong:
2113 Width = Target->getLongLongWidth();
2114 Align = Target->getLongLongAlign();
2115 break;
2116 case BuiltinType::Int128:
2117 case BuiltinType::UInt128:
2118 Width = 128;
2119 Align = Target->getInt128Align();
2120 break;
2121 case BuiltinType::ShortAccum:
2122 case BuiltinType::UShortAccum:
2123 case BuiltinType::SatShortAccum:
2124 case BuiltinType::SatUShortAccum:
2125 Width = Target->getShortAccumWidth();
2126 Align = Target->getShortAccumAlign();
2127 break;
2128 case BuiltinType::Accum:
2129 case BuiltinType::UAccum:
2130 case BuiltinType::SatAccum:
2131 case BuiltinType::SatUAccum:
2132 Width = Target->getAccumWidth();
2133 Align = Target->getAccumAlign();
2134 break;
2135 case BuiltinType::LongAccum:
2136 case BuiltinType::ULongAccum:
2137 case BuiltinType::SatLongAccum:
2138 case BuiltinType::SatULongAccum:
2139 Width = Target->getLongAccumWidth();
2140 Align = Target->getLongAccumAlign();
2141 break;
2142 case BuiltinType::ShortFract:
2143 case BuiltinType::UShortFract:
2144 case BuiltinType::SatShortFract:
2145 case BuiltinType::SatUShortFract:
2146 Width = Target->getShortFractWidth();
2147 Align = Target->getShortFractAlign();
2148 break;
2149 case BuiltinType::Fract:
2150 case BuiltinType::UFract:
2151 case BuiltinType::SatFract:
2152 case BuiltinType::SatUFract:
2153 Width = Target->getFractWidth();
2154 Align = Target->getFractAlign();
2155 break;
2156 case BuiltinType::LongFract:
2157 case BuiltinType::ULongFract:
2158 case BuiltinType::SatLongFract:
2159 case BuiltinType::SatULongFract:
2160 Width = Target->getLongFractWidth();
2161 Align = Target->getLongFractAlign();
2162 break;
2163 case BuiltinType::BFloat16:
2164 if (Target->hasBFloat16Type()) {
2165 Width = Target->getBFloat16Width();
2166 Align = Target->getBFloat16Align();
2167 } else if ((getLangOpts().SYCLIsDevice ||
2168 (getLangOpts().OpenMP &&
2169 getLangOpts().OpenMPIsTargetDevice)) &&
2170 AuxTarget->hasBFloat16Type()) {
2171 Width = AuxTarget->getBFloat16Width();
2172 Align = AuxTarget->getBFloat16Align();
2173 }
2174 break;
2175 case BuiltinType::Float16:
2176 case BuiltinType::Half:
2177 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2178 !getLangOpts().OpenMPIsTargetDevice) {
2179 Width = Target->getHalfWidth();
2180 Align = Target->getHalfAlign();
2181 } else {
2182 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2183 "Expected OpenMP device compilation.");
2184 Width = AuxTarget->getHalfWidth();
2185 Align = AuxTarget->getHalfAlign();
2186 }
2187 break;
2188 case BuiltinType::Float:
2189 Width = Target->getFloatWidth();
2190 Align = Target->getFloatAlign();
2191 break;
2192 case BuiltinType::Double:
2193 Width = Target->getDoubleWidth();
2194 Align = Target->getDoubleAlign();
2195 break;
2196 case BuiltinType::Ibm128:
2197 Width = Target->getIbm128Width();
2198 Align = Target->getIbm128Align();
2199 break;
2200 case BuiltinType::LongDouble:
2201 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2202 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2203 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2204 Width = AuxTarget->getLongDoubleWidth();
2205 Align = AuxTarget->getLongDoubleAlign();
2206 } else {
2207 Width = Target->getLongDoubleWidth();
2208 Align = Target->getLongDoubleAlign();
2209 }
2210 break;
2211 case BuiltinType::Float128:
2212 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2213 !getLangOpts().OpenMPIsTargetDevice) {
2214 Width = Target->getFloat128Width();
2215 Align = Target->getFloat128Align();
2216 } else {
2217 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2218 "Expected OpenMP device compilation.");
2219 Width = AuxTarget->getFloat128Width();
2220 Align = AuxTarget->getFloat128Align();
2221 }
2222 break;
2223 case BuiltinType::NullPtr:
2224 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2225 Width = Target->getPointerWidth(LangAS::Default);
2226 Align = Target->getPointerAlign(LangAS::Default);
2227 break;
2228 case BuiltinType::ObjCId:
2229 case BuiltinType::ObjCClass:
2230 case BuiltinType::ObjCSel:
2231 Width = Target->getPointerWidth(LangAS::Default);
2232 Align = Target->getPointerAlign(LangAS::Default);
2233 break;
2234 case BuiltinType::OCLSampler:
2235 case BuiltinType::OCLEvent:
2236 case BuiltinType::OCLClkEvent:
2237 case BuiltinType::OCLQueue:
2238 case BuiltinType::OCLReserveID:
2239#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2240 case BuiltinType::Id:
2241#include "clang/Basic/OpenCLImageTypes.def"
2242#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2243 case BuiltinType::Id:
2244#include "clang/Basic/OpenCLExtensionTypes.def"
2245 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2246 Width = Target->getPointerWidth(AS);
2247 Align = Target->getPointerAlign(AS);
2248 break;
2249 // The SVE types are effectively target-specific. The length of an
2250 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2251 // of 128 bits. There is one predicate bit for each vector byte, so the
2252 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2253 //
2254 // Because the length is only known at runtime, we use a dummy value
2255 // of 0 for the static length. The alignment values are those defined
2256 // by the Procedure Call Standard for the Arm Architecture.
2257#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2258 case BuiltinType::Id: \
2259 Width = 0; \
2260 Align = 128; \
2261 break;
2262#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2263 case BuiltinType::Id: \
2264 Width = 0; \
2265 Align = 16; \
2266 break;
2267#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2268 case BuiltinType::Id: \
2269 Width = 0; \
2270 Align = 16; \
2271 break;
2272#define AARCH64_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
2273 ElBits, NF) \
2274 case BuiltinType::Id: \
2275 Width = NumEls * ElBits * NF; \
2276 Align = NumEls * ElBits; \
2277 break;
2278#include "clang/Basic/AArch64SVEACLETypes.def"
2279#define PPC_VECTOR_TYPE(Name, Id, Size) \
2280 case BuiltinType::Id: \
2281 Width = Size; \
2282 Align = Size; \
2283 break;
2284#include "clang/Basic/PPCTypes.def"
2285#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2286 IsFP, IsBF) \
2287 case BuiltinType::Id: \
2288 Width = 0; \
2289 Align = ElBits; \
2290 break;
2291#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2292 case BuiltinType::Id: \
2293 Width = 0; \
2294 Align = 8; \
2295 break;
2296#include "clang/Basic/RISCVVTypes.def"
2297#define WASM_TYPE(Name, Id, SingletonId) \
2298 case BuiltinType::Id: \
2299 Width = 0; \
2300 Align = 8; \
2301 break;
2302#include "clang/Basic/WebAssemblyReferenceTypes.def"
2303#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2304 case BuiltinType::ID: \
2305 Width = WIDTH; \
2306 Align = ALIGN; \
2307 break;
2308#include "clang/Basic/AMDGPUTypes.def"
2309#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2310#include "clang/Basic/HLSLIntangibleTypes.def"
2311 Width = Target->getPointerWidth(LangAS::Default);
2312 Align = Target->getPointerAlign(LangAS::Default);
2313 break;
2314 }
2315 break;
2316 case Type::ObjCObjectPointer:
2317 Width = Target->getPointerWidth(LangAS::Default);
2318 Align = Target->getPointerAlign(LangAS::Default);
2319 break;
2320 case Type::BlockPointer:
2321 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2322 Width = Target->getPointerWidth(AS);
2323 Align = Target->getPointerAlign(AS);
2324 break;
2325 case Type::LValueReference:
2326 case Type::RValueReference:
2327 // alignof and sizeof should never enter this code path here, so we go
2328 // the pointer route.
2329 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2330 Width = Target->getPointerWidth(AS);
2331 Align = Target->getPointerAlign(AS);
2332 break;
2333 case Type::Pointer:
2334 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2335 Width = Target->getPointerWidth(AS);
2336 Align = Target->getPointerAlign(AS);
2337 break;
2338 case Type::MemberPointer: {
2339 const auto *MPT = cast<MemberPointerType>(T);
2340 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2341 Width = MPI.Width;
2342 Align = MPI.Align;
2343 break;
2344 }
2345 case Type::Complex: {
2346 // Complex types have the same alignment as their elements, but twice the
2347 // size.
2348 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2349 Width = EltInfo.Width * 2;
2350 Align = EltInfo.Align;
2351 break;
2352 }
2353 case Type::ObjCObject:
2354 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2355 case Type::Adjusted:
2356 case Type::Decayed:
2357 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2358 case Type::ObjCInterface: {
2359 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2360 if (ObjCI->getDecl()->isInvalidDecl()) {
2361 Width = 8;
2362 Align = 8;
2363 break;
2364 }
2365 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2366 Width = toBits(Layout.getSize());
2367 Align = toBits(Layout.getAlignment());
2368 break;
2369 }
2370 case Type::BitInt: {
2371 const auto *EIT = cast<BitIntType>(T);
2372 Align = Target->getBitIntAlign(EIT->getNumBits());
2373 Width = Target->getBitIntWidth(EIT->getNumBits());
2374 break;
2375 }
2376 case Type::Record:
2377 case Type::Enum: {
2378 const auto *TT = cast<TagType>(T);
2379
2380 if (TT->getDecl()->isInvalidDecl()) {
2381 Width = 8;
2382 Align = 8;
2383 break;
2384 }
2385
2386 if (const auto *ET = dyn_cast<EnumType>(TT)) {
2387 const EnumDecl *ED = ET->getDecl();
2388 TypeInfo Info =
2390 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2391 Info.Align = AttrAlign;
2393 }
2394 return Info;
2395 }
2396
2397 const auto *RT = cast<RecordType>(TT);
2398 const RecordDecl *RD = RT->getDecl();
2399 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2400 Width = toBits(Layout.getSize());
2401 Align = toBits(Layout.getAlignment());
2402 AlignRequirement = RD->hasAttr<AlignedAttr>()
2405 break;
2406 }
2407
2408 case Type::SubstTemplateTypeParm:
2409 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2410 getReplacementType().getTypePtr());
2411
2412 case Type::Auto:
2413 case Type::DeducedTemplateSpecialization: {
2414 const auto *A = cast<DeducedType>(T);
2415 assert(!A->getDeducedType().isNull() &&
2416 "cannot request the size of an undeduced or dependent auto type");
2417 return getTypeInfo(A->getDeducedType().getTypePtr());
2418 }
2419
2420 case Type::Paren:
2421 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2422
2423 case Type::MacroQualified:
2424 return getTypeInfo(
2425 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2426
2427 case Type::ObjCTypeParam:
2428 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2429
2430 case Type::Using:
2431 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2432
2433 case Type::Typedef: {
2434 const auto *TT = cast<TypedefType>(T);
2435 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2436 // If the typedef has an aligned attribute on it, it overrides any computed
2437 // alignment we have. This violates the GCC documentation (which says that
2438 // attribute(aligned) can only round up) but matches its implementation.
2439 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2440 Align = AttrAlign;
2441 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2442 } else {
2443 Align = Info.Align;
2444 AlignRequirement = Info.AlignRequirement;
2445 }
2446 Width = Info.Width;
2447 break;
2448 }
2449
2450 case Type::Elaborated:
2451 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2452
2453 case Type::Attributed:
2454 return getTypeInfo(
2455 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2456
2457 case Type::CountAttributed:
2458 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2459
2460 case Type::BTFTagAttributed:
2461 return getTypeInfo(
2462 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2463
2464 case Type::HLSLAttributedResource:
2465 return getTypeInfo(
2466 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2467
2468 case Type::Atomic: {
2469 // Start with the base type information.
2470 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2471 Width = Info.Width;
2472 Align = Info.Align;
2473
2474 if (!Width) {
2475 // An otherwise zero-sized type should still generate an
2476 // atomic operation.
2477 Width = Target->getCharWidth();
2478 assert(Align);
2479 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2480 // If the size of the type doesn't exceed the platform's max
2481 // atomic promotion width, make the size and alignment more
2482 // favorable to atomic operations:
2483
2484 // Round the size up to a power of 2.
2485 Width = llvm::bit_ceil(Width);
2486
2487 // Set the alignment equal to the size.
2488 Align = static_cast<unsigned>(Width);
2489 }
2490 }
2491 break;
2492
2493 case Type::Pipe:
2494 Width = Target->getPointerWidth(LangAS::opencl_global);
2495 Align = Target->getPointerAlign(LangAS::opencl_global);
2496 break;
2497 }
2498
2499 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2500 return TypeInfo(Width, Align, AlignRequirement);
2501}
2502
2504 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2505 if (I != MemoizedUnadjustedAlign.end())
2506 return I->second;
2507
2508 unsigned UnadjustedAlign;
2509 if (const auto *RT = T->getAs<RecordType>()) {
2510 const RecordDecl *RD = RT->getDecl();
2511 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2512 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2513 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2514 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2515 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2516 } else {
2517 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2518 }
2519
2520 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2521 return UnadjustedAlign;
2522}
2523
2525 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2526 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2527 return SimdAlign;
2528}
2529
2530/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2532 return CharUnits::fromQuantity(BitSize / getCharWidth());
2533}
2534
2535/// toBits - Convert a size in characters to a size in characters.
2536int64_t ASTContext::toBits(CharUnits CharSize) const {
2537 return CharSize.getQuantity() * getCharWidth();
2538}
2539
2540/// getTypeSizeInChars - Return the size of the specified type, in characters.
2541/// This method does not work on incomplete types.
2543 return getTypeInfoInChars(T).Width;
2544}
2546 return getTypeInfoInChars(T).Width;
2547}
2548
2549/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2550/// characters. This method does not work on incomplete types.
2553}
2556}
2557
2558/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2559/// type, in characters, before alignment adjustments. This method does
2560/// not work on incomplete types.
2563}
2566}
2567
2568/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2569/// type for the current target in bits. This can be different than the ABI
2570/// alignment in cases where it is beneficial for performance or backwards
2571/// compatibility preserving to overalign a data type. (Note: despite the name,
2572/// the preferred alignment is ABI-impacting, and not an optimization.)
2574 TypeInfo TI = getTypeInfo(T);
2575 unsigned ABIAlign = TI.Align;
2576
2578
2579 // The preferred alignment of member pointers is that of a pointer.
2580 if (T->isMemberPointerType())
2581 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2582
2583 if (!Target->allowsLargerPreferedTypeAlignment())
2584 return ABIAlign;
2585
2586 if (const auto *RT = T->getAs<RecordType>()) {
2587 const RecordDecl *RD = RT->getDecl();
2588
2589 // When used as part of a typedef, or together with a 'packed' attribute,
2590 // the 'aligned' attribute can be used to decrease alignment. Note that the
2591 // 'packed' case is already taken into consideration when computing the
2592 // alignment, we only need to handle the typedef case here.
2594 RD->isInvalidDecl())
2595 return ABIAlign;
2596
2597 unsigned PreferredAlign = static_cast<unsigned>(
2598 toBits(getASTRecordLayout(RD).PreferredAlignment));
2599 assert(PreferredAlign >= ABIAlign &&
2600 "PreferredAlign should be at least as large as ABIAlign.");
2601 return PreferredAlign;
2602 }
2603
2604 // Double (and, for targets supporting AIX `power` alignment, long double) and
2605 // long long should be naturally aligned (despite requiring less alignment) if
2606 // possible.
2607 if (const auto *CT = T->getAs<ComplexType>())
2608 T = CT->getElementType().getTypePtr();
2609 if (const auto *ET = T->getAs<EnumType>())
2610 T = ET->getDecl()->getIntegerType().getTypePtr();
2611 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2612 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2613 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2614 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2615 Target->defaultsToAIXPowerAlignment()))
2616 // Don't increase the alignment if an alignment attribute was specified on a
2617 // typedef declaration.
2618 if (!TI.isAlignRequired())
2619 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2620
2621 return ABIAlign;
2622}
2623
2624/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2625/// for __attribute__((aligned)) on this target, to be used if no alignment
2626/// value is specified.
2629}
2630
2631/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2632/// to a global variable of the specified type.
2634 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2635 return std::max(getPreferredTypeAlign(T),
2636 getMinGlobalAlignOfVar(TypeSize, VD));
2637}
2638
2639/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2640/// should be given to a global variable of the specified type.
2642 const VarDecl *VD) const {
2644}
2645
2647 const VarDecl *VD) const {
2648 // Make the default handling as that of a non-weak definition in the
2649 // current translation unit.
2650 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2651 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2652}
2653
2655 CharUnits Offset = CharUnits::Zero();
2656 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2657 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2658 Offset += Layout->getBaseClassOffset(Base);
2659 Layout = &getASTRecordLayout(Base);
2660 }
2661 return Offset;
2662}
2663
2665 const ValueDecl *MPD = MP.getMemberPointerDecl();
2668 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2669 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2670 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2671 const CXXRecordDecl *Base = RD;
2672 const CXXRecordDecl *Derived = Path[I];
2673 if (DerivedMember)
2674 std::swap(Base, Derived);
2676 RD = Path[I];
2677 }
2678 if (DerivedMember)
2680 return ThisAdjustment;
2681}
2682
2683/// DeepCollectObjCIvars -
2684/// This routine first collects all declared, but not synthesized, ivars in
2685/// super class and then collects all ivars, including those synthesized for
2686/// current class. This routine is used for implementation of current class
2687/// when all ivars, declared and synthesized are known.
2689 bool leafClass,
2691 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2692 DeepCollectObjCIvars(SuperClass, false, Ivars);
2693 if (!leafClass) {
2694 llvm::append_range(Ivars, OI->ivars());
2695 } else {
2696 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2697 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2698 Iv= Iv->getNextIvar())
2699 Ivars.push_back(Iv);
2700 }
2701}
2702
2703/// CollectInheritedProtocols - Collect all protocols in current class and
2704/// those inherited by it.
2707 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2708 // We can use protocol_iterator here instead of
2709 // all_referenced_protocol_iterator since we are walking all categories.
2710 for (auto *Proto : OI->all_referenced_protocols()) {
2711 CollectInheritedProtocols(Proto, Protocols);
2712 }
2713
2714 // Categories of this Interface.
2715 for (const auto *Cat : OI->visible_categories())
2716 CollectInheritedProtocols(Cat, Protocols);
2717
2718 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2719 while (SD) {
2720 CollectInheritedProtocols(SD, Protocols);
2721 SD = SD->getSuperClass();
2722 }
2723 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2724 for (auto *Proto : OC->protocols()) {
2725 CollectInheritedProtocols(Proto, Protocols);
2726 }
2727 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2728 // Insert the protocol.
2729 if (!Protocols.insert(
2730 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2731 return;
2732
2733 for (auto *Proto : OP->protocols())
2734 CollectInheritedProtocols(Proto, Protocols);
2735 }
2736}
2737
2739 const RecordDecl *RD,
2740 bool CheckIfTriviallyCopyable) {
2741 assert(RD->isUnion() && "Must be union type");
2742 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2743
2744 for (const auto *Field : RD->fields()) {
2745 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2746 CheckIfTriviallyCopyable))
2747 return false;
2748 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2749 if (FieldSize != UnionSize)
2750 return false;
2751 }
2752 return !RD->field_empty();
2753}
2754
2755static int64_t getSubobjectOffset(const FieldDecl *Field,
2756 const ASTContext &Context,
2757 const clang::ASTRecordLayout & /*Layout*/) {
2758 return Context.getFieldOffset(Field);
2759}
2760
2761static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2762 const ASTContext &Context,
2763 const clang::ASTRecordLayout &Layout) {
2764 return Context.toBits(Layout.getBaseClassOffset(RD));
2765}
2766
2767static std::optional<int64_t>
2769 const RecordDecl *RD,
2770 bool CheckIfTriviallyCopyable);
2771
2772static std::optional<int64_t>
2773getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2774 bool CheckIfTriviallyCopyable) {
2775 if (Field->getType()->isRecordType()) {
2776 const RecordDecl *RD = Field->getType()->getAsRecordDecl();
2777 if (!RD->isUnion())
2778 return structHasUniqueObjectRepresentations(Context, RD,
2779 CheckIfTriviallyCopyable);
2780 }
2781
2782 // A _BitInt type may not be unique if it has padding bits
2783 // but if it is a bitfield the padding bits are not used.
2784 bool IsBitIntType = Field->getType()->isBitIntType();
2785 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2786 !Context.hasUniqueObjectRepresentations(Field->getType(),
2787 CheckIfTriviallyCopyable))
2788 return std::nullopt;
2789
2790 int64_t FieldSizeInBits =
2791 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2792 if (Field->isBitField()) {
2793 // If we have explicit padding bits, they don't contribute bits
2794 // to the actual object representation, so return 0.
2795 if (Field->isUnnamedBitField())
2796 return 0;
2797
2798 int64_t BitfieldSize = Field->getBitWidthValue();
2799 if (IsBitIntType) {
2800 if ((unsigned)BitfieldSize >
2801 cast<BitIntType>(Field->getType())->getNumBits())
2802 return std::nullopt;
2803 } else if (BitfieldSize > FieldSizeInBits) {
2804 return std::nullopt;
2805 }
2806 FieldSizeInBits = BitfieldSize;
2807 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2808 Field->getType(), CheckIfTriviallyCopyable)) {
2809 return std::nullopt;
2810 }
2811 return FieldSizeInBits;
2812}
2813
2814static std::optional<int64_t>
2816 bool CheckIfTriviallyCopyable) {
2817 return structHasUniqueObjectRepresentations(Context, RD,
2818 CheckIfTriviallyCopyable);
2819}
2820
2821template <typename RangeT>
2823 const RangeT &Subobjects, int64_t CurOffsetInBits,
2824 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2825 bool CheckIfTriviallyCopyable) {
2826 for (const auto *Subobject : Subobjects) {
2827 std::optional<int64_t> SizeInBits =
2828 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2829 if (!SizeInBits)
2830 return std::nullopt;
2831 if (*SizeInBits != 0) {
2832 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2833 if (Offset != CurOffsetInBits)
2834 return std::nullopt;
2835 CurOffsetInBits += *SizeInBits;
2836 }
2837 }
2838 return CurOffsetInBits;
2839}
2840
2841static std::optional<int64_t>
2843 const RecordDecl *RD,
2844 bool CheckIfTriviallyCopyable) {
2845 assert(!RD->isUnion() && "Must be struct/class type");
2846 const auto &Layout = Context.getASTRecordLayout(RD);
2847
2848 int64_t CurOffsetInBits = 0;
2849 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2850 if (ClassDecl->isDynamicClass())
2851 return std::nullopt;
2852
2854 for (const auto &Base : ClassDecl->bases()) {
2855 // Empty types can be inherited from, and non-empty types can potentially
2856 // have tail padding, so just make sure there isn't an error.
2857 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2858 }
2859
2860 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2861 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2862 });
2863
2864 std::optional<int64_t> OffsetAfterBases =
2866 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2867 if (!OffsetAfterBases)
2868 return std::nullopt;
2869 CurOffsetInBits = *OffsetAfterBases;
2870 }
2871
2872 std::optional<int64_t> OffsetAfterFields =
2874 RD->fields(), CurOffsetInBits, Context, Layout,
2875 CheckIfTriviallyCopyable);
2876 if (!OffsetAfterFields)
2877 return std::nullopt;
2878 CurOffsetInBits = *OffsetAfterFields;
2879
2880 return CurOffsetInBits;
2881}
2882
2884 QualType Ty, bool CheckIfTriviallyCopyable) const {
2885 // C++17 [meta.unary.prop]:
2886 // The predicate condition for a template specialization
2887 // has_unique_object_representations<T> shall be satisfied if and only if:
2888 // (9.1) - T is trivially copyable, and
2889 // (9.2) - any two objects of type T with the same value have the same
2890 // object representation, where:
2891 // - two objects of array or non-union class type are considered to have
2892 // the same value if their respective sequences of direct subobjects
2893 // have the same values, and
2894 // - two objects of union type are considered to have the same value if
2895 // they have the same active member and the corresponding members have
2896 // the same value.
2897 // The set of scalar types for which this condition holds is
2898 // implementation-defined. [ Note: If a type has padding bits, the condition
2899 // does not hold; otherwise, the condition holds true for unsigned integral
2900 // types. -- end note ]
2901 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2902
2903 // Arrays are unique only if their element type is unique.
2904 if (Ty->isArrayType())
2906 CheckIfTriviallyCopyable);
2907
2908 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
2909 "hasUniqueObjectRepresentations should not be called with an "
2910 "incomplete type");
2911
2912 // (9.1) - T is trivially copyable...
2913 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
2914 return false;
2915
2916 // All integrals and enums are unique.
2917 if (Ty->isIntegralOrEnumerationType()) {
2918 // Except _BitInt types that have padding bits.
2919 if (const auto *BIT = Ty->getAs<BitIntType>())
2920 return getTypeSize(BIT) == BIT->getNumBits();
2921
2922 return true;
2923 }
2924
2925 // All other pointers are unique.
2926 if (Ty->isPointerType())
2927 return true;
2928
2929 if (const auto *MPT = Ty->getAs<MemberPointerType>())
2930 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2931
2932 if (Ty->isRecordType()) {
2933 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2934
2935 if (Record->isInvalidDecl())
2936 return false;
2937
2938 if (Record->isUnion())
2940 CheckIfTriviallyCopyable);
2941
2942 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
2943 *this, Record, CheckIfTriviallyCopyable);
2944
2945 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
2946 }
2947
2948 // FIXME: More cases to handle here (list by rsmith):
2949 // vectors (careful about, eg, vector of 3 foo)
2950 // _Complex int and friends
2951 // _Atomic T
2952 // Obj-C block pointers
2953 // Obj-C object pointers
2954 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2955 // clk_event_t, queue_t, reserve_id_t)
2956 // There're also Obj-C class types and the Obj-C selector type, but I think it
2957 // makes sense for those to return false here.
2958
2959 return false;
2960}
2961
2963 unsigned count = 0;
2964 // Count ivars declared in class extension.
2965 for (const auto *Ext : OI->known_extensions())
2966 count += Ext->ivar_size();
2967
2968 // Count ivar defined in this class's implementation. This
2969 // includes synthesized ivars.
2970 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2971 count += ImplDecl->ivar_size();
2972
2973 return count;
2974}
2975
2977 if (!E)
2978 return false;
2979
2980 // nullptr_t is always treated as null.
2981 if (E->getType()->isNullPtrType()) return true;
2982
2983 if (E->getType()->isAnyPointerType() &&
2986 return true;
2987
2988 // Unfortunately, __null has type 'int'.
2989 if (isa<GNUNullExpr>(E)) return true;
2990
2991 return false;
2992}
2993
2994/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2995/// exists.
2997 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2998 I = ObjCImpls.find(D);
2999 if (I != ObjCImpls.end())
3000 return cast<ObjCImplementationDecl>(I->second);
3001 return nullptr;
3002}
3003
3004/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3005/// exists.
3007 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3008 I = ObjCImpls.find(D);
3009 if (I != ObjCImpls.end())
3010 return cast<ObjCCategoryImplDecl>(I->second);
3011 return nullptr;
3012}
3013
3014/// Set the implementation of ObjCInterfaceDecl.
3016 ObjCImplementationDecl *ImplD) {
3017 assert(IFaceD && ImplD && "Passed null params");
3018 ObjCImpls[IFaceD] = ImplD;
3019}
3020
3021/// Set the implementation of ObjCCategoryDecl.
3023 ObjCCategoryImplDecl *ImplD) {
3024 assert(CatD && ImplD && "Passed null params");
3025 ObjCImpls[CatD] = ImplD;
3026}
3027
3028const ObjCMethodDecl *
3030 return ObjCMethodRedecls.lookup(MD);
3031}
3032
3034 const ObjCMethodDecl *Redecl) {
3035 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3036 ObjCMethodRedecls[MD] = Redecl;
3037}
3038
3040 const NamedDecl *ND) const {
3041 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3042 return ID;
3043 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3044 return CD->getClassInterface();
3045 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3046 return IMD->getClassInterface();
3047
3048 return nullptr;
3049}
3050
3051/// Get the copy initialization expression of VarDecl, or nullptr if
3052/// none exists.
3054 assert(VD && "Passed null params");
3055 assert(VD->hasAttr<BlocksAttr>() &&
3056 "getBlockVarCopyInits - not __block var");
3057 auto I = BlockVarCopyInits.find(VD);
3058 if (I != BlockVarCopyInits.end())
3059 return I->second;
3060 return {nullptr, false};
3061}
3062
3063/// Set the copy initialization expression of a block var decl.
3065 bool CanThrow) {
3066 assert(VD && CopyExpr && "Passed null params");
3067 assert(VD->hasAttr<BlocksAttr>() &&
3068 "setBlockVarCopyInits - not __block var");
3069 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3070}
3071
3073 unsigned DataSize) const {
3074 if (!DataSize)
3076 else
3077 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3078 "incorrect data size provided to CreateTypeSourceInfo!");
3079
3080 auto *TInfo =
3081 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3082 new (TInfo) TypeSourceInfo(T, DataSize);
3083 return TInfo;
3084}
3085
3087 SourceLocation L) const {
3089 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3090 return DI;
3091}
3092
3093const ASTRecordLayout &
3095 return getObjCLayout(D, nullptr);
3096}
3097
3098const ASTRecordLayout &
3100 const ObjCImplementationDecl *D) const {
3101 return getObjCLayout(D->getClassInterface(), D);
3102}
3103
3106 bool &AnyNonCanonArgs) {
3107 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3108 for (auto &Arg : CanonArgs) {
3109 TemplateArgument OrigArg = Arg;
3110 Arg = C.getCanonicalTemplateArgument(Arg);
3111 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3112 }
3113 return CanonArgs;
3114}
3115
3116//===----------------------------------------------------------------------===//
3117// Type creation/memoization methods
3118//===----------------------------------------------------------------------===//
3119
3121ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3122 unsigned fastQuals = quals.getFastQualifiers();
3123 quals.removeFastQualifiers();
3124
3125 // Check if we've already instantiated this type.
3126 llvm::FoldingSetNodeID ID;
3127 ExtQuals::Profile(ID, baseType, quals);
3128 void *insertPos = nullptr;
3129 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3130 assert(eq->getQualifiers() == quals);
3131 return QualType(eq, fastQuals);
3132 }
3133
3134 // If the base type is not canonical, make the appropriate canonical type.
3135 QualType canon;
3136 if (!baseType->isCanonicalUnqualified()) {
3137 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3138 canonSplit.Quals.addConsistentQualifiers(quals);
3139 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3140
3141 // Re-find the insert position.
3142 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3143 }
3144
3145 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3146 ExtQualNodes.InsertNode(eq, insertPos);
3147 return QualType(eq, fastQuals);
3148}
3149
3151 LangAS AddressSpace) const {
3152 QualType CanT = getCanonicalType(T);
3153 if (CanT.getAddressSpace() == AddressSpace)
3154 return T;
3155
3156 // If we are composing extended qualifiers together, merge together
3157 // into one ExtQuals node.
3158 QualifierCollector Quals;
3159 const Type *TypeNode = Quals.strip(T);
3160
3161 // If this type already has an address space specified, it cannot get
3162 // another one.
3163 assert(!Quals.hasAddressSpace() &&
3164 "Type cannot be in multiple addr spaces!");
3165 Quals.addAddressSpace(AddressSpace);
3166
3167 return getExtQualType(TypeNode, Quals);
3168}
3169
3171 // If the type is not qualified with an address space, just return it
3172 // immediately.
3173 if (!T.hasAddressSpace())
3174 return T;
3175
3176 QualifierCollector Quals;
3177 const Type *TypeNode;
3178 // For arrays, strip the qualifier off the element type, then reconstruct the
3179 // array type
3180 if (T.getTypePtr()->isArrayType()) {
3181 T = getUnqualifiedArrayType(T, Quals);
3182 TypeNode = T.getTypePtr();
3183 } else {
3184 // If we are composing extended qualifiers together, merge together
3185 // into one ExtQuals node.
3186 while (T.hasAddressSpace()) {
3187 TypeNode = Quals.strip(T);
3188
3189 // If the type no longer has an address space after stripping qualifiers,
3190 // jump out.
3191 if (!QualType(TypeNode, 0).hasAddressSpace())
3192 break;
3193
3194 // There might be sugar in the way. Strip it and try again.
3195 T = T.getSingleStepDesugaredType(*this);
3196 }
3197 }
3198
3199 Quals.removeAddressSpace();
3200
3201 // Removal of the address space can mean there are no longer any
3202 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3203 // or required.
3204 if (Quals.hasNonFastQualifiers())
3205 return getExtQualType(TypeNode, Quals);
3206 else
3207 return QualType(TypeNode, Quals.getFastQualifiers());
3208}
3209
3210uint16_t
3212 assert(RD->isPolymorphic() &&
3213 "Attempted to get vtable pointer discriminator on a monomorphic type");
3214 std::unique_ptr<MangleContext> MC(createMangleContext());
3215 SmallString<256> Str;
3216 llvm::raw_svector_ostream Out(Str);
3217 MC->mangleCXXVTable(RD, Out);
3218 return llvm::getPointerAuthStableSipHash(Str);
3219}
3220
3221/// Encode a function type for use in the discriminator of a function pointer
3222/// type. We can't use the itanium scheme for this since C has quite permissive
3223/// rules for type compatibility that we need to be compatible with.
3224///
3225/// Formally, this function associates every function pointer type T with an
3226/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3227/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3228/// compatibility requires equivalent treatment under the ABI, so
3229/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3230/// a subset of ~. Crucially, however, it must be a proper subset because
3231/// CCompatible is not an equivalence relation: for example, int[] is compatible
3232/// with both int[1] and int[2], but the latter are not compatible with each
3233/// other. Therefore this encoding function must be careful to only distinguish
3234/// types if there is no third type with which they are both required to be
3235/// compatible.
3237 raw_ostream &OS, QualType QT) {
3238 // FIXME: Consider address space qualifiers.
3239 const Type *T = QT.getCanonicalType().getTypePtr();
3240
3241 // FIXME: Consider using the C++ type mangling when we encounter a construct
3242 // that is incompatible with C.
3243
3244 switch (T->getTypeClass()) {
3245 case Type::Atomic:
3247 Ctx, OS, cast<AtomicType>(T)->getValueType());
3248
3249 case Type::LValueReference:
3250 OS << "R";
3252 cast<ReferenceType>(T)->getPointeeType());
3253 return;
3254 case Type::RValueReference:
3255 OS << "O";
3257 cast<ReferenceType>(T)->getPointeeType());
3258 return;
3259
3260 case Type::Pointer:
3261 // C11 6.7.6.1p2:
3262 // For two pointer types to be compatible, both shall be identically
3263 // qualified and both shall be pointers to compatible types.
3264 // FIXME: we should also consider pointee types.
3265 OS << "P";
3266 return;
3267
3268 case Type::ObjCObjectPointer:
3269 case Type::BlockPointer:
3270 OS << "P";
3271 return;
3272
3273 case Type::Complex:
3274 OS << "C";
3276 Ctx, OS, cast<ComplexType>(T)->getElementType());
3277
3278 case Type::VariableArray:
3279 case Type::ConstantArray:
3280 case Type::IncompleteArray:
3281 case Type::ArrayParameter:
3282 // C11 6.7.6.2p6:
3283 // For two array types to be compatible, both shall have compatible
3284 // element types, and if both size specifiers are present, and are integer
3285 // constant expressions, then both size specifiers shall have the same
3286 // constant value [...]
3287 //
3288 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3289 // width of the array.
3290 OS << "A";
3292 Ctx, OS, cast<ArrayType>(T)->getElementType());
3293
3294 case Type::ObjCInterface:
3295 case Type::ObjCObject:
3296 OS << "<objc_object>";
3297 return;
3298
3299 case Type::Enum: {
3300 // C11 6.7.2.2p4:
3301 // Each enumerated type shall be compatible with char, a signed integer
3302 // type, or an unsigned integer type.
3303 //
3304 // So we have to treat enum types as integers.
3305 QualType UnderlyingType = cast<EnumType>(T)->getDecl()->getIntegerType();
3307 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3308 }
3309
3310 case Type::FunctionNoProto:
3311 case Type::FunctionProto: {
3312 // C11 6.7.6.3p15:
3313 // For two function types to be compatible, both shall specify compatible
3314 // return types. Moreover, the parameter type lists, if both are present,
3315 // shall agree in the number of parameters and in the use of the ellipsis
3316 // terminator; corresponding parameters shall have compatible types.
3317 //
3318 // That paragraph goes on to describe how unprototyped functions are to be
3319 // handled, which we ignore here. Unprototyped function pointers are hashed
3320 // as though they were prototyped nullary functions since thats probably
3321 // what the user meant. This behavior is non-conforming.
3322 // FIXME: If we add a "custom discriminator" function type attribute we
3323 // should encode functions as their discriminators.
3324 OS << "F";
3325 const auto *FuncType = cast<FunctionType>(T);
3326 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3327 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3328 for (QualType Param : FPT->param_types()) {
3329 Param = Ctx.getSignatureParameterType(Param);
3330 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3331 }
3332 if (FPT->isVariadic())
3333 OS << "z";
3334 }
3335 OS << "E";
3336 return;
3337 }
3338
3339 case Type::MemberPointer: {
3340 OS << "M";
3341 const auto *MPT = T->castAs<MemberPointerType>();
3342 encodeTypeForFunctionPointerAuth(Ctx, OS, QualType(MPT->getClass(), 0));
3343 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3344 return;
3345 }
3346 case Type::ExtVector:
3347 case Type::Vector:
3348 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3349 break;
3350
3351 // Don't bother discriminating based on these types.
3352 case Type::Pipe:
3353 case Type::BitInt:
3354 case Type::ConstantMatrix:
3355 OS << "?";
3356 return;
3357
3358 case Type::Builtin: {
3359 const auto *BTy = T->castAs<BuiltinType>();
3360 switch (BTy->getKind()) {
3361#define SIGNED_TYPE(Id, SingletonId) \
3362 case BuiltinType::Id: \
3363 OS << "i"; \
3364 return;
3365#define UNSIGNED_TYPE(Id, SingletonId) \
3366 case BuiltinType::Id: \
3367 OS << "i"; \
3368 return;
3369#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3370#define BUILTIN_TYPE(Id, SingletonId)
3371#include "clang/AST/BuiltinTypes.def"
3372 llvm_unreachable("placeholder types should not appear here.");
3373
3374 case BuiltinType::Half:
3375 OS << "Dh";
3376 return;
3377 case BuiltinType::Float:
3378 OS << "f";
3379 return;
3380 case BuiltinType::Double:
3381 OS << "d";
3382 return;
3383 case BuiltinType::LongDouble:
3384 OS << "e";
3385 return;
3386 case BuiltinType::Float16:
3387 OS << "DF16_";
3388 return;
3389 case BuiltinType::Float128:
3390 OS << "g";
3391 return;
3392
3393 case BuiltinType::Void:
3394 OS << "v";
3395 return;
3396
3397 case BuiltinType::ObjCId:
3398 case BuiltinType::ObjCClass:
3399 case BuiltinType::ObjCSel:
3400 case BuiltinType::NullPtr:
3401 OS << "P";
3402 return;
3403
3404 // Don't bother discriminating based on OpenCL types.
3405 case BuiltinType::OCLSampler:
3406 case BuiltinType::OCLEvent:
3407 case BuiltinType::OCLClkEvent:
3408 case BuiltinType::OCLQueue:
3409 case BuiltinType::OCLReserveID:
3410 case BuiltinType::BFloat16:
3411 case BuiltinType::VectorQuad:
3412 case BuiltinType::VectorPair:
3413 OS << "?";
3414 return;
3415
3416 // Don't bother discriminating based on these seldom-used types.
3417 case BuiltinType::Ibm128:
3418 return;
3419#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3420 case BuiltinType::Id: \
3421 return;
3422#include "clang/Basic/OpenCLImageTypes.def"
3423#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3424 case BuiltinType::Id: \
3425 return;
3426#include "clang/Basic/OpenCLExtensionTypes.def"
3427#define SVE_TYPE(Name, Id, SingletonId) \
3428 case BuiltinType::Id: \
3429 return;
3430#include "clang/Basic/AArch64SVEACLETypes.def"
3431#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3432 case BuiltinType::Id: \
3433 return;
3434#include "clang/Basic/HLSLIntangibleTypes.def"
3435 case BuiltinType::Dependent:
3436 llvm_unreachable("should never get here");
3437#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3438#include "clang/Basic/AMDGPUTypes.def"
3439 case BuiltinType::WasmExternRef:
3440#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3441#include "clang/Basic/RISCVVTypes.def"
3442 llvm_unreachable("not yet implemented");
3443 }
3444 llvm_unreachable("should never get here");
3445 }
3446 case Type::Record: {
3447 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
3448 const IdentifierInfo *II = RD->getIdentifier();
3449
3450 // In C++, an immediate typedef of an anonymous struct or union
3451 // is considered to name it for ODR purposes, but C's specification
3452 // of type compatibility does not have a similar rule. Using the typedef
3453 // name in function type discriminators anyway, as we do here,
3454 // therefore technically violates the C standard: two function pointer
3455 // types defined in terms of two typedef'd anonymous structs with
3456 // different names are formally still compatible, but we are assigning
3457 // them different discriminators and therefore incompatible ABIs.
3458 //
3459 // This is a relatively minor violation that significantly improves
3460 // discrimination in some cases and has not caused problems in
3461 // practice. Regardless, it is now part of the ABI in places where
3462 // function type discrimination is used, and it can no longer be
3463 // changed except on new platforms.
3464
3465 if (!II)
3466 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3467 II = Typedef->getDeclName().getAsIdentifierInfo();
3468
3469 if (!II) {
3470 OS << "<anonymous_record>";
3471 return;
3472 }
3473 OS << II->getLength() << II->getName();
3474 return;
3475 }
3476 case Type::HLSLAttributedResource:
3477 llvm_unreachable("should never get here");
3478 break;
3479 case Type::DeducedTemplateSpecialization:
3480 case Type::Auto:
3481#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3482#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3483#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3484#define ABSTRACT_TYPE(Class, Base)
3485#define TYPE(Class, Base)
3486#include "clang/AST/TypeNodes.inc"
3487 llvm_unreachable("unexpected non-canonical or dependent type!");
3488 return;
3489 }
3490}
3491
3493 assert(!T->isDependentType() &&
3494 "cannot compute type discriminator of a dependent type");
3495
3496 SmallString<256> Str;
3497 llvm::raw_svector_ostream Out(Str);
3498
3500 T = T->getPointeeType();
3501
3502 if (T->isFunctionType()) {
3504 } else {
3505 T = T.getUnqualifiedType();
3506 std::unique_ptr<MangleContext> MC(createMangleContext());
3507 MC->mangleCanonicalTypeName(T, Out);
3508 }
3509
3510 return llvm::getPointerAuthStableSipHash(Str);
3511}
3512
3514 Qualifiers::GC GCAttr) const {
3515 QualType CanT = getCanonicalType(T);
3516 if (CanT.getObjCGCAttr() == GCAttr)
3517 return T;
3518
3519 if (const auto *ptr = T->getAs<PointerType>()) {
3520 QualType Pointee = ptr->getPointeeType();
3521 if (Pointee->isAnyPointerType()) {
3522 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3523 return getPointerType(ResultType);
3524 }
3525 }
3526
3527 // If we are composing extended qualifiers together, merge together
3528 // into one ExtQuals node.
3529 QualifierCollector Quals;
3530 const Type *TypeNode = Quals.strip(T);
3531
3532 // If this type already has an ObjCGC specified, it cannot get
3533 // another one.
3534 assert(!Quals.hasObjCGCAttr() &&
3535 "Type cannot have multiple ObjCGCs!");
3536 Quals.addObjCGCAttr(GCAttr);
3537
3538 return getExtQualType(TypeNode, Quals);
3539}
3540
3542 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3543 QualType Pointee = Ptr->getPointeeType();
3544 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3545 return getPointerType(removeAddrSpaceQualType(Pointee));
3546 }
3547 }
3548 return T;
3549}
3550
3552 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3553 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3554 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3555
3556 llvm::FoldingSetNodeID ID;
3557 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3558
3559 void *InsertPos = nullptr;
3560 CountAttributedType *CATy =
3561 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3562 if (CATy)
3563 return QualType(CATy, 0);
3564
3565 QualType CanonTy = getCanonicalType(WrappedTy);
3566 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3567 DependentDecls.size());
3569 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3570 OrNull, DependentDecls);
3571 Types.push_back(CATy);
3572 CountAttributedTypes.InsertNode(CATy, InsertPos);
3573
3574 return QualType(CATy, 0);
3575}
3576
3579 llvm::function_ref<QualType(QualType)> Adjust) const {
3580 switch (Orig->getTypeClass()) {
3581 case Type::Attributed: {
3582 const auto *AT = cast<AttributedType>(Orig);
3583 return getAttributedType(AT->getAttrKind(),
3584 adjustType(AT->getModifiedType(), Adjust),
3585 adjustType(AT->getEquivalentType(), Adjust),
3586 AT->getAttr());
3587 }
3588
3589 case Type::BTFTagAttributed: {
3590 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3591 return getBTFTagAttributedType(BTFT->getAttr(),
3592 adjustType(BTFT->getWrappedType(), Adjust));
3593 }
3594
3595 case Type::Elaborated: {
3596 const auto *ET = cast<ElaboratedType>(Orig);
3597 return getElaboratedType(ET->getKeyword(), ET->getQualifier(),
3598 adjustType(ET->getNamedType(), Adjust));
3599 }
3600
3601 case Type::Paren:
3602 return getParenType(
3603 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3604
3605 case Type::Adjusted: {
3606 const auto *AT = cast<AdjustedType>(Orig);
3607 return getAdjustedType(AT->getOriginalType(),
3608 adjustType(AT->getAdjustedType(), Adjust));
3609 }
3610
3611 case Type::MacroQualified: {
3612 const auto *MQT = cast<MacroQualifiedType>(Orig);
3613 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3614 MQT->getMacroIdentifier());
3615 }
3616
3617 default:
3618 return Adjust(Orig);
3619 }
3620}
3621
3623 FunctionType::ExtInfo Info) {
3624 if (T->getExtInfo() == Info)
3625 return T;
3626
3628 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3629 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3630 } else {
3631 const auto *FPT = cast<FunctionProtoType>(T);
3632 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3633 EPI.ExtInfo = Info;
3634 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3635 }
3636
3637 return cast<FunctionType>(Result.getTypePtr());
3638}
3639
3641 QualType ResultType) {
3642 return adjustType(FunctionType, [&](QualType Orig) {
3643 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3644 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3645
3646 const auto *FPT = Orig->castAs<FunctionProtoType>();
3647 return getFunctionType(ResultType, FPT->getParamTypes(),
3648 FPT->getExtProtoInfo());
3649 });
3650}
3651
3653 QualType ResultType) {
3654 FD = FD->getMostRecentDecl();
3655 while (true) {
3656 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3657 if (FunctionDecl *Next = FD->getPreviousDecl())
3658 FD = Next;
3659 else
3660 break;
3661 }
3663 L->DeducedReturnType(FD, ResultType);
3664}
3665
3666/// Get a function type and produce the equivalent function type with the
3667/// specified exception specification. Type sugar that can be present on a
3668/// declaration of a function with an exception specification is permitted
3669/// and preserved. Other type sugar (for instance, typedefs) is not.
3671 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3672 return adjustType(Orig, [&](QualType Ty) {
3673 const auto *Proto = Ty->castAs<FunctionProtoType>();
3674 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3675 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3676 });
3677}
3678
3680 QualType U) const {
3681 return hasSameType(T, U) ||
3682 (getLangOpts().CPlusPlus17 &&
3685}
3686
3688 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3689 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3690 SmallVector<QualType, 16> Args(Proto->param_types().size());
3691 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3692 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3693 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3694 }
3695
3696 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3697 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3698 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3699 }
3700
3701 return T;
3702}
3703
3705 return hasSameType(T, U) ||
3708}
3709
3711 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3712 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3713 EPI.ExtParameterInfos = nullptr;
3714 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3715 }
3716 return T;
3717}
3718
3720 QualType U) const {
3723}
3724
3727 bool AsWritten) {
3728 // Update the type.
3729 QualType Updated =
3731 FD->setType(Updated);
3732
3733 if (!AsWritten)
3734 return;
3735
3736 // Update the type in the type source information too.
3737 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3738 // If the type and the type-as-written differ, we may need to update
3739 // the type-as-written too.
3740 if (TSInfo->getType() != FD->getType())
3741 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3742
3743 // FIXME: When we get proper type location information for exceptions,
3744 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3745 // up the TypeSourceInfo;
3746 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3747 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3748 "TypeLoc size mismatch from updating exception specification");
3749 TSInfo->overrideType(Updated);
3750 }
3751}
3752
3753/// getComplexType - Return the uniqued reference to the type for a complex
3754/// number with the specified element type.
3756 // Unique pointers, to guarantee there is only one pointer of a particular
3757 // structure.
3758 llvm::FoldingSetNodeID ID;
3760
3761 void *InsertPos = nullptr;
3762 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3763 return QualType(CT, 0);
3764
3765 // If the pointee type isn't canonical, this won't be a canonical type either,
3766 // so fill in the canonical type field.
3767 QualType Canonical;
3768 if (!T.isCanonical()) {
3769 Canonical = getComplexType(getCanonicalType(T));
3770
3771 // Get the new insert position for the node we care about.
3772 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3773 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3774 }
3775 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3776 Types.push_back(New);
3777 ComplexTypes.InsertNode(New, InsertPos);
3778 return QualType(New, 0);
3779}
3780
3781/// getPointerType - Return the uniqued reference to the type for a pointer to
3782/// the specified type.
3784 // Unique pointers, to guarantee there is only one pointer of a particular
3785 // structure.
3786 llvm::FoldingSetNodeID ID;
3788
3789 void *InsertPos = nullptr;
3790 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3791 return QualType(PT, 0);
3792
3793 // If the pointee type isn't canonical, this won't be a canonical type either,
3794 // so fill in the canonical type field.
3795 QualType Canonical;
3796 if (!T.isCanonical()) {
3797 Canonical = getPointerType(getCanonicalType(T));
3798
3799 // Get the new insert position for the node we care about.
3800 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3801 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3802 }
3803 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3804 Types.push_back(New);
3805 PointerTypes.InsertNode(New, InsertPos);
3806 return QualType(New, 0);
3807}
3808
3810 llvm::FoldingSetNodeID ID;
3811 AdjustedType::Profile(ID, Orig, New);
3812 void *InsertPos = nullptr;
3813 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3814 if (AT)
3815 return QualType(AT, 0);
3816
3817 QualType Canonical = getCanonicalType(New);
3818
3819 // Get the new insert position for the node we care about.
3820 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3821 assert(!AT && "Shouldn't be in the map!");
3822
3823 AT = new (*this, alignof(AdjustedType))
3824 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3825 Types.push_back(AT);
3826 AdjustedTypes.InsertNode(AT, InsertPos);
3827 return QualType(AT, 0);
3828}
3829
3831 llvm::FoldingSetNodeID ID;
3832 AdjustedType::Profile(ID, Orig, Decayed);
3833 void *InsertPos = nullptr;
3834 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3835 if (AT)
3836 return QualType(AT, 0);
3837
3838 QualType Canonical = getCanonicalType(Decayed);
3839
3840 // Get the new insert position for the node we care about.
3841 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3842 assert(!AT && "Shouldn't be in the map!");
3843
3844 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3845 Types.push_back(AT);
3846 AdjustedTypes.InsertNode(AT, InsertPos);
3847 return QualType(AT, 0);
3848}
3849
3851 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3852
3853 QualType Decayed;
3854
3855 // C99 6.7.5.3p7:
3856 // A declaration of a parameter as "array of type" shall be
3857 // adjusted to "qualified pointer to type", where the type
3858 // qualifiers (if any) are those specified within the [ and ] of
3859 // the array type derivation.
3860 if (T->isArrayType())
3861 Decayed = getArrayDecayedType(T);
3862
3863 // C99 6.7.5.3p8:
3864 // A declaration of a parameter as "function returning type"
3865 // shall be adjusted to "pointer to function returning type", as
3866 // in 6.3.2.1.
3867 if (T->isFunctionType())
3868 Decayed = getPointerType(T);
3869
3870 return getDecayedType(T, Decayed);
3871}
3872
3874 if (Ty->isArrayParameterType())
3875 return Ty;
3876 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
3877 const auto *ATy = cast<ConstantArrayType>(Ty);
3878 llvm::FoldingSetNodeID ID;
3879 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
3880 ATy->getSizeExpr(), ATy->getSizeModifier(),
3881 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
3882 void *InsertPos = nullptr;
3883 ArrayParameterType *AT =
3884 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3885 if (AT)
3886 return QualType(AT, 0);
3887
3888 QualType Canonical;
3889 if (!Ty.isCanonical()) {
3890 Canonical = getArrayParameterType(getCanonicalType(Ty));
3891
3892 // Get the new insert position for the node we care about.
3893 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3894 assert(!AT && "Shouldn't be in the map!");
3895 }
3896
3897 AT = new (*this, alignof(ArrayParameterType))
3898 ArrayParameterType(ATy, Canonical);
3899 Types.push_back(AT);
3900 ArrayParameterTypes.InsertNode(AT, InsertPos);
3901 return QualType(AT, 0);
3902}
3903
3904/// getBlockPointerType - Return the uniqued reference to the type for
3905/// a pointer to the specified block.
3907 assert(T->isFunctionType() && "block of function types only");
3908 // Unique pointers, to guarantee there is only one block of a particular
3909 // structure.
3910 llvm::FoldingSetNodeID ID;
3912
3913 void *InsertPos = nullptr;
3914 if (BlockPointerType *PT =
3915 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3916 return QualType(PT, 0);
3917
3918 // If the block pointee type isn't canonical, this won't be a canonical
3919 // type either so fill in the canonical type field.
3920 QualType Canonical;
3921 if (!T.isCanonical()) {
3923
3924 // Get the new insert position for the node we care about.
3925 BlockPointerType *NewIP =
3926 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3927 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3928 }
3929 auto *New =
3930 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
3931 Types.push_back(New);
3932 BlockPointerTypes.InsertNode(New, InsertPos);
3933 return QualType(New, 0);
3934}
3935
3936/// getLValueReferenceType - Return the uniqued reference to the type for an
3937/// lvalue reference to the specified type.
3939ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3940 assert((!T->isPlaceholderType() ||
3941 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3942 "Unresolved placeholder type");
3943
3944 // Unique pointers, to guarantee there is only one pointer of a particular
3945 // structure.
3946 llvm::FoldingSetNodeID ID;
3947 ReferenceType::Profile(ID, T, SpelledAsLValue);
3948
3949 void *InsertPos = nullptr;
3950 if (LValueReferenceType *RT =
3951 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3952 return QualType(RT, 0);
3953
3954 const auto *InnerRef = T->getAs<ReferenceType>();
3955
3956 // If the referencee type isn't canonical, this won't be a canonical type
3957 // either, so fill in the canonical type field.
3958 QualType Canonical;
3959 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3960 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3961 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3962
3963 // Get the new insert position for the node we care about.
3964 LValueReferenceType *NewIP =
3965 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3966 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3967 }
3968
3969 auto *New = new (*this, alignof(LValueReferenceType))
3970 LValueReferenceType(T, Canonical, SpelledAsLValue);
3971 Types.push_back(New);
3972 LValueReferenceTypes.InsertNode(New, InsertPos);
3973
3974 return QualType(New, 0);
3975}
3976
3977/// getRValueReferenceType - Return the uniqued reference to the type for an
3978/// rvalue reference to the specified type.
3980 assert((!T->isPlaceholderType() ||
3981 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3982 "Unresolved placeholder type");
3983
3984 // Unique pointers, to guarantee there is only one pointer of a particular
3985 // structure.
3986 llvm::FoldingSetNodeID ID;
3987 ReferenceType::Profile(ID, T, false);
3988
3989 void *InsertPos = nullptr;
3990 if (RValueReferenceType *RT =
3991 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3992 return QualType(RT, 0);
3993
3994 const auto *InnerRef = T->getAs<ReferenceType>();
3995
3996 // If the referencee type isn't canonical, this won't be a canonical type
3997 // either, so fill in the canonical type field.
3998 QualType Canonical;
3999 if (InnerRef || !T.isCanonical()) {
4000 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4001 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4002
4003 // Get the new insert position for the node we care about.
4004 RValueReferenceType *NewIP =
4005 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4006 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4007 }
4008
4009 auto *New = new (*this, alignof(RValueReferenceType))
4010 RValueReferenceType(T, Canonical);
4011 Types.push_back(New);
4012 RValueReferenceTypes.InsertNode(New, InsertPos);
4013 return QualType(New, 0);
4014}
4015
4016/// getMemberPointerType - Return the uniqued reference to the type for a
4017/// member pointer to the specified type, in the specified class.
4019 // Unique pointers, to guarantee there is only one pointer of a particular
4020 // structure.
4021 llvm::FoldingSetNodeID ID;
4022 MemberPointerType::Profile(ID, T, Cls);
4023
4024 void *InsertPos = nullptr;
4025 if (MemberPointerType *PT =
4026 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4027 return QualType(PT, 0);
4028
4029 // If the pointee or class type isn't canonical, this won't be a canonical
4030 // type either, so fill in the canonical type field.
4031 QualType Canonical;
4032 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
4034
4035 // Get the new insert position for the node we care about.
4036 MemberPointerType *NewIP =
4037 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4038 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4039 }
4040 auto *New = new (*this, alignof(MemberPointerType))
4041 MemberPointerType(T, Cls, Canonical);
4042 Types.push_back(New);
4043 MemberPointerTypes.InsertNode(New, InsertPos);
4044 return QualType(New, 0);
4045}
4046
4047/// getConstantArrayType - Return the unique reference to the type for an
4048/// array of the specified element type.
4050 const llvm::APInt &ArySizeIn,
4051 const Expr *SizeExpr,
4053 unsigned IndexTypeQuals) const {
4054 assert((EltTy->isDependentType() ||
4055 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4056 "Constant array of VLAs is illegal!");
4057
4058 // We only need the size as part of the type if it's instantiation-dependent.
4059 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4060 SizeExpr = nullptr;
4061
4062 // Convert the array size into a canonical width matching the pointer size for
4063 // the target.
4064 llvm::APInt ArySize(ArySizeIn);
4065 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4066
4067 llvm::FoldingSetNodeID ID;
4068 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4069 ASM, IndexTypeQuals);
4070
4071 void *InsertPos = nullptr;
4072 if (ConstantArrayType *ATP =
4073 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4074 return QualType(ATP, 0);
4075
4076 // If the element type isn't canonical or has qualifiers, or the array bound
4077 // is instantiation-dependent, this won't be a canonical type either, so fill
4078 // in the canonical type field.
4079 QualType Canon;
4080 // FIXME: Check below should look for qualifiers behind sugar.
4081 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4082 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4083 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4084 ASM, IndexTypeQuals);
4085 Canon = getQualifiedType(Canon, canonSplit.Quals);
4086
4087 // Get the new insert position for the node we care about.
4088 ConstantArrayType *NewIP =
4089 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4090 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4091 }
4092
4093 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4094 ASM, IndexTypeQuals);
4095 ConstantArrayTypes.InsertNode(New, InsertPos);
4096 Types.push_back(New);
4097 return QualType(New, 0);
4098}
4099
4100/// getVariableArrayDecayedType - Turns the given type, which may be
4101/// variably-modified, into the corresponding type with all the known
4102/// sizes replaced with [*].
4104 // Vastly most common case.
4105 if (!type->isVariablyModifiedType()) return type;
4106
4107 QualType result;
4108
4109 SplitQualType split = type.getSplitDesugaredType();
4110 const Type *ty = split.Ty;
4111 switch (ty->getTypeClass()) {
4112#define TYPE(Class, Base)
4113#define ABSTRACT_TYPE(Class, Base)
4114#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4115#include "clang/AST/TypeNodes.inc"
4116 llvm_unreachable("didn't desugar past all non-canonical types?");
4117
4118 // These types should never be variably-modified.
4119 case Type::Builtin:
4120 case Type::Complex:
4121 case Type::Vector:
4122 case Type::DependentVector:
4123 case Type::ExtVector:
4124 case Type::DependentSizedExtVector:
4125 case Type::ConstantMatrix:
4126 case Type::DependentSizedMatrix:
4127 case Type::DependentAddressSpace:
4128 case Type::ObjCObject:
4129 case Type::ObjCInterface:
4130 case Type::ObjCObjectPointer:
4131 case Type::Record:
4132 case Type::Enum:
4133 case Type::UnresolvedUsing:
4134 case Type::TypeOfExpr:
4135 case Type::TypeOf:
4136 case Type::Decltype:
4137 case Type::UnaryTransform:
4138 case Type::DependentName:
4139 case Type::InjectedClassName:
4140 case Type::TemplateSpecialization:
4141 case Type::DependentTemplateSpecialization:
4142 case Type::TemplateTypeParm:
4143 case Type::SubstTemplateTypeParmPack:
4144 case Type::Auto:
4145 case Type::DeducedTemplateSpecialization:
4146 case Type::PackExpansion:
4147 case Type::PackIndexing:
4148 case Type::BitInt:
4149 case Type::DependentBitInt:
4150 case Type::ArrayParameter:
4151 case Type::HLSLAttributedResource:
4152 llvm_unreachable("type should never be variably-modified");
4153
4154 // These types can be variably-modified but should never need to
4155 // further decay.
4156 case Type::FunctionNoProto:
4157 case Type::FunctionProto:
4158 case Type::BlockPointer:
4159 case Type::MemberPointer:
4160 case Type::Pipe:
4161 return type;
4162
4163 // These types can be variably-modified. All these modifications
4164 // preserve structure except as noted by comments.
4165 // TODO: if we ever care about optimizing VLAs, there are no-op
4166 // optimizations available here.
4167 case Type::Pointer:
4169 cast<PointerType>(ty)->getPointeeType()));
4170 break;
4171
4172 case Type::LValueReference: {
4173 const auto *lv = cast<LValueReferenceType>(ty);
4174 result = getLValueReferenceType(
4175 getVariableArrayDecayedType(lv->getPointeeType()),
4176 lv->isSpelledAsLValue());
4177 break;
4178 }
4179
4180 case Type::RValueReference: {
4181 const auto *lv = cast<RValueReferenceType>(ty);
4182 result = getRValueReferenceType(
4183 getVariableArrayDecayedType(lv->getPointeeType()));
4184 break;
4185 }
4186
4187 case Type::Atomic: {
4188 const auto *at = cast<AtomicType>(ty);
4189 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4190 break;
4191 }
4192
4193 case Type::ConstantArray: {
4194 const auto *cat = cast<ConstantArrayType>(ty);
4195 result = getConstantArrayType(
4196 getVariableArrayDecayedType(cat->getElementType()),
4197 cat->getSize(),
4198 cat->getSizeExpr(),
4199 cat->getSizeModifier(),
4200 cat->getIndexTypeCVRQualifiers());
4201 break;
4202 }
4203
4204 case Type::DependentSizedArray: {
4205 const auto *dat = cast<DependentSizedArrayType>(ty);
4207 getVariableArrayDecayedType(dat->getElementType()),
4208 dat->getSizeExpr(),
4209 dat->getSizeModifier(),
4210 dat->getIndexTypeCVRQualifiers(),
4211 dat->getBracketsRange());
4212 break;
4213 }
4214
4215 // Turn incomplete types into [*] types.
4216 case Type::IncompleteArray: {
4217 const auto *iat = cast<IncompleteArrayType>(ty);
4218 result =
4220 /*size*/ nullptr, ArraySizeModifier::Normal,
4221 iat->getIndexTypeCVRQualifiers(), SourceRange());
4222 break;
4223 }
4224
4225 // Turn VLA types into [*] types.
4226 case Type::VariableArray: {
4227 const auto *vat = cast<VariableArrayType>(ty);
4228 result = getVariableArrayType(
4229 getVariableArrayDecayedType(vat->getElementType()),
4230 /*size*/ nullptr, ArraySizeModifier::Star,
4231 vat->getIndexTypeCVRQualifiers(), vat->getBracketsRange());
4232 break;
4233 }
4234 }
4235
4236 // Apply the top-level qualifiers from the original.
4237 return getQualifiedType(result, split.Quals);
4238}
4239
4240/// getVariableArrayType - Returns a non-unique reference to the type for a
4241/// variable array of the specified element type.
4244 unsigned IndexTypeQuals,
4245 SourceRange Brackets) const {
4246 // Since we don't unique expressions, it isn't possible to unique VLA's
4247 // that have an expression provided for their size.
4248 QualType Canon;
4249
4250 // Be sure to pull qualifiers off the element type.
4251 // FIXME: Check below should look for qualifiers behind sugar.
4252 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4253 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4254 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4255 IndexTypeQuals, Brackets);
4256 Canon = getQualifiedType(Canon, canonSplit.Quals);
4257 }
4258
4259 auto *New = new (*this, alignof(VariableArrayType))
4260 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
4261
4262 VariableArrayTypes.push_back(New);
4263 Types.push_back(New);
4264 return QualType(New, 0);
4265}
4266
4267/// getDependentSizedArrayType - Returns a non-unique reference to
4268/// the type for a dependently-sized array of the specified element
4269/// type.
4271 Expr *numElements,
4273 unsigned elementTypeQuals,
4274 SourceRange brackets) const {
4275 assert((!numElements || numElements->isTypeDependent() ||
4276 numElements->isValueDependent()) &&
4277 "Size must be type- or value-dependent!");
4278
4279 SplitQualType canonElementType = getCanonicalType(elementType).split();
4280
4281 void *insertPos = nullptr;
4282 llvm::FoldingSetNodeID ID;
4284 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4285 ASM, elementTypeQuals, numElements);
4286
4287 // Look for an existing type with these properties.
4288 DependentSizedArrayType *canonTy =
4289 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4290
4291 // Dependently-sized array types that do not have a specified number
4292 // of elements will have their sizes deduced from a dependent
4293 // initializer.
4294 if (!numElements) {
4295 if (canonTy)
4296 return QualType(canonTy, 0);
4297
4298 auto *newType = new (*this, alignof(DependentSizedArrayType))
4299 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4300 elementTypeQuals, brackets);
4301 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4302 Types.push_back(newType);
4303 return QualType(newType, 0);
4304 }
4305
4306 // If we don't have one, build one.
4307 if (!canonTy) {
4308 canonTy = new (*this, alignof(DependentSizedArrayType))
4309 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4310 numElements, ASM, elementTypeQuals, brackets);
4311 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4312 Types.push_back(canonTy);
4313 }
4314
4315 // Apply qualifiers from the element type to the array.
4316 QualType canon = getQualifiedType(QualType(canonTy,0),
4317 canonElementType.Quals);
4318
4319 // If we didn't need extra canonicalization for the element type or the size
4320 // expression, then just use that as our result.
4321 if (QualType(canonElementType.Ty, 0) == elementType &&
4322 canonTy->getSizeExpr() == numElements)
4323 return canon;
4324
4325 // Otherwise, we need to build a type which follows the spelling
4326 // of the element type.
4327 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4328 DependentSizedArrayType(elementType, canon, numElements, ASM,
4329 elementTypeQuals, brackets);
4330 Types.push_back(sugaredType);
4331 return QualType(sugaredType, 0);
4332}
4333
4336 unsigned elementTypeQuals) const {
4337 llvm::FoldingSetNodeID ID;
4338 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4339
4340 void *insertPos = nullptr;
4341 if (IncompleteArrayType *iat =
4342 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4343 return QualType(iat, 0);
4344
4345 // If the element type isn't canonical, this won't be a canonical type
4346 // either, so fill in the canonical type field. We also have to pull
4347 // qualifiers off the element type.
4348 QualType canon;
4349
4350 // FIXME: Check below should look for qualifiers behind sugar.
4351 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4352 SplitQualType canonSplit = getCanonicalType(elementType).split();
4353 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4354 ASM, elementTypeQuals);
4355 canon = getQualifiedType(canon, canonSplit.Quals);
4356
4357 // Get the new insert position for the node we care about.
4358 IncompleteArrayType *existing =
4359 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4360 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4361 }
4362
4363 auto *newType = new (*this, alignof(IncompleteArrayType))
4364 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4365
4366 IncompleteArrayTypes.InsertNode(newType, insertPos);
4367 Types.push_back(newType);
4368 return QualType(newType, 0);
4369}
4370
4373#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4374 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4375 NUMVECTORS};
4376
4377#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4378 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4379
4380 switch (Ty->getKind()) {
4381 default:
4382 llvm_unreachable("Unsupported builtin vector type");
4383
4384#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4385 ElBits, NF, IsSigned) \
4386 case BuiltinType::Id: \
4387 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4388 llvm::ElementCount::getScalable(NumEls), NF};
4389#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4390 ElBits, NF) \
4391 case BuiltinType::Id: \
4392 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4393 llvm::ElementCount::getScalable(NumEls), NF};
4394#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4395 ElBits, NF) \
4396 case BuiltinType::Id: \
4397 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4398#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4399 case BuiltinType::Id: \
4400 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4401#define AARCH64_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4402 ElBits, NF) \
4403 case BuiltinType::Id: \
4404 return {getIntTypeForBitwidth(ElBits, false), \
4405 llvm::ElementCount::getFixed(NumEls), NF};
4406#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId)
4407#include "clang/Basic/AArch64SVEACLETypes.def"
4408
4409#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4410 IsSigned) \
4411 case BuiltinType::Id: \
4412 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4413 llvm::ElementCount::getScalable(NumEls), NF};
4414#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4415 case BuiltinType::Id: \
4416 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4417 llvm::ElementCount::getScalable(NumEls), NF};
4418#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4419 case BuiltinType::Id: \
4420 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4421#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4422 case BuiltinType::Id: \
4423 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4424#include "clang/Basic/RISCVVTypes.def"
4425 }
4426}
4427
4428/// getExternrefType - Return a WebAssembly externref type, which represents an
4429/// opaque reference to a host value.
4431 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4432#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4433 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4434 return SingletonId;
4435#include "clang/Basic/WebAssemblyReferenceTypes.def"
4436 }
4437 llvm_unreachable(
4438 "shouldn't try to generate type externref outside WebAssembly target");
4439}
4440
4441/// getScalableVectorType - Return the unique reference to a scalable vector
4442/// type of the specified element type and size. VectorType must be a built-in
4443/// type.
4445 unsigned NumFields) const {
4446 if (Target->hasAArch64SVETypes()) {
4447 uint64_t EltTySize = getTypeSize(EltTy);
4448
4449#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4450 ElBits, NF, IsSigned) \
4451 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4452 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4453 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4454 return SingletonId; \
4455 }
4456#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4457 ElBits, NF) \
4458 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4459 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4460 return SingletonId; \
4461 }
4462#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4463 ElBits, NF) \
4464 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4465 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4466 return SingletonId; \
4467 }
4468#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4469 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4470 return SingletonId;
4471#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId)
4472#define AARCH64_VECTOR_TYPE(Name, MangledName, Id, SingletonId)
4473#include "clang/Basic/AArch64SVEACLETypes.def"
4474 } else if (Target->hasRISCVVTypes()) {
4475 uint64_t EltTySize = getTypeSize(EltTy);
4476#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4477 IsFP, IsBF) \
4478 if (!EltTy->isBooleanType() && \
4479 ((EltTy->hasIntegerRepresentation() && \
4480 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4481 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4482 IsFP && !IsBF) || \
4483 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4484 IsBF && !IsFP)) && \
4485 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4486 return SingletonId;
4487#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4488 if (EltTy->isBooleanType() && NumElts == NumEls) \
4489 return SingletonId;
4490#include "clang/Basic/RISCVVTypes.def"
4491 }
4492 return QualType();
4493}
4494
4495/// getVectorType - Return the unique reference to a vector type of
4496/// the specified element type and size. VectorType must be a built-in type.
4498 VectorKind VecKind) const {
4499 assert(vecType->isBuiltinType() ||
4500 (vecType->isBitIntType() &&
4501 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4502 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4503 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4504
4505 // Check if we've already instantiated a vector of this type.
4506 llvm::FoldingSetNodeID ID;
4507 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4508
4509 void *InsertPos = nullptr;
4510 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4511 return QualType(VTP, 0);
4512
4513 // If the element type isn't canonical, this won't be a canonical type either,
4514 // so fill in the canonical type field.
4515 QualType Canonical;
4516 if (!vecType.isCanonical()) {
4517 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4518
4519 // Get the new insert position for the node we care about.
4520 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4521 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4522 }
4523 auto *New = new (*this, alignof(VectorType))
4524 VectorType(vecType, NumElts, Canonical, VecKind);
4525 VectorTypes.InsertNode(New, InsertPos);
4526 Types.push_back(New);
4527 return QualType(New, 0);
4528}
4529
4531 SourceLocation AttrLoc,
4532 VectorKind VecKind) const {
4533 llvm::FoldingSetNodeID ID;
4534 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4535 VecKind);
4536 void *InsertPos = nullptr;
4537 DependentVectorType *Canon =
4538 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4540
4541 if (Canon) {
4542 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4543 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4544 } else {
4545 QualType CanonVecTy = getCanonicalType(VecType);
4546 if (CanonVecTy == VecType) {
4547 New = new (*this, alignof(DependentVectorType))
4548 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4549
4550 DependentVectorType *CanonCheck =
4551 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4552 assert(!CanonCheck &&
4553 "Dependent-sized vector_size canonical type broken");
4554 (void)CanonCheck;
4555 DependentVectorTypes.InsertNode(New, InsertPos);
4556 } else {
4557 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4558 SourceLocation(), VecKind);
4559 New = new (*this, alignof(DependentVectorType))
4560 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4561 }
4562 }
4563
4564 Types.push_back(New);
4565 return QualType(New, 0);
4566}
4567
4568/// getExtVectorType - Return the unique reference to an extended vector type of
4569/// the specified element type and size. VectorType must be a built-in type.
4571 unsigned NumElts) const {
4572 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4573 (vecType->isBitIntType() &&
4574 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4575 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4576 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4577
4578 // Check if we've already instantiated a vector of this type.
4579 llvm::FoldingSetNodeID ID;
4580 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4582 void *InsertPos = nullptr;
4583 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4584 return QualType(VTP, 0);
4585
4586 // If the element type isn't canonical, this won't be a canonical type either,
4587 // so fill in the canonical type field.
4588 QualType Canonical;
4589 if (!vecType.isCanonical()) {
4590 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4591
4592 // Get the new insert position for the node we care about.
4593 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4594 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4595 }
4596 auto *New = new (*this, alignof(ExtVectorType))
4597 ExtVectorType(vecType, NumElts, Canonical);
4598 VectorTypes.InsertNode(New, InsertPos);
4599 Types.push_back(New);
4600 return QualType(New, 0);
4601}
4602
4605 Expr *SizeExpr,
4606 SourceLocation AttrLoc) const {
4607 llvm::FoldingSetNodeID ID;
4609 SizeExpr);
4610
4611 void *InsertPos = nullptr;
4613 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4615 if (Canon) {
4616 // We already have a canonical version of this array type; use it as
4617 // the canonical type for a newly-built type.
4618 New = new (*this, alignof(DependentSizedExtVectorType))
4619 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4620 AttrLoc);
4621 } else {
4622 QualType CanonVecTy = getCanonicalType(vecType);
4623 if (CanonVecTy == vecType) {
4624 New = new (*this, alignof(DependentSizedExtVectorType))
4625 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4626
4627 DependentSizedExtVectorType *CanonCheck
4628 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4629 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4630 (void)CanonCheck;
4631 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4632 } else {
4633 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4634 SourceLocation());
4635 New = new (*this, alignof(DependentSizedExtVectorType))
4636 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4637 }
4638 }
4639
4640 Types.push_back(New);
4641 return QualType(New, 0);
4642}
4643
4645 unsigned NumColumns) const {
4646 llvm::FoldingSetNodeID ID;
4647 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4648 Type::ConstantMatrix);
4649
4650 assert(MatrixType::isValidElementType(ElementTy) &&
4651 "need a valid element type");
4652 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4654 "need valid matrix dimensions");
4655 void *InsertPos = nullptr;
4656 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4657 return QualType(MTP, 0);
4658
4659 QualType Canonical;
4660 if (!ElementTy.isCanonical()) {
4661 Canonical =
4662 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4663
4664 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4665 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4666 (void)NewIP;
4667 }
4668
4669 auto *New = new (*this, alignof(ConstantMatrixType))
4670 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4671 MatrixTypes.InsertNode(New, InsertPos);
4672 Types.push_back(New);
4673 return QualType(New, 0);
4674}
4675
4677 Expr *RowExpr,
4678 Expr *ColumnExpr,
4679 SourceLocation AttrLoc) const {
4680 QualType CanonElementTy = getCanonicalType(ElementTy);
4681 llvm::FoldingSetNodeID ID;
4682 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4683 ColumnExpr);
4684
4685 void *InsertPos = nullptr;
4687 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4688
4689 if (!Canon) {
4690 Canon = new (*this, alignof(DependentSizedMatrixType))
4691 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4692 ColumnExpr, AttrLoc);
4693#ifndef NDEBUG
4694 DependentSizedMatrixType *CanonCheck =
4695 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4696 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4697#endif
4698 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4699 Types.push_back(Canon);
4700 }
4701
4702 // Already have a canonical version of the matrix type
4703 //
4704 // If it exactly matches the requested type, use it directly.
4705 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4706 Canon->getRowExpr() == ColumnExpr)
4707 return QualType(Canon, 0);
4708
4709 // Use Canon as the canonical type for newly-built type.
4710 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4711 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4712 ColumnExpr, AttrLoc);
4713 Types.push_back(New);
4714 return QualType(New, 0);
4715}
4716
4718 Expr *AddrSpaceExpr,
4719 SourceLocation AttrLoc) const {
4720 assert(AddrSpaceExpr->isInstantiationDependent());
4721
4722 QualType canonPointeeType = getCanonicalType(PointeeType);
4723
4724 void *insertPos = nullptr;
4725 llvm::FoldingSetNodeID ID;
4726 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4727 AddrSpaceExpr);
4728
4729 DependentAddressSpaceType *canonTy =
4730 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4731
4732 if (!canonTy) {
4733 canonTy = new (*this, alignof(DependentAddressSpaceType))
4734 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4735 AttrLoc);
4736 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4737 Types.push_back(canonTy);
4738 }
4739
4740 if (canonPointeeType == PointeeType &&
4741 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4742 return QualType(canonTy, 0);
4743
4744 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4745 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4746 AddrSpaceExpr, AttrLoc);
4747 Types.push_back(sugaredType);
4748 return QualType(sugaredType, 0);
4749}
4750
4751/// Determine whether \p T is canonical as the result type of a function.
4753 return T.isCanonical() &&
4754 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4755 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4756}
4757
4758/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4761 const FunctionType::ExtInfo &Info) const {
4762 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4763 // functionality creates a function without a prototype regardless of
4764 // language mode (so it makes them even in C++). Once the rewriter has been
4765 // fixed, this assertion can be enabled again.
4766 //assert(!LangOpts.requiresStrictPrototypes() &&
4767 // "strict prototypes are disabled");
4768
4769 // Unique functions, to guarantee there is only one function of a particular
4770 // structure.
4771 llvm::FoldingSetNodeID ID;
4772 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4773
4774 void *InsertPos = nullptr;
4775 if (FunctionNoProtoType *FT =
4776 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4777 return QualType(FT, 0);
4778
4779 QualType Canonical;
4780 if (!isCanonicalResultType(ResultTy)) {
4781 Canonical =
4783
4784 // Get the new insert position for the node we care about.
4785 FunctionNoProtoType *NewIP =
4786 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4787 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4788 }
4789
4790 auto *New = new (*this, alignof(FunctionNoProtoType))
4791 FunctionNoProtoType(ResultTy, Canonical, Info);
4792 Types.push_back(New);
4793 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4794 return QualType(New, 0);
4795}
4796
4799 CanQualType CanResultType = getCanonicalType(ResultType);
4800
4801 // Canonical result types do not have ARC lifetime qualifiers.
4802 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4803 Qualifiers Qs = CanResultType.getQualifiers();
4804 Qs.removeObjCLifetime();
4806 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4807 }
4808
4809 return CanResultType;
4810}
4811
4813 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4814 if (ESI.Type == EST_None)
4815 return true;
4816 if (!NoexceptInType)
4817 return false;
4818
4819 // C++17 onwards: exception specification is part of the type, as a simple
4820 // boolean "can this function type throw".
4821 if (ESI.Type == EST_BasicNoexcept)
4822 return true;
4823
4824 // A noexcept(expr) specification is (possibly) canonical if expr is
4825 // value-dependent.
4826 if (ESI.Type == EST_DependentNoexcept)
4827 return true;
4828
4829 // A dynamic exception specification is canonical if it only contains pack
4830 // expansions (so we can't tell whether it's non-throwing) and all its
4831 // contained types are canonical.
4832 if (ESI.Type == EST_Dynamic) {
4833 bool AnyPackExpansions = false;
4834 for (QualType ET : ESI.Exceptions) {
4835 if (!ET.isCanonical())
4836 return false;
4837 if (ET->getAs<PackExpansionType>())
4838 AnyPackExpansions = true;
4839 }
4840 return AnyPackExpansions;
4841 }
4842
4843 return false;
4844}
4845
4846QualType ASTContext::getFunctionTypeInternal(
4847 QualType ResultTy, ArrayRef<QualType> ArgArray,
4848 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4849 size_t NumArgs = ArgArray.size();
4850
4851 // Unique functions, to guarantee there is only one function of a particular
4852 // structure.
4853 llvm::FoldingSetNodeID ID;
4854 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4855 *this, true);
4856
4857 QualType Canonical;
4858 bool Unique = false;
4859
4860 void *InsertPos = nullptr;
4861 if (FunctionProtoType *FPT =
4862 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4863 QualType Existing = QualType(FPT, 0);
4864
4865 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4866 // it so long as our exception specification doesn't contain a dependent
4867 // noexcept expression, or we're just looking for a canonical type.
4868 // Otherwise, we're going to need to create a type
4869 // sugar node to hold the concrete expression.
4870 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4871 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4872 return Existing;
4873
4874 // We need a new type sugar node for this one, to hold the new noexcept
4875 // expression. We do no canonicalization here, but that's OK since we don't
4876 // expect to see the same noexcept expression much more than once.
4877 Canonical = getCanonicalType(Existing);
4878 Unique = true;
4879 }
4880
4881 bool NoexceptInType = getLangOpts().CPlusPlus17;
4882 bool IsCanonicalExceptionSpec =
4884
4885 // Determine whether the type being created is already canonical or not.
4886 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4887 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4888 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4889 if (!ArgArray[i].isCanonicalAsParam())
4890 isCanonical = false;
4891
4892 if (OnlyWantCanonical)
4893 assert(isCanonical &&
4894 "given non-canonical parameters constructing canonical type");
4895
4896 // If this type isn't canonical, get the canonical version of it if we don't
4897 // already have it. The exception spec is only partially part of the
4898 // canonical type, and only in C++17 onwards.
4899 if (!isCanonical && Canonical.isNull()) {
4900 SmallVector<QualType, 16> CanonicalArgs;
4901 CanonicalArgs.reserve(NumArgs);
4902 for (unsigned i = 0; i != NumArgs; ++i)
4903 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4904
4905 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4906 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4907 CanonicalEPI.HasTrailingReturn = false;
4908
4909 if (IsCanonicalExceptionSpec) {
4910 // Exception spec is already OK.
4911 } else if (NoexceptInType) {
4912 switch (EPI.ExceptionSpec.Type) {
4914 // We don't know yet. It shouldn't matter what we pick here; no-one
4915 // should ever look at this.
4916 [[fallthrough]];
4917 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4918 CanonicalEPI.ExceptionSpec.Type = EST_None;
4919 break;
4920
4921 // A dynamic exception specification is almost always "not noexcept",
4922 // with the exception that a pack expansion might expand to no types.
4923 case EST_Dynamic: {
4924 bool AnyPacks = false;
4925 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4926 if (ET->getAs<PackExpansionType>())
4927 AnyPacks = true;
4928 ExceptionTypeStorage.push_back(getCanonicalType(ET));
4929 }
4930 if (!AnyPacks)
4931 CanonicalEPI.ExceptionSpec.Type = EST_None;
4932 else {
4933 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4934 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4935 }
4936 break;
4937 }
4938
4939 case EST_DynamicNone:
4940 case EST_BasicNoexcept:
4941 case EST_NoexceptTrue:
4942 case EST_NoThrow:
4943 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4944 break;
4945
4947 llvm_unreachable("dependent noexcept is already canonical");
4948 }
4949 } else {
4951 }
4952
4953 // Adjust the canonical function result type.
4954 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4955 Canonical =
4956 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4957
4958 // Get the new insert position for the node we care about.
4959 FunctionProtoType *NewIP =
4960 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4961 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4962 }
4963
4964 // Compute the needed size to hold this FunctionProtoType and the
4965 // various trailing objects.
4966 auto ESH = FunctionProtoType::getExceptionSpecSize(
4967 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4968 size_t Size = FunctionProtoType::totalSizeToAlloc<
4974 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
4975 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4976 EPI.ExtParameterInfos ? NumArgs : 0,
4978 EPI.FunctionEffects.conditions().size());
4979
4980 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
4982 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4983 Types.push_back(FTP);
4984 if (!Unique)
4985 FunctionProtoTypes.InsertNode(FTP, InsertPos);
4986 if (!EPI.FunctionEffects.empty())
4987 AnyFunctionEffects = true;
4988 return QualType(FTP, 0);
4989}
4990
4991QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4992 llvm::FoldingSetNodeID ID;
4993 PipeType::Profile(ID, T, ReadOnly);
4994
4995 void *InsertPos = nullptr;
4996 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4997 return QualType(PT, 0);
4998
4999 // If the pipe element type isn't canonical, this won't be a canonical type
5000 // either, so fill in the canonical type field.
5001 QualType Canonical;
5002 if (!T.isCanonical()) {
5003 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5004
5005 // Get the new insert position for the node we care about.
5006 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5007 assert(!NewIP && "Shouldn't be in the map!");
5008 (void)NewIP;
5009 }
5010 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5011 Types.push_back(New);
5012 PipeTypes.InsertNode(New, InsertPos);
5013 return QualType(New, 0);
5014}
5015
5017 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5018 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5019 : Ty;
5020}
5021
5023 return getPipeType(T, true);
5024}
5025
5027 return getPipeType(T, false);
5028}
5029
5030QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5031 llvm::FoldingSetNodeID ID;
5032 BitIntType::Profile(ID, IsUnsigned, NumBits);
5033
5034 void *InsertPos = nullptr;
5035 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5036 return QualType(EIT, 0);
5037
5038 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5039 BitIntTypes.InsertNode(New, InsertPos);
5040 Types.push_back(New);
5041 return QualType(New, 0);
5042}
5043
5045 Expr *NumBitsExpr) const {
5046 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5047 llvm::FoldingSetNodeID ID;
5048 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5049
5050 void *InsertPos = nullptr;
5051 if (DependentBitIntType *Existing =
5052 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5053 return QualType(Existing, 0);
5054
5055 auto *New = new (*this, alignof(DependentBitIntType))
5056 DependentBitIntType(IsUnsigned, NumBitsExpr);
5057 DependentBitIntTypes.InsertNode(New, InsertPos);
5058
5059 Types.push_back(New);
5060 return QualType(New, 0);
5061}
5062
5063#ifndef NDEBUG
5065 if (!isa<CXXRecordDecl>(D)) return false;
5066 const auto *RD = cast<CXXRecordDecl>(D);
5067 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
5068 return true;
5069 if (RD->getDescribedClassTemplate() &&
5070 !isa<ClassTemplateSpecializationDecl>(RD))
5071 return true;
5072 return false;
5073}
5074#endif
5075
5076/// getInjectedClassNameType - Return the unique reference to the
5077/// injected class name type for the specified templated declaration.
5079 QualType TST) const {
5081 if (Decl->TypeForDecl) {
5082 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
5083 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
5084 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
5085 Decl->TypeForDecl = PrevDecl->TypeForDecl;
5086 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
5087 } else {
5088 Type *newType = new (*this, alignof(InjectedClassNameType))
5090 Decl->TypeForDecl = newType;
5091 Types.push_back(newType);
5092 }
5093 return QualType(Decl->TypeForDecl, 0);
5094}
5095
5096/// getTypeDeclType - Return the unique reference to the type for the
5097/// specified type declaration.
5098QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
5099 assert(Decl && "Passed null for Decl param");
5100 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
5101
5102 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5103 return getTypedefType(Typedef);
5104
5105 assert(!isa<TemplateTypeParmDecl>(Decl) &&
5106 "Template type parameter types are always available.");
5107
5108 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
5109 assert(Record->isFirstDecl() && "struct/union has previous declaration");
5111 return getRecordType(Record);
5112 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
5113 assert(Enum->isFirstDecl() && "enum has previous declaration");
5114 return getEnumType(Enum);
5115 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
5116 return getUnresolvedUsingType(Using);
5117 } else
5118 llvm_unreachable("TypeDecl without a type?");
5119
5120 return QualType(Decl->TypeForDecl, 0);
5121}
5122
5123/// getTypedefType - Return the unique reference to the type for the
5124/// specified typedef name decl.
5126 QualType Underlying) const {
5127 if (!Decl->TypeForDecl) {
5128 if (Underlying.isNull())
5129 Underlying = Decl->getUnderlyingType();
5130 auto *NewType = new (*this, alignof(TypedefType)) TypedefType(
5131 Type::Typedef, Decl, QualType(), getCanonicalType(Underlying));
5132 Decl->TypeForDecl = NewType;
5133 Types.push_back(NewType);
5134 return QualType(NewType, 0);
5135 }
5136 if (Underlying.isNull() || Decl->getUnderlyingType() == Underlying)
5137 return QualType(Decl->TypeForDecl, 0);
5138 assert(hasSameType(Decl->getUnderlyingType(), Underlying));
5139
5140 llvm::FoldingSetNodeID ID;
5141 TypedefType::Profile(ID, Decl, Underlying);
5142
5143 void *InsertPos = nullptr;
5144 if (TypedefType *T = TypedefTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5145 assert(!T->typeMatchesDecl() &&
5146 "non-divergent case should be handled with TypeDecl");
5147 return QualType(T, 0);
5148 }
5149
5150 void *Mem = Allocate(TypedefType::totalSizeToAlloc<QualType>(true),
5151 alignof(TypedefType));
5152 auto *NewType = new (Mem) TypedefType(Type::Typedef, Decl, Underlying,
5153 getCanonicalType(Underlying));
5154 TypedefTypes.InsertNode(NewType, InsertPos);
5155 Types.push_back(NewType);
5156 return QualType(NewType, 0);
5157}
5158
5160 QualType Underlying) const {
5161 llvm::FoldingSetNodeID ID;
5162 UsingType::Profile(ID, Found, Underlying);
5163
5164 void *InsertPos = nullptr;
5165 if (UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5166 return QualType(T, 0);
5167
5168 const Type *TypeForDecl =
5169 cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl();
5170
5171 assert(!Underlying.hasLocalQualifiers());
5172 QualType Canon = Underlying->getCanonicalTypeInternal();
5173 assert(TypeForDecl->getCanonicalTypeInternal() == Canon);
5174
5175 if (Underlying.getTypePtr() == TypeForDecl)
5176 Underlying = QualType();
5177 void *Mem =
5178 Allocate(UsingType::totalSizeToAlloc<QualType>(!Underlying.isNull()),
5179 alignof(UsingType));
5180 UsingType *NewType = new (Mem) UsingType(Found, Underlying, Canon);
5181 Types.push_back(NewType);
5182 UsingTypes.InsertNode(NewType, InsertPos);
5183 return QualType(NewType, 0);
5184}
5185
5187 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
5188
5189 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
5190 if (PrevDecl->TypeForDecl)
5191 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
5192
5193 auto *newType = new (*this, alignof(RecordType)) RecordType(Decl);
5194 Decl->TypeForDecl = newType;
5195 Types.push_back(newType);
5196 return QualType(newType, 0);
5197}
5198
5200 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
5201
5202 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
5203 if (PrevDecl->TypeForDecl)
5204 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
5205
5206 auto *newType = new (*this, alignof(EnumType)) EnumType(Decl);
5207 Decl->TypeForDecl = newType;
5208 Types.push_back(newType);
5209 return QualType(newType, 0);
5210}
5211
5212bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5213 unsigned NumPositiveBits,
5214 QualType &BestType,
5215 QualType &BestPromotionType) {
5216 unsigned IntWidth = Target->getIntWidth();
5217 unsigned CharWidth = Target->getCharWidth();
5218 unsigned ShortWidth = Target->getShortWidth();
5219 bool EnumTooLarge = false;
5220 unsigned BestWidth;
5221 if (NumNegativeBits) {
5222 // If there is a negative value, figure out the smallest integer type (of
5223 // int/long/longlong) that fits.
5224 // If it's packed, check also if it fits a char or a short.
5225 if (IsPacked && NumNegativeBits <= CharWidth &&
5226 NumPositiveBits < CharWidth) {
5227 BestType = SignedCharTy;
5228 BestWidth = CharWidth;
5229 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5230 NumPositiveBits < ShortWidth) {
5231 BestType = ShortTy;
5232 BestWidth = ShortWidth;
5233 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5234 BestType = IntTy;
5235 BestWidth = IntWidth;
5236 } else {
5237 BestWidth = Target->getLongWidth();
5238
5239 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5240 BestType = LongTy;
5241 } else {
5242 BestWidth = Target->getLongLongWidth();
5243
5244 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5245 EnumTooLarge = true;
5246 BestType = LongLongTy;
5247 }
5248 }
5249 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5250 } else {
5251 // If there is no negative value, figure out the smallest type that fits
5252 // all of the enumerator values.
5253 // If it's packed, check also if it fits a char or a short.
5254 if (IsPacked && NumPositiveBits <= CharWidth) {
5255 BestType = UnsignedCharTy;
5256 BestPromotionType = IntTy;
5257 BestWidth = CharWidth;
5258 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5259 BestType = UnsignedShortTy;
5260 BestPromotionType = IntTy;
5261 BestWidth = ShortWidth;
5262 } else if (NumPositiveBits <= IntWidth) {
5263 BestType = UnsignedIntTy;
5264 BestWidth = IntWidth;
5265 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5267 : IntTy;
5268 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5269 BestType = UnsignedLongTy;
5270 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5272 : LongTy;
5273 } else {
5274 BestWidth = Target->getLongLongWidth();
5275 if (NumPositiveBits > BestWidth) {
5276 // This can happen with bit-precise integer types, but those are not
5277 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5278 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5279 // a 128-bit integer, we should consider doing the same.
5280 EnumTooLarge = true;
5281 }
5282 BestType = UnsignedLongLongTy;
5283 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5285 : LongLongTy;
5286 }
5287 }
5288 return EnumTooLarge;
5289}
5290
5292 const UnresolvedUsingTypenameDecl *Decl) const {
5293 if (Decl->TypeForDecl)
5294 return QualType(Decl->TypeForDecl, 0);
5295
5296 if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
5298 if (CanonicalDecl->TypeForDecl)
5299 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
5300
5301 Type *newType =
5302 new (*this, alignof(UnresolvedUsingType)) UnresolvedUsingType(Decl);
5303 Decl->TypeForDecl = newType;
5304 Types.push_back(newType);
5305 return QualType(newType, 0);
5306}
5307
5309 QualType modifiedType,
5310 QualType equivalentType,
5311 const Attr *attr) const {
5312 llvm::FoldingSetNodeID id;
5313 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr);
5314
5315 void *insertPos = nullptr;
5316 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5317 if (type) return QualType(type, 0);
5318
5319 assert(!attr || attr->getKind() == attrKind);
5320
5321 QualType canon = getCanonicalType(equivalentType);
5322 type = new (*this, alignof(AttributedType))
5323 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5324
5325 Types.push_back(type);
5326 AttributedTypes.InsertNode(type, insertPos);
5327
5328 return QualType(type, 0);
5329}
5330
5332 QualType equivalentType) const {
5333 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5334}
5335
5337 QualType modifiedType,
5338 QualType equivalentType) {
5339 switch (nullability) {
5341 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5342
5344 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5345
5347 return getAttributedType(attr::TypeNullableResult, modifiedType,
5348 equivalentType);
5349
5351 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5352 equivalentType);
5353 }
5354
5355 llvm_unreachable("Unknown nullability kind");
5356}
5357
5358QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5359 QualType Wrapped) const {
5360 llvm::FoldingSetNodeID ID;
5361 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5362
5363 void *InsertPos = nullptr;
5365 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5366 if (Ty)
5367 return QualType(Ty, 0);
5368
5369 QualType Canon = getCanonicalType(Wrapped);
5370 Ty = new (*this, alignof(BTFTagAttributedType))
5371 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5372
5373 Types.push_back(Ty);
5374 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5375
5376 return QualType(Ty, 0);
5377}
5378
5380 QualType Wrapped, QualType Contained,
5382
5383 llvm::FoldingSetNodeID ID;
5384 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5385
5386 void *InsertPos = nullptr;
5388 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5389 if (Ty)
5390 return QualType(Ty, 0);
5391
5392 Ty = new (*this, alignof(HLSLAttributedResourceType))
5393 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5394
5395 Types.push_back(Ty);
5396 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5397
5398 return QualType(Ty, 0);
5399}
5400/// Retrieve a substitution-result type.
5402 QualType Replacement, Decl *AssociatedDecl, unsigned Index,
5403 std::optional<unsigned> PackIndex,
5404 SubstTemplateTypeParmTypeFlag Flag) const {
5405 llvm::FoldingSetNodeID ID;
5406 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5407 PackIndex, Flag);
5408 void *InsertPos = nullptr;
5409 SubstTemplateTypeParmType *SubstParm =
5410 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5411
5412 if (!SubstParm) {
5413 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5414 !Replacement.isCanonical()),
5415 alignof(SubstTemplateTypeParmType));
5416 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5417 Index, PackIndex, Flag);
5418 Types.push_back(SubstParm);
5419 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5420 }
5421
5422 return QualType(SubstParm, 0);
5423}
5424
5425/// Retrieve a
5428 unsigned Index, bool Final,
5429 const TemplateArgument &ArgPack) {
5430#ifndef NDEBUG
5431 for (const auto &P : ArgPack.pack_elements())
5432 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5433#endif
5434
5435 llvm::FoldingSetNodeID ID;
5436 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5437 ArgPack);
5438 void *InsertPos = nullptr;
5439 if (SubstTemplateTypeParmPackType *SubstParm =
5440 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5441 return QualType(SubstParm, 0);
5442
5443 QualType Canon;
5444 {
5445 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5446 if (!AssociatedDecl->isCanonicalDecl() ||
5447 !CanonArgPack.structurallyEquals(ArgPack)) {
5449 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5450 [[maybe_unused]] const auto *Nothing =
5451 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5452 assert(!Nothing);
5453 }
5454 }
5455
5456 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5457 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5458 ArgPack);
5459 Types.push_back(SubstParm);
5460 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5461 return QualType(SubstParm, 0);
5462}
5463
5464/// Retrieve the template type parameter type for a template
5465/// parameter or parameter pack with the given depth, index, and (optionally)
5466/// name.
5467QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5468 bool ParameterPack,
5469 TemplateTypeParmDecl *TTPDecl) const {
5470 llvm::FoldingSetNodeID ID;
5471 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5472 void *InsertPos = nullptr;
5473 TemplateTypeParmType *TypeParm
5474 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5475
5476 if (TypeParm)
5477 return QualType(TypeParm, 0);
5478
5479 if (TTPDecl) {
5480 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5481 TypeParm = new (*this, alignof(TemplateTypeParmType))
5482 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
5483
5484 TemplateTypeParmType *TypeCheck
5485 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5486 assert(!TypeCheck && "Template type parameter canonical type broken");
5487 (void)TypeCheck;
5488 } else
5489 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
5490 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
5491
5492 Types.push_back(TypeParm);
5493 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5494
5495 return QualType(TypeParm, 0);
5496}
5497
5500 SourceLocation NameLoc,
5501 const TemplateArgumentListInfo &Args,
5502 QualType Underlying) const {
5503 assert(!Name.getAsDependentTemplateName() &&
5504 "No dependent template names here!");
5505 QualType TST =
5506 getTemplateSpecializationType(Name, Args.arguments(), Underlying);
5507
5512 TL.setTemplateNameLoc(NameLoc);
5513 TL.setLAngleLoc(Args.getLAngleLoc());
5514 TL.setRAngleLoc(Args.getRAngleLoc());
5515 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5516 TL.setArgLocInfo(i, Args[i].getLocInfo());
5517 return DI;
5518}
5519
5523 QualType Underlying) const {
5524 assert(!Template.getAsDependentTemplateName() &&
5525 "No dependent template names here!");
5526
5528 ArgVec.reserve(Args.size());
5529 for (const TemplateArgumentLoc &Arg : Args)
5530 ArgVec.push_back(Arg.getArgument());
5531
5532 return getTemplateSpecializationType(Template, ArgVec, Underlying);
5533}
5534
5535#ifndef NDEBUG
5537 for (const TemplateArgument &Arg : Args)
5538 if (Arg.isPackExpansion())
5539 return true;
5540
5541 return true;
5542}
5543#endif
5544
5548 QualType Underlying) const {
5549 assert(!Template.getAsDependentTemplateName() &&
5550 "No dependent template names here!");
5551
5552 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
5553 bool IsTypeAlias = TD && TD->isTypeAlias();
5554 QualType CanonType;
5555 if (!Underlying.isNull())
5556 CanonType = getCanonicalType(Underlying);
5557 else {
5558 // We can get here with an alias template when the specialization contains
5559 // a pack expansion that does not match up with a parameter pack.
5560 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
5561 "Caller must compute aliased type");
5562 IsTypeAlias = false;
5563 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
5564 }
5565
5566 // Allocate the (non-canonical) template specialization type, but don't
5567 // try to unique it: these types typically have location information that
5568 // we don't unique and don't want to lose.
5569 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5570 sizeof(TemplateArgument) * Args.size() +
5571 (IsTypeAlias ? sizeof(QualType) : 0),
5573 auto *Spec
5574 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
5575 IsTypeAlias ? Underlying : QualType());
5576
5577 Types.push_back(Spec);
5578 return QualType(Spec, 0);
5579}
5580
5582 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
5583 assert(!Template.getAsDependentTemplateName() &&
5584 "No dependent template names here!");
5585
5586 // Build the canonical template specialization type.
5587 // Any DeducedTemplateNames are ignored, because the effective name of a TST
5588 // accounts for the TST arguments laid over any default arguments contained in
5589 // its name.
5590 TemplateName CanonTemplate =
5591 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
5592
5593 bool AnyNonCanonArgs = false;
5594 auto CanonArgs =
5595 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5596
5597 // Determine whether this canonical template specialization type already
5598 // exists.
5599 llvm::FoldingSetNodeID ID;
5600 TemplateSpecializationType::Profile(ID, CanonTemplate,
5601 CanonArgs, *this);
5602
5603 void *InsertPos = nullptr;
5605 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5606
5607 if (!Spec) {
5608 // Allocate a new canonical template specialization type.
5609 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
5610 sizeof(TemplateArgument) * CanonArgs.size()),
5612 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
5613 CanonArgs,
5614 QualType(), QualType());
5615 Types.push_back(Spec);
5616 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
5617 }
5618
5619 assert(Spec->isDependentType() &&
5620 "Non-dependent template-id type must have a canonical type");
5621 return QualType(Spec, 0);
5622}
5623
5626 QualType NamedType,
5627 TagDecl *OwnedTagDecl) const {
5628 llvm::FoldingSetNodeID ID;
5629 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
5630
5631 void *InsertPos = nullptr;
5632 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5633 if (T)
5634 return QualType(T, 0);
5635
5636 QualType Canon = NamedType;
5637 if (!Canon.isCanonical()) {
5638 Canon = getCanonicalType(NamedType);
5639 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5640 assert(!CheckT && "Elaborated canonical type broken");
5641 (void)CheckT;
5642 }
5643
5644 void *Mem =
5645 Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
5646 alignof(ElaboratedType));
5647 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
5648
5649 Types.push_back(T);
5650 ElaboratedTypes.InsertNode(T, InsertPos);
5651 return QualType(T, 0);
5652}
5653
5656 llvm::FoldingSetNodeID ID;
5657 ParenType::Profile(ID, InnerType);
5658
5659 void *InsertPos = nullptr;
5660 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5661 if (T)
5662 return QualType(T, 0);
5663
5664 QualType Canon = InnerType;
5665 if (!Canon.isCanonical()) {
5666 Canon = getCanonicalType(InnerType);
5667 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5668 assert(!CheckT && "Paren canonical type broken");
5669 (void)CheckT;
5670 }
5671
5672 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
5673 Types.push_back(T);
5674 ParenTypes.InsertNode(T, InsertPos);
5675 return QualType(T, 0);
5676}
5677
5680 const IdentifierInfo *MacroII) const {
5681 QualType Canon = UnderlyingTy;
5682 if (!Canon.isCanonical())
5683 Canon = getCanonicalType(UnderlyingTy);
5684
5685 auto *newType = new (*this, alignof(MacroQualifiedType))
5686 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
5687 Types.push_back(newType);
5688 return QualType(newType, 0);
5689}
5690
5693 const IdentifierInfo *Name,
5694 QualType Canon) const {
5695 if (Canon.isNull()) {
5697 if (CanonNNS != NNS)
5698 Canon = getDependentNameType(Keyword, CanonNNS, Name);
5699 }
5700
5701 llvm::FoldingSetNodeID ID;
5702 DependentNameType::Profile(ID, Keyword, NNS, Name);
5703
5704 void *InsertPos = nullptr;
5706 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
5707 if (T)
5708 return QualType(T, 0);
5709
5710 T = new (*this, alignof(DependentNameType))
5711 DependentNameType(Keyword, NNS, Name, Canon);
5712 Types.push_back(T);
5713 DependentNameTypes.InsertNode(T, InsertPos);
5714 return QualType(T, 0);
5715}
5716
5719 const IdentifierInfo *Name, ArrayRef<TemplateArgumentLoc> Args) const {
5720 // TODO: avoid this copy
5722 for (unsigned I = 0, E = Args.size(); I != E; ++I)
5723 ArgCopy.push_back(Args[I].getArgument());
5724 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
5725}
5726
5729 ElaboratedTypeKeyword Keyword,
5731 const IdentifierInfo *Name,
5732 ArrayRef<TemplateArgument> Args) const {
5733 assert((!NNS || NNS->isDependent()) &&
5734 "nested-name-specifier must be dependent");
5735
5736 llvm::FoldingSetNodeID ID;
5737 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
5738 Name, Args);
5739
5740 void *InsertPos = nullptr;
5742 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5743 if (T)
5744 return QualType(T, 0);
5745
5747
5748 ElaboratedTypeKeyword CanonKeyword = Keyword;
5749 if (Keyword == ElaboratedTypeKeyword::None)
5750 CanonKeyword = ElaboratedTypeKeyword::Typename;
5751
5752 bool AnyNonCanonArgs = false;
5753 auto CanonArgs =
5754 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5755
5756 QualType Canon;
5757 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
5758 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
5759 Name,
5760 CanonArgs);
5761
5762 // Find the insert position again.
5763 [[maybe_unused]] auto *Nothing =
5764 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5765 assert(!Nothing && "canonical type broken");
5766 }
5767
5768 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
5769 sizeof(TemplateArgument) * Args.size()),
5771 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
5772 Name, Args, Canon);
5773 Types.push_back(T);
5774 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
5775 return QualType(T, 0);
5776}
5777
5779 TemplateArgument Arg;
5780 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5781 QualType ArgType = getTypeDeclType(TTP);
5782 if (TTP->isParameterPack())
5783 ArgType = getPackExpansionType(ArgType, std::nullopt);
5784
5785 Arg = TemplateArgument(ArgType);
5786 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5787 QualType T =
5788 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
5789 // For class NTTPs, ensure we include the 'const' so the type matches that
5790 // of a real template argument.
5791 // FIXME: It would be more faithful to model this as something like an
5792 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
5793 ExprValueKind VK;
5794 if (T->isRecordType()) {
5795 // C++ [temp.param]p8: An id-expression naming a non-type
5796 // template-parameter of class type T denotes a static storage duration
5797 // object of type const T.
5798 T.addConst();
5799 VK = VK_LValue;
5800 } else {
5801 VK = Expr::getValueKindForType(NTTP->getType());
5802 }
5803 Expr *E = new (*this)
5804 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
5805 T, VK, NTTP->getLocation());
5806
5807 if (NTTP->isParameterPack())
5808 E = new (*this)
5809 PackExpansionExpr(DependentTy, E, NTTP->getLocation(), std::nullopt);
5810 Arg = TemplateArgument(E);
5811 } else {
5812 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
5814 nullptr, /*TemplateKeyword=*/false, TemplateName(TTP));
5815 if (TTP->isParameterPack())
5816 Arg = TemplateArgument(Name, std::optional<unsigned>());
5817 else
5818 Arg = TemplateArgument(Name);
5819 }
5820
5821 if (Param->isTemplateParameterPack())
5822 Arg =
5823 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
5824
5825 return Arg;
5826}
5827
5829 std::optional<unsigned> NumExpansions,
5830 bool ExpectPackInType) const {
5831 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
5832 "Pack expansions must expand one or more parameter packs");
5833
5834 llvm::FoldingSetNodeID ID;
5835 PackExpansionType::Profile(ID, Pattern, NumExpansions);
5836
5837 void *InsertPos = nullptr;
5838 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5839 if (T)
5840 return QualType(T, 0);
5841
5842 QualType Canon;
5843 if (!Pattern.isCanonical()) {
5844 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5845 /*ExpectPackInType=*/false);
5846
5847 // Find the insert position again, in case we inserted an element into
5848 // PackExpansionTypes and invalidated our insert position.
5849 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5850 }
5851
5852 T = new (*this, alignof(PackExpansionType))
5853 PackExpansionType(Pattern, Canon, NumExpansions);
5854 Types.push_back(T);
5855 PackExpansionTypes.InsertNode(T, InsertPos);
5856 return QualType(T, 0);
5857}
5858
5859/// CmpProtocolNames - Comparison predicate for sorting protocols
5860/// alphabetically.
5861static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5862 ObjCProtocolDecl *const *RHS) {
5863 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5864}
5865
5867 if (Protocols.empty()) return true;
5868
5869 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5870 return false;
5871
5872 for (unsigned i = 1; i != Protocols.size(); ++i)
5873 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5874 Protocols[i]->getCanonicalDecl() != Protocols[i])
5875 return false;
5876 return true;
5877}
5878
5879static void
5881 // Sort protocols, keyed by name.
5882 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5883
5884 // Canonicalize.
5885 for (ObjCProtocolDecl *&P : Protocols)
5886 P = P->getCanonicalDecl();
5887
5888 // Remove duplicates.
5889 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5890 Protocols.erase(ProtocolsEnd, Protocols.end());
5891}
5892
5894 ObjCProtocolDecl * const *Protocols,
5895 unsigned NumProtocols) const {
5896 return getObjCObjectType(BaseType, {},
5897 llvm::ArrayRef(Protocols, NumProtocols),
5898 /*isKindOf=*/false);
5899}
5900
5902 QualType baseType,
5903 ArrayRef<QualType> typeArgs,
5905 bool isKindOf) const {
5906 // If the base type is an interface and there aren't any protocols or
5907 // type arguments to add, then the interface type will do just fine.
5908 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5909 isa<ObjCInterfaceType>(baseType))
5910 return baseType;
5911
5912 // Look in the folding set for an existing type.
5913 llvm::FoldingSetNodeID ID;
5914 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5915 void *InsertPos = nullptr;
5916 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5917 return QualType(QT, 0);
5918
5919 // Determine the type arguments to be used for canonicalization,
5920 // which may be explicitly specified here or written on the base
5921 // type.
5922 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5923 if (effectiveTypeArgs.empty()) {
5924 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5925 effectiveTypeArgs = baseObject->getTypeArgs();
5926 }
5927
5928 // Build the canonical type, which has the canonical base type and a
5929 // sorted-and-uniqued list of protocols and the type arguments
5930 // canonicalized.
5931 QualType canonical;
5932 bool typeArgsAreCanonical = llvm::all_of(
5933 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
5934 bool protocolsSorted = areSortedAndUniqued(protocols);
5935 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5936 // Determine the canonical type arguments.
5937 ArrayRef<QualType> canonTypeArgs;
5938 SmallVector<QualType, 4> canonTypeArgsVec;
5939 if (!typeArgsAreCanonical) {
5940 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5941 for (auto typeArg : effectiveTypeArgs)
5942 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5943 canonTypeArgs = canonTypeArgsVec;
5944 } else {
5945 canonTypeArgs = effectiveTypeArgs;
5946 }
5947
5948 ArrayRef<ObjCProtocolDecl *> canonProtocols;
5949 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5950 if (!protocolsSorted) {
5951 canonProtocolsVec.append(protocols.begin(), protocols.end());
5952 SortAndUniqueProtocols(canonProtocolsVec);
5953 canonProtocols = canonProtocolsVec;
5954 } else {
5955 canonProtocols = protocols;
5956 }
5957
5958 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5959 canonProtocols, isKindOf);
5960
5961 // Regenerate InsertPos.
5962 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5963 }
5964
5965 unsigned size = sizeof(ObjCObjectTypeImpl);
5966 size += typeArgs.size() * sizeof(QualType);
5967 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5968 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
5969 auto *T =
5970 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5971 isKindOf);
5972
5973 Types.push_back(T);
5974 ObjCObjectTypes.InsertNode(T, InsertPos);
5975 return QualType(T, 0);
5976}
5977
5978/// Apply Objective-C protocol qualifiers to the given type.
5979/// If this is for the canonical type of a type parameter, we can apply
5980/// protocol qualifiers on the ObjCObjectPointerType.
5983 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5984 bool allowOnPointerType) const {
5985 hasError = false;
5986
5987 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5988 return getObjCTypeParamType(objT->getDecl(), protocols);
5989 }
5990
5991 // Apply protocol qualifiers to ObjCObjectPointerType.
5992 if (allowOnPointerType) {
5993 if (const auto *objPtr =
5994 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5995 const ObjCObjectType *objT = objPtr->getObjectType();
5996 // Merge protocol lists and construct ObjCObjectType.
5998 protocolsVec.append(objT->qual_begin(),
5999 objT->qual_end());
6000 protocolsVec.append(protocols.begin(), protocols.end());
6001 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6003 objT->getBaseType(),
6004 objT->getTypeArgsAsWritten(),
6005 protocols,
6006 objT->isKindOfTypeAsWritten());
6008 }
6009 }
6010
6011 // Apply protocol qualifiers to ObjCObjectType.
6012 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6013 // FIXME: Check for protocols to which the class type is already
6014 // known to conform.
6015
6016 return getObjCObjectType(objT->getBaseType(),
6017 objT->getTypeArgsAsWritten(),
6018 protocols,
6019 objT->isKindOfTypeAsWritten());
6020 }
6021
6022 // If the canonical type is ObjCObjectType, ...
6023 if (type->isObjCObjectType()) {
6024 // Silently overwrite any existing protocol qualifiers.
6025 // TODO: determine whether that's the right thing to do.
6026
6027 // FIXME: Check for protocols to which the class type is already
6028 // known to conform.
6029 return getObjCObjectType(type, {}, protocols, false);
6030 }
6031
6032 // id<protocol-list>
6033 if (type->isObjCIdType()) {
6034 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6035 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6036 objPtr->isKindOfType());
6038 }
6039
6040 // Class<protocol-list>
6041 if (type->isObjCClassType()) {
6042 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6043 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6044 objPtr->isKindOfType());
6046 }
6047
6048 hasError = true;
6049 return type;
6050}
6051
6054 ArrayRef<ObjCProtocolDecl *> protocols) const {
6055 // Look in the folding set for an existing type.
6056 llvm::FoldingSetNodeID ID;
6057 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6058 void *InsertPos = nullptr;
6059 if (ObjCTypeParamType *TypeParam =
6060 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6061 return QualType(TypeParam, 0);
6062
6063 // We canonicalize to the underlying type.
6064 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6065 if (!protocols.empty()) {
6066 // Apply the protocol qualifers.
6067 bool hasError;
6069 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6070 assert(!hasError && "Error when apply protocol qualifier to bound type");
6071 }
6072
6073 unsigned size = sizeof(ObjCTypeParamType);
6074 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6075 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6076 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6077
6078 Types.push_back(newType);
6079 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6080 return QualType(newType, 0);
6081}
6082
6084 ObjCTypeParamDecl *New) const {
6086 // Update TypeForDecl after updating TypeSourceInfo.
6087 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
6089 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6090 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6091 New->setTypeForDecl(UpdatedTy.getTypePtr());
6092}
6093
6094/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6095/// protocol list adopt all protocols in QT's qualified-id protocol
6096/// list.
6098 ObjCInterfaceDecl *IC) {
6099 if (!QT->isObjCQualifiedIdType())
6100 return false;
6101
6102 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6103 // If both the right and left sides have qualifiers.
6104 for (auto *Proto : OPT->quals()) {
6105 if (!IC->ClassImplementsProtocol(Proto, false))
6106 return false;
6107 }
6108 return true;
6109 }
6110 return false;
6111}
6112
6113/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6114/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6115/// of protocols.
6117 ObjCInterfaceDecl *IDecl) {
6118 if (!QT->isObjCQualifiedIdType())
6119 return false;
6120 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6121 if (!OPT)
6122 return false;
6123 if (!IDecl->hasDefinition())
6124 return false;
6126 CollectInheritedProtocols(IDecl, InheritedProtocols);
6127 if (InheritedProtocols.empty())
6128 return false;
6129 // Check that if every protocol in list of id<plist> conforms to a protocol
6130 // of IDecl's, then bridge casting is ok.
6131 bool Conforms = false;
6132 for (auto *Proto : OPT->quals()) {
6133 Conforms = false;
6134 for (auto *PI : InheritedProtocols) {
6135 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6136 Conforms = true;
6137 break;
6138 }
6139 }
6140 if (!Conforms)
6141 break;
6142 }
6143 if (Conforms)
6144 return true;
6145
6146 for (auto *PI : InheritedProtocols) {
6147 // If both the right and left sides have qualifiers.
6148 bool Adopts = false;
6149 for (auto *Proto : OPT->quals()) {
6150 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6151 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6152 break;
6153 }
6154 if (!Adopts)
6155 return false;
6156 }
6157 return true;
6158}
6159
6160/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6161/// the given object type.
6163 llvm::FoldingSetNodeID ID;
6164 ObjCObjectPointerType::Profile(ID, ObjectT);
6165
6166 void *InsertPos = nullptr;
6167 if (ObjCObjectPointerType *QT =
6168 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6169 return QualType(QT, 0);
6170
6171 // Find the canonical object type.
6172 QualType Canonical;
6173 if (!ObjectT.isCanonical()) {
6174 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6175
6176 // Regenerate InsertPos.
6177 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6178 }
6179
6180 // No match.
6181 void *Mem =
6183 auto *QType =
6184 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6185
6186 Types.push_back(QType);
6187 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6188 return QualType(QType, 0);
6189}
6190
6191/// getObjCInterfaceType - Return the unique reference to the type for the
6192/// specified ObjC interface decl. The list of protocols is optional.
6194 ObjCInterfaceDecl *PrevDecl) const {
6195 if (Decl->TypeForDecl)
6196 return QualType(Decl->TypeForDecl, 0);
6197
6198 if (PrevDecl) {
6199 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6200 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6201 return QualType(PrevDecl->TypeForDecl, 0);
6202 }
6203
6204 // Prefer the definition, if there is one.
6205 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6206 Decl = Def;
6207
6208 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6209 auto *T = new (Mem) ObjCInterfaceType(Decl);
6210 Decl->TypeForDecl = T;
6211 Types.push_back(T);
6212 return QualType(T, 0);
6213}
6214
6215/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6216/// TypeOfExprType AST's (since expression's are never shared). For example,
6217/// multiple declarations that refer to "typeof(x)" all contain different
6218/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6219/// on canonical type's (which are always unique).
6221 TypeOfExprType *toe;
6222 if (tofExpr->isTypeDependent()) {
6223 llvm::FoldingSetNodeID ID;
6224 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6225 Kind == TypeOfKind::Unqualified);
6226
6227 void *InsertPos = nullptr;
6229 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6230 if (Canon) {
6231 // We already have a "canonical" version of an identical, dependent
6232 // typeof(expr) type. Use that as our canonical type.
6233 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6234 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6235 } else {
6236 // Build a new, canonical typeof(expr) type.
6237 Canon = new (*this, alignof(DependentTypeOfExprType))
6238 DependentTypeOfExprType(*this, tofExpr, Kind);
6239 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6240 toe = Canon;
6241 }
6242 } else {
6243 QualType Canonical = getCanonicalType(tofExpr->getType());
6244 toe = new (*this, alignof(TypeOfExprType))
6245 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6246 }
6247 Types.push_back(toe);
6248 return QualType(toe, 0);
6249}
6250
6251/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6252/// TypeOfType nodes. The only motivation to unique these nodes would be
6253/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6254/// an issue. This doesn't affect the type checker, since it operates
6255/// on canonical types (which are always unique).
6257 QualType Canonical = getCanonicalType(tofType);
6258 auto *tot = new (*this, alignof(TypeOfType))
6259 TypeOfType(*this, tofType, Canonical, Kind);
6260 Types.push_back(tot);
6261 return QualType(tot, 0);
6262}
6263
6264/// getReferenceQualifiedType - Given an expr, will return the type for
6265/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6266/// and class member access into account.
6268 // C++11 [dcl.type.simple]p4:
6269 // [...]
6270 QualType T = E->getType();
6271 switch (E->getValueKind()) {
6272 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6273 // type of e;
6274 case VK_XValue:
6275 return getRValueReferenceType(T);
6276 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6277 // type of e;
6278 case VK_LValue:
6279 return getLValueReferenceType(T);
6280 // - otherwise, decltype(e) is the type of e.
6281 case VK_PRValue:
6282 return T;
6283 }
6284 llvm_unreachable("Unknown value kind");
6285}
6286
6287/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6288/// nodes. This would never be helpful, since each such type has its own
6289/// expression, and would not give a significant memory saving, since there
6290/// is an Expr tree under each such type.
6292 DecltypeType *dt;
6293
6294 // C++11 [temp.type]p2:
6295 // If an expression e involves a template parameter, decltype(e) denotes a
6296 // unique dependent type. Two such decltype-specifiers refer to the same
6297 // type only if their expressions are equivalent (14.5.6.1).
6298 if (e->isInstantiationDependent()) {
6299 llvm::FoldingSetNodeID ID;
6300 DependentDecltypeType::Profile(ID, *this, e);
6301
6302 void *InsertPos = nullptr;
6304 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
6305 if (!Canon) {
6306 // Build a new, canonical decltype(expr) type.
6307 Canon = new (*this, alignof(DependentDecltypeType))
6309 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
6310 }
6311 dt = new (*this, alignof(DecltypeType))
6312 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
6313 } else {
6314 dt = new (*this, alignof(DecltypeType))
6315 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
6316 }
6317 Types.push_back(dt);
6318 return QualType(dt, 0);
6319}
6320
6322 bool FullySubstituted,
6323 ArrayRef<QualType> Expansions,
6324 int Index) const {
6325 QualType Canonical;
6326 if (FullySubstituted && Index != -1) {
6327 Canonical = getCanonicalType(Expansions[Index]);
6328 } else {
6329 llvm::FoldingSetNodeID ID;
6330 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6331 FullySubstituted);
6332 void *InsertPos = nullptr;
6333 PackIndexingType *Canon =
6334 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6335 if (!Canon) {
6336 void *Mem = Allocate(
6337 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6339 Canon = new (Mem)
6340 PackIndexingType(*this, QualType(), Pattern.getCanonicalType(),
6341 IndexExpr, FullySubstituted, Expansions);
6342 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6343 }
6344 Canonical = QualType(Canon, 0);
6345 }
6346
6347 void *Mem =
6348 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6350 auto *T = new (Mem) PackIndexingType(*this, Canonical, Pattern, IndexExpr,
6351 FullySubstituted, Expansions);
6352 Types.push_back(T);
6353 return QualType(T, 0);
6354}
6355
6356/// getUnaryTransformationType - We don't unique these, since the memory
6357/// savings are minimal and these are rare.
6359 QualType UnderlyingType,
6361 const {
6362 UnaryTransformType *ut = nullptr;
6363
6364 if (BaseType->isDependentType()) {
6365 // Look in the folding set for an existing type.
6366 llvm::FoldingSetNodeID ID;
6368
6369 void *InsertPos = nullptr;
6371 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6372
6373 if (!Canon) {
6374 // Build a new, canonical __underlying_type(type) type.
6375 Canon = new (*this, alignof(DependentUnaryTransformType))
6376 DependentUnaryTransformType(*this, getCanonicalType(BaseType), Kind);
6377 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
6378 }
6379 ut = new (*this, alignof(UnaryTransformType))
6380 UnaryTransformType(BaseType, QualType(), Kind, QualType(Canon, 0));
6381 } else {
6382 QualType CanonType = getCanonicalType(UnderlyingType);
6383 ut = new (*this, alignof(UnaryTransformType))
6384 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6385 }
6386 Types.push_back(ut);
6387 return QualType(ut, 0);
6388}
6389
6390QualType ASTContext::getAutoTypeInternal(
6391 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6392 bool IsPack, ConceptDecl *TypeConstraintConcept,
6393 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6394 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6395 !TypeConstraintConcept && !IsDependent)
6396 return getAutoDeductType();
6397
6398 // Look in the folding set for an existing type.
6399 llvm::FoldingSetNodeID ID;
6400 bool IsDeducedDependent =
6401 !DeducedType.isNull() && DeducedType->isDependentType();
6402 AutoType::Profile(ID, *this, DeducedType, Keyword,
6403 IsDependent || IsDeducedDependent, TypeConstraintConcept,
6404 TypeConstraintArgs);
6405 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6406 return QualType(AT_iter->getSecond(), 0);
6407
6408 QualType Canon;
6409 if (!IsCanon) {
6410 if (!DeducedType.isNull()) {
6411 Canon = DeducedType.getCanonicalType();
6412 } else if (TypeConstraintConcept) {
6413 bool AnyNonCanonArgs = false;
6414 ConceptDecl *CanonicalConcept = TypeConstraintConcept->getCanonicalDecl();
6415 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6416 *this, TypeConstraintArgs, AnyNonCanonArgs);
6417 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6418 Canon =
6419 getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6420 CanonicalConcept, CanonicalConceptArgs, true);
6421 }
6422 }
6423 }
6424
6425 void *Mem = Allocate(sizeof(AutoType) +
6426 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6427 alignof(AutoType));
6428 auto *AT = new (Mem) AutoType(
6429 DeducedType, Keyword,
6430 (IsDependent ? TypeDependence::DependentInstantiation
6431 : TypeDependence::None) |
6432 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6433 Canon, TypeConstraintConcept, TypeConstraintArgs);
6434#ifndef NDEBUG
6435 llvm::FoldingSetNodeID InsertedID;
6436 AT->Profile(InsertedID, *this);
6437 assert(InsertedID == ID && "ID does not match");
6438#endif
6439 Types.push_back(AT);
6440 AutoTypes.try_emplace(ID, AT);
6441 return QualType(AT, 0);
6442}
6443
6444/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6445/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6446/// canonical deduced-but-dependent 'auto' type.
6449 bool IsDependent, bool IsPack,
6450 ConceptDecl *TypeConstraintConcept,
6451 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6452 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6453 assert((!IsDependent || DeducedType.isNull()) &&
6454 "A dependent auto should be undeduced");
6455 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6456 TypeConstraintConcept, TypeConstraintArgs);
6457}
6458
6460 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6461
6462 // Remove a type-constraint from a top-level auto or decltype(auto).
6463 if (auto *AT = CanonT->getAs<AutoType>()) {
6464 if (!AT->isConstrained())
6465 return T;
6466 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6467 AT->isDependentType(),
6468 AT->containsUnexpandedParameterPack()),
6469 T.getQualifiers());
6470 }
6471
6472 // FIXME: We only support constrained auto at the top level in the type of a
6473 // non-type template parameter at the moment. Once we lift that restriction,
6474 // we'll need to recursively build types containing auto here.
6475 assert(!CanonT->getContainedAutoType() ||
6476 !CanonT->getContainedAutoType()->isConstrained());
6477 return T;
6478}
6479
6480QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6481 TemplateName Template, QualType DeducedType, bool IsDependent,
6482 QualType Canon) const {
6483 // Look in the folding set for an existing type.
6484 void *InsertPos = nullptr;
6485 llvm::FoldingSetNodeID ID;
6487 IsDependent);
6489 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6490 return QualType(DTST, 0);
6491
6492 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6493 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent,
6494 Canon);
6495 llvm::FoldingSetNodeID TempID;
6496 DTST->Profile(TempID);
6497 assert(ID == TempID && "ID does not match");
6498 Types.push_back(DTST);
6499 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6500 return QualType(DTST, 0);
6501}
6502
6503/// Return the uniqued reference to the deduced template specialization type
6504/// which has been deduced to the given type, or to the canonical undeduced
6505/// such type, or the canonical deduced-but-dependent such type.
6507 TemplateName Template, QualType DeducedType, bool IsDependent) const {
6508 QualType Canon = DeducedType.isNull()
6509 ? getDeducedTemplateSpecializationTypeInternal(
6511 IsDependent, QualType())
6512 : DeducedType.getCanonicalType();
6513 return getDeducedTemplateSpecializationTypeInternal(Template, DeducedType,
6514 IsDependent, Canon);
6515}
6516
6517/// getAtomicType - Return the uniqued reference to the atomic type for
6518/// the given value type.
6520 // Unique pointers, to guarantee there is only one pointer of a particular
6521 // structure.
6522 llvm::FoldingSetNodeID ID;
6524
6525 void *InsertPos = nullptr;
6526 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6527 return QualType(AT, 0);
6528
6529 // If the atomic value type isn't canonical, this won't be a canonical type
6530 // either, so fill in the canonical type field.
6531 QualType Canonical;
6532 if (!T.isCanonical()) {
6533 Canonical = getAtomicType(getCanonicalType(T));
6534
6535 // Get the new insert position for the node we care about.
6536 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6537 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6538 }
6539 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6540 Types.push_back(New);
6541 AtomicTypes.InsertNode(New, InsertPos);
6542 return QualType(New, 0);
6543}
6544
6545/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6547 if (AutoDeductTy.isNull())
6548 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6550 TypeDependence::None, QualType(),
6551 /*concept*/ nullptr, /*args*/ {}),
6552 0);
6553 return AutoDeductTy;
6554}
6555
6556/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6560 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6561 return AutoRRefDeductTy;
6562}
6563
6564/// getTagDeclType - Return the unique reference to the type for the
6565/// specified TagDecl (struct/union/class/enum) decl.
6567 assert(Decl);
6568 // FIXME: What is the design on getTagDeclType when it requires casting
6569 // away const? mutable?
6570 return getTypeDeclType(const_cast<TagDecl*>(Decl));
6571}
6572
6573/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6574/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6575/// needs to agree with the definition in <stddef.h>.
6577 return getFromTargetType(Target->getSizeType());
6578}
6579
6580/// Return the unique signed counterpart of the integer type
6581/// corresponding to size_t.
6583 return getFromTargetType(Target->getSignedSizeType());
6584}
6585
6586/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
6588 return getFromTargetType(Target->getIntMaxType());
6589}
6590
6591/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
6593 return getFromTargetType(Target->getUIntMaxType());
6594}
6595
6596/// getSignedWCharType - Return the type of "signed wchar_t".
6597/// Used when in C++, as a GCC extension.
6599 // FIXME: derive from "Target" ?
6600 return WCharTy;
6601}
6602
6603/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
6604/// Used when in C++, as a GCC extension.
6606 // FIXME: derive from "Target" ?
6607 return UnsignedIntTy;
6608}
6609
6611 return getFromTargetType(Target->getIntPtrType());
6612}
6613
6616}
6617
6618/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6619/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6621 return getFromTargetType(Target->getPtrDiffType(LangAS::Default));
6622}
6623
6624/// Return the unique unsigned counterpart of "ptrdiff_t"
6625/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6626/// in the definition of %tu format specifier.
6628 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6629}
6630
6631/// Return the unique type for "pid_t" defined in
6632/// <sys/types.h>. We need this to compute the correct type for vfork().
6634 return getFromTargetType(Target->getProcessIDType());
6635}
6636
6637//===----------------------------------------------------------------------===//
6638// Type Operators
6639//===----------------------------------------------------------------------===//
6640
6642 // Push qualifiers into arrays, and then discard any remaining
6643 // qualifiers.
6644 T = getCanonicalType(T);
6646 const Type *Ty = T.getTypePtr();
6648 if (getLangOpts().HLSL && isa<ConstantArrayType>(Ty)) {
6650 } else if (isa<ArrayType>(Ty)) {
6652 } else if (isa<FunctionType>(Ty)) {
6653 Result = getPointerType(QualType(Ty, 0));
6654 } else {
6655 Result = QualType(Ty, 0);
6656 }
6657
6659}
6660
6662 Qualifiers &quals) const {
6663 SplitQualType splitType = type.getSplitUnqualifiedType();
6664
6665 // FIXME: getSplitUnqualifiedType() actually walks all the way to
6666 // the unqualified desugared type and then drops it on the floor.
6667 // We then have to strip that sugar back off with
6668 // getUnqualifiedDesugaredType(), which is silly.
6669 const auto *AT =
6670 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
6671
6672 // If we don't have an array, just use the results in splitType.
6673 if (!AT) {
6674 quals = splitType.Quals;
6675 return QualType(splitType.Ty, 0);
6676 }
6677
6678 // Otherwise, recurse on the array's element type.
6679 QualType elementType = AT->getElementType();
6680 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
6681
6682 // If that didn't change the element type, AT has no qualifiers, so we
6683 // can just use the results in splitType.
6684 if (elementType == unqualElementType) {
6685 assert(quals.empty()); // from the recursive call
6686 quals = splitType.Quals;
6687 return QualType(splitType.Ty, 0);
6688 }
6689
6690 // Otherwise, add in the qualifiers from the outermost type, then
6691 // build the type back up.
6692 quals.addConsistentQualifiers(splitType.Quals);
6693
6694 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
6695 return getConstantArrayType(unqualElementType, CAT->getSize(),
6696 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
6697 }
6698
6699 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
6700 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
6701 }
6702
6703 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
6704 return getVariableArrayType(unqualElementType,
6705 VAT->getSizeExpr(),
6706 VAT->getSizeModifier(),
6707 VAT->getIndexTypeCVRQualifiers(),
6708 VAT->getBracketsRange());
6709 }
6710
6711 const auto *DSAT = cast<DependentSizedArrayType>(AT);
6712 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
6713 DSAT->getSizeModifier(), 0,
6714 SourceRange());
6715}
6716
6717/// Attempt to unwrap two types that may both be array types with the same bound
6718/// (or both be array types of unknown bound) for the purpose of comparing the
6719/// cv-decomposition of two types per C++ [conv.qual].
6720///
6721/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6722/// C++20 [conv.qual], if permitted by the current language mode.
6724 bool AllowPiMismatch) const {
6725 while (true) {
6726 auto *AT1 = getAsArrayType(T1);
6727 if (!AT1)
6728 return;
6729
6730 auto *AT2 = getAsArrayType(T2);
6731 if (!AT2)
6732 return;
6733
6734 // If we don't have two array types with the same constant bound nor two
6735 // incomplete array types, we've unwrapped everything we can.
6736 // C++20 also permits one type to be a constant array type and the other
6737 // to be an incomplete array type.
6738 // FIXME: Consider also unwrapping array of unknown bound and VLA.
6739 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
6740 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
6741 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
6742 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6743 isa<IncompleteArrayType>(AT2))))
6744 return;
6745 } else if (isa<IncompleteArrayType>(AT1)) {
6746 if (!(isa<IncompleteArrayType>(AT2) ||
6747 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6748 isa<ConstantArrayType>(AT2))))
6749 return;
6750 } else {
6751 return;
6752 }
6753
6754 T1 = AT1->getElementType();
6755 T2 = AT2->getElementType();
6756 }
6757}
6758
6759/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
6760///
6761/// If T1 and T2 are both pointer types of the same kind, or both array types
6762/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
6763/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
6764///
6765/// This function will typically be called in a loop that successively
6766/// "unwraps" pointer and pointer-to-member types to compare them at each
6767/// level.
6768///
6769/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6770/// C++20 [conv.qual], if permitted by the current language mode.
6771///
6772/// \return \c true if a pointer type was unwrapped, \c false if we reached a
6773/// pair of types that can't be unwrapped further.
6775 bool AllowPiMismatch) const {
6776 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
6777
6778 const auto *T1PtrType = T1->getAs<PointerType>();
6779 const auto *T2PtrType = T2->getAs<PointerType>();
6780 if (T1PtrType && T2PtrType) {
6781 T1 = T1PtrType->getPointeeType();
6782 T2 = T2PtrType->getPointeeType();
6783 return true;
6784 }
6785
6786 const auto *T1MPType = T1->getAs<MemberPointerType>();
6787 const auto *T2MPType = T2->getAs<MemberPointerType>();
6788 if (T1MPType && T2MPType &&
6789 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
6790 QualType(T2MPType->getClass(), 0))) {
6791 T1 = T1MPType->getPointeeType();
6792 T2 = T2MPType->getPointeeType();
6793 return true;
6794 }
6795
6796 if (getLangOpts().ObjC) {
6797 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
6798 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
6799 if (T1OPType && T2OPType) {
6800 T1 = T1OPType->getPointeeType();
6801 T2 = T2OPType->getPointeeType();
6802 return true;
6803 }
6804 }
6805
6806 // FIXME: Block pointers, too?
6807
6808 return false;
6809}
6810
6812 while (true) {
6813 Qualifiers Quals;
6814 T1 = getUnqualifiedArrayType(T1, Quals);
6815 T2 = getUnqualifiedArrayType(T2, Quals);
6816 if (hasSameType(T1, T2))
6817 return true;
6818 if (!UnwrapSimilarTypes(T1, T2))
6819 return false;
6820 }
6821}
6822
6824 while (true) {
6825 Qualifiers Quals1, Quals2;
6826 T1 = getUnqualifiedArrayType(T1, Quals1);
6827 T2 = getUnqualifiedArrayType(T2, Quals2);
6828
6829 Quals1.removeCVRQualifiers();
6830 Quals2.removeCVRQualifiers();
6831 if (Quals1 != Quals2)
6832 return false;
6833
6834 if (hasSameType(T1, T2))
6835 return true;
6836
6837 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
6838 return false;
6839 }
6840}
6841
6844 SourceLocation NameLoc) const {
6845 switch (Name.getKind()) {
6848 // DNInfo work in progress: CHECKME: what about DNLoc?
6849 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
6850 NameLoc);
6851
6853 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
6854 // DNInfo work in progress: CHECKME: what about DNLoc?
6855 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
6856 }
6857
6859 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
6860 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
6861 }
6862
6864 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6865 DeclarationName DName;
6866 if (DTN->isIdentifier()) {
6868 return DeclarationNameInfo(DName, NameLoc);
6869 } else {
6871 // DNInfo work in progress: FIXME: source locations?
6872 DeclarationNameLoc DNLoc =
6874 return DeclarationNameInfo(DName, NameLoc, DNLoc);
6875 }
6876 }
6877
6880 = Name.getAsSubstTemplateTemplateParm();
6881 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
6882 NameLoc);
6883 }
6884
6887 = Name.getAsSubstTemplateTemplateParmPack();
6889 NameLoc);
6890 }
6892 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
6893 NameLoc);
6895 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
6896 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
6897 }
6898 }
6899
6900 llvm_unreachable("bad template name kind!");
6901}
6902
6903static const TemplateArgument *
6905 auto handleParam = [](auto *TP) -> const TemplateArgument * {
6906 if (!TP->hasDefaultArgument())
6907 return nullptr;
6908 return &TP->getDefaultArgument().getArgument();
6909 };
6910 switch (P->getKind()) {
6911 case NamedDecl::TemplateTypeParm:
6912 return handleParam(cast<TemplateTypeParmDecl>(P));
6913 case NamedDecl::NonTypeTemplateParm:
6914 return handleParam(cast<NonTypeTemplateParmDecl>(P));
6915 case NamedDecl::TemplateTemplateParm:
6916 return handleParam(cast<TemplateTemplateParmDecl>(P));
6917 default:
6918 llvm_unreachable("Unexpected template parameter kind");
6919 }
6920}
6921
6923 bool IgnoreDeduced) const {
6924 while (std::optional<TemplateName> UnderlyingOrNone =
6925 Name.desugar(IgnoreDeduced))
6926 Name = *UnderlyingOrNone;
6927
6928 switch (Name.getKind()) {
6930 TemplateDecl *Template = Name.getAsTemplateDecl();
6931 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
6932 Template = getCanonicalTemplateTemplateParmDecl(TTP);
6933
6934 // The canonical template name is the canonical template declaration.
6935 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
6936 }
6937
6940 llvm_unreachable("cannot canonicalize unresolved template");
6941
6943 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6944 assert(DTN && "Non-dependent template names must refer to template decls.");
6945 return DTN->CanonicalTemplateName;
6946 }
6947
6950 Name.getAsSubstTemplateTemplateParmPack();
6951 TemplateArgument canonArgPack =
6954 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
6955 subst->getFinal(), subst->getIndex());
6956 }
6958 assert(IgnoreDeduced == false);
6959 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
6960 DefaultArguments DefArgs = DTS->getDefaultArguments();
6961 TemplateName Underlying = DTS->getUnderlying();
6962
6963 TemplateName CanonUnderlying =
6964 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
6965 bool NonCanonical = CanonUnderlying != Underlying;
6966 auto CanonArgs =
6967 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
6968
6969 ArrayRef<NamedDecl *> Params =
6970 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
6971 assert(CanonArgs.size() <= Params.size());
6972 // A deduced template name which deduces the same default arguments already
6973 // declared in the underlying template is the same template as the
6974 // underlying template. We need need to note any arguments which differ from
6975 // the corresponding declaration. If any argument differs, we must build a
6976 // deduced template name.
6977 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
6979 if (!A)
6980 break;
6981 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
6982 TemplateArgument &CanonDefArg = CanonArgs[I];
6983 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
6984 continue;
6985 // Keep popping from the back any deault arguments which are the same.
6986 if (I == int(CanonArgs.size() - 1))
6987 CanonArgs.pop_back();
6988 NonCanonical = true;
6989 }
6990 return NonCanonical ? getDeducedTemplateName(
6991 CanonUnderlying,
6992 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
6993 : Name;
6994 }
6998 llvm_unreachable("always sugar node");
6999 }
7000
7001 llvm_unreachable("bad template name!");
7002}
7003
7005 const TemplateName &Y,
7006 bool IgnoreDeduced) const {
7007 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7008 getCanonicalTemplateName(Y, IgnoreDeduced);
7009}
7010
7011bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7012 if (!XCE != !YCE)
7013 return false;
7014
7015 if (!XCE)
7016 return true;
7017
7018 llvm::FoldingSetNodeID XCEID, YCEID;
7019 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7020 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7021 return XCEID == YCEID;
7022}
7023
7025 const TypeConstraint *YTC) const {
7026 if (!XTC != !YTC)
7027 return false;
7028
7029 if (!XTC)
7030 return true;
7031
7032 auto *NCX = XTC->getNamedConcept();
7033 auto *NCY = YTC->getNamedConcept();
7034 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7035 return false;
7038 return false;
7040 if (XTC->getConceptReference()
7042 ->NumTemplateArgs !=
7044 return false;
7045
7046 // Compare slowly by profiling.
7047 //
7048 // We couldn't compare the profiling result for the template
7049 // args here. Consider the following example in different modules:
7050 //
7051 // template <__integer_like _Tp, C<_Tp> Sentinel>
7052 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7053 // return __t;
7054 // }
7055 //
7056 // When we compare the profiling result for `C<_Tp>` in different
7057 // modules, it will compare the type of `_Tp` in different modules.
7058 // However, the type of `_Tp` in different modules refer to different
7059 // types here naturally. So we couldn't compare the profiling result
7060 // for the template args directly.
7063}
7064
7066 const NamedDecl *Y) const {
7067 if (X->getKind() != Y->getKind())
7068 return false;
7069
7070 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7071 auto *TY = cast<TemplateTypeParmDecl>(Y);
7072 if (TX->isParameterPack() != TY->isParameterPack())
7073 return false;
7074 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7075 return false;
7076 return isSameTypeConstraint(TX->getTypeConstraint(),
7077 TY->getTypeConstraint());
7078 }
7079
7080 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7081 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7082 return TX->isParameterPack() == TY->isParameterPack() &&
7083 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7084 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7085 TY->getPlaceholderTypeConstraint());
7086 }
7087
7088 auto *TX = cast<TemplateTemplateParmDecl>(X);
7089 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7090 return TX->isParameterPack() == TY->isParameterPack() &&
7091 isSameTemplateParameterList(TX->getTemplateParameters(),
7092 TY->getTemplateParameters());
7093}
7094
7096 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7097 if (X->size() != Y->size())
7098 return false;
7099
7100 for (unsigned I = 0, N = X->size(); I != N; ++I)
7101 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7102 return false;
7103
7104 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7105}
7106
7108 const NamedDecl *Y) const {
7109 // If the type parameter isn't the same already, we don't need to check the
7110 // default argument further.
7111 if (!isSameTemplateParameter(X, Y))
7112 return false;
7113
7114 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7115 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7116 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7117 return false;
7118
7119 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7120 TTPY->getDefaultArgument().getArgument().getAsType());
7121 }
7122
7123 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7124 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7125 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7126 return false;
7127
7128 Expr *DefaultArgumentX =
7129 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7130 Expr *DefaultArgumentY =
7131 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7132 llvm::FoldingSetNodeID XID, YID;
7133 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7134 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7135 return XID == YID;
7136 }
7137
7138 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7139 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7140
7141 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7142 return false;
7143
7144 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7145 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7146 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7147}
7148
7150 if (auto *NS = X->getAsNamespace())
7151 return NS;
7152 if (auto *NAS = X->getAsNamespaceAlias())
7153 return NAS->getNamespace();
7154 return nullptr;
7155}
7156
7158 const NestedNameSpecifier *Y) {
7159 if (auto *NSX = getNamespace(X)) {
7160 auto *NSY = getNamespace(Y);
7161 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
7162 return false;
7163 } else if (X->getKind() != Y->getKind())
7164 return false;
7165
7166 // FIXME: For namespaces and types, we're permitted to check that the entity
7167 // is named via the same tokens. We should probably do so.
7168 switch (X->getKind()) {
7170 if (X->getAsIdentifier() != Y->getAsIdentifier())
7171 return false;
7172 break;
7175 // We've already checked that we named the same namespace.
7176 break;
7179 if (X->getAsType()->getCanonicalTypeInternal() !=
7181 return false;
7182 break;
7185 return true;
7186 }
7187
7188 // Recurse into earlier portion of NNS, if any.
7189 auto *PX = X->getPrefix();
7190 auto *PY = Y->getPrefix();
7191 if (PX && PY)
7192 return isSameQualifier(PX, PY);
7193 return !PX && !PY;
7194}
7195
7196/// Determine whether the attributes we can overload on are identical for A and
7197/// B. Will ignore any overloadable attrs represented in the type of A and B.
7199 const FunctionDecl *B) {
7200 // Note that pass_object_size attributes are represented in the function's
7201 // ExtParameterInfo, so we don't need to check them here.
7202
7203 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7204 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7205 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7206
7207 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7208 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7209 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7210
7211 // Return false if the number of enable_if attributes is different.
7212 if (!Cand1A || !Cand2A)
7213 return false;
7214
7215 Cand1ID.clear();
7216 Cand2ID.clear();
7217
7218 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7219 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7220
7221 // Return false if any of the enable_if expressions of A and B are
7222 // different.
7223 if (Cand1ID != Cand2ID)
7224 return false;
7225 }
7226 return true;
7227}
7228
7229bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7230 // Caution: this function is called by the AST reader during deserialization,
7231 // so it cannot rely on AST invariants being met. Non-trivial accessors
7232 // should be avoided, along with any traversal of redeclaration chains.
7233
7234 if (X == Y)
7235 return true;
7236
7237 if (X->getDeclName() != Y->getDeclName())
7238 return false;
7239
7240 // Must be in the same context.
7241 //
7242 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7243 // could be two different declarations of the same function. (We will fix the
7244 // semantic DC to refer to the primary definition after merging.)
7245 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7246 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
7247 return false;
7248
7249 // Two typedefs refer to the same entity if they have the same underlying
7250 // type.
7251 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7252 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7253 return hasSameType(TypedefX->getUnderlyingType(),
7254 TypedefY->getUnderlyingType());
7255
7256 // Must have the same kind.
7257 if (X->getKind() != Y->getKind())
7258 return false;
7259
7260 // Objective-C classes and protocols with the same name always match.
7261 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
7262 return true;
7263
7264 if (isa<ClassTemplateSpecializationDecl>(X)) {
7265 // No need to handle these here: we merge them when adding them to the
7266 // template.
7267 return false;
7268 }
7269
7270 // Compatible tags match.
7271 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7272 const auto *TagY = cast<TagDecl>(Y);
7273 return (TagX->getTagKind() == TagY->getTagKind()) ||
7274 ((TagX->getTagKind() == TagTypeKind::Struct ||
7275 TagX->getTagKind() == TagTypeKind::Class ||
7276 TagX->getTagKind() == TagTypeKind::Interface) &&
7277 (TagY->getTagKind() == TagTypeKind::Struct ||
7278 TagY->getTagKind() == TagTypeKind::Class ||
7279 TagY->getTagKind() == TagTypeKind::Interface));
7280 }
7281
7282 // Functions with the same type and linkage match.
7283 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7284 // functions, etc.
7285 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7286 const auto *FuncY = cast<FunctionDecl>(Y);
7287 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7288 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7289 if (CtorX->getInheritedConstructor() &&
7290 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7291 CtorY->getInheritedConstructor().getConstructor()))
7292 return false;
7293 }
7294
7295 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7296 return false;
7297
7298 // Multiversioned functions with different feature strings are represented
7299 // as separate declarations.
7300 if (FuncX->isMultiVersion()) {
7301 const auto *TAX = FuncX->getAttr<TargetAttr>();
7302 const auto *TAY = FuncY->getAttr<TargetAttr>();
7303 assert(TAX && TAY && "Multiversion Function without target attribute");
7304
7305 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7306 return false;
7307 }
7308
7309 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7310 // not the same entity if they are constrained.
7311 if ((FuncX->isMemberLikeConstrainedFriend() ||
7312 FuncY->isMemberLikeConstrainedFriend()) &&
7313 !FuncX->getLexicalDeclContext()->Equals(
7314 FuncY->getLexicalDeclContext())) {
7315 return false;
7316 }
7317
7318 if (!isSameConstraintExpr(FuncX->getTrailingRequiresClause(),
7319 FuncY->getTrailingRequiresClause()))
7320 return false;
7321
7322 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7323 // Map to the first declaration that we've already merged into this one.
7324 // The TSI of redeclarations might not match (due to calling conventions
7325 // being inherited onto the type but not the TSI), but the TSI type of
7326 // the first declaration of the function should match across modules.
7327 FD = FD->getCanonicalDecl();
7328 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7329 : FD->getType();
7330 };
7331 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7332 if (!hasSameType(XT, YT)) {
7333 // We can get functions with different types on the redecl chain in C++17
7334 // if they have differing exception specifications and at least one of
7335 // the excpetion specs is unresolved.
7336 auto *XFPT = XT->getAs<FunctionProtoType>();
7337 auto *YFPT = YT->getAs<FunctionProtoType>();
7338 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7339 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7342 return true;
7343 return false;
7344 }
7345
7346 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7347 hasSameOverloadableAttrs(FuncX, FuncY);
7348 }
7349
7350 // Variables with the same type and linkage match.
7351 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7352 const auto *VarY = cast<VarDecl>(Y);
7353 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7354 // During deserialization, we might compare variables before we load
7355 // their types. Assume the types will end up being the same.
7356 if (VarX->getType().isNull() || VarY->getType().isNull())
7357 return true;
7358
7359 if (hasSameType(VarX->getType(), VarY->getType()))
7360 return true;
7361
7362 // We can get decls with different types on the redecl chain. Eg.
7363 // template <typename T> struct S { static T Var[]; }; // #1
7364 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7365 // Only? happens when completing an incomplete array type. In this case
7366 // when comparing #1 and #2 we should go through their element type.
7367 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7368 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7369 if (!VarXTy || !VarYTy)
7370 return false;
7371 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7372 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7373 }
7374 return false;
7375 }
7376
7377 // Namespaces with the same name and inlinedness match.
7378 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7379 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7380 return NamespaceX->isInline() == NamespaceY->isInline();
7381 }
7382
7383 // Identical template names and kinds match if their template parameter lists
7384 // and patterns match.
7385 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7386 const auto *TemplateY = cast<TemplateDecl>(Y);
7387
7388 // ConceptDecl wouldn't be the same if their constraint expression differs.
7389 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7390 const auto *ConceptY = cast<ConceptDecl>(Y);
7391 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7392 ConceptY->getConstraintExpr()))
7393 return false;
7394 }
7395
7396 return isSameEntity(TemplateX->getTemplatedDecl(),
7397 TemplateY->getTemplatedDecl()) &&
7398 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7399 TemplateY->getTemplateParameters());
7400 }
7401
7402 // Fields with the same name and the same type match.
7403 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7404 const auto *FDY = cast<FieldDecl>(Y);
7405 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7406 return hasSameType(FDX->getType(), FDY->getType());
7407 }
7408
7409 // Indirect fields with the same target field match.
7410 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7411 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7412 return IFDX->getAnonField()->getCanonicalDecl() ==
7413 IFDY->getAnonField()->getCanonicalDecl();
7414 }
7415
7416 // Enumerators with the same name match.
7417 if (isa<EnumConstantDecl>(X))
7418 // FIXME: Also check the value is odr-equivalent.
7419 return true;
7420
7421 // Using shadow declarations with the same target match.
7422 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7423 const auto *USY = cast<UsingShadowDecl>(Y);
7424 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7425 }
7426
7427 // Using declarations with the same qualifier match. (We already know that
7428 // the name matches.)
7429 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7430 const auto *UY = cast<UsingDecl>(Y);
7431 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7432 UX->hasTypename() == UY->hasTypename() &&
7433 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7434 }
7435 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7436 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7437 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7438 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7439 }
7440 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7441 return isSameQualifier(
7442 UX->getQualifier(),
7443 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7444 }
7445
7446 // Using-pack declarations are only created by instantiation, and match if
7447 // they're instantiated from matching UnresolvedUsing...Decls.
7448 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7449 return declaresSameEntity(
7450 UX->getInstantiatedFromUsingDecl(),
7451 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7452 }
7453
7454 // Namespace alias definitions with the same target match.
7455 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7456 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7457 return NAX->getNamespace()->Equals(NAY->getNamespace());
7458 }
7459
7460 return false;
7461}
7462
7465 switch (Arg.getKind()) {
7467 return Arg;
7468
7470 return Arg;
7471
7473 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7475 Arg.getIsDefaulted());
7476 }
7477
7480 /*isNullPtr*/ true, Arg.getIsDefaulted());
7481
7484 Arg.getIsDefaulted());
7485
7487 return TemplateArgument(
7490
7493
7495 return TemplateArgument(*this,
7498
7501 /*isNullPtr*/ false, Arg.getIsDefaulted());
7502
7504 bool AnyNonCanonArgs = false;
7505 auto CanonArgs = ::getCanonicalTemplateArguments(
7506 *this, Arg.pack_elements(), AnyNonCanonArgs);
7507 if (!AnyNonCanonArgs)
7508 return Arg;
7510 const_cast<ASTContext &>(*this), CanonArgs);
7511 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7512 return NewArg;
7513 }
7514 }
7515
7516 // Silence GCC warning
7517 llvm_unreachable("Unhandled template argument kind");
7518}
7519
7522 if (!NNS)
7523 return nullptr;
7524
7525 switch (NNS->getKind()) {
7527 // Canonicalize the prefix but keep the identifier the same.
7528 return NestedNameSpecifier::Create(*this,
7530 NNS->getAsIdentifier());
7531
7533 // A namespace is canonical; build a nested-name-specifier with
7534 // this namespace and no prefix.
7535 return NestedNameSpecifier::Create(*this, nullptr,
7536 NNS->getAsNamespace()->getFirstDecl());
7537
7539 // A namespace is canonical; build a nested-name-specifier with
7540 // this namespace and no prefix.
7542 *this, nullptr,
7544
7545 // The difference between TypeSpec and TypeSpecWithTemplate is that the
7546 // latter will have the 'template' keyword when printed.
7549 const Type *T = getCanonicalType(NNS->getAsType());
7550
7551 // If we have some kind of dependent-named type (e.g., "typename T::type"),
7552 // break it apart into its prefix and identifier, then reconsititute those
7553 // as the canonical nested-name-specifier. This is required to canonicalize
7554 // a dependent nested-name-specifier involving typedefs of dependent-name
7555 // types, e.g.,
7556 // typedef typename T::type T1;
7557 // typedef typename T1::type T2;
7558 if (const auto *DNT = T->getAs<DependentNameType>())
7559 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
7560 DNT->getIdentifier());
7561 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>())
7562 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, T);
7563
7564 // TODO: Set 'Template' parameter to true for other template types.
7565 return NestedNameSpecifier::Create(*this, nullptr, false, T);
7566 }
7567
7570 // The global specifier and __super specifer are canonical and unique.
7571 return NNS;
7572 }
7573
7574 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
7575}
7576
7578 // Handle the non-qualified case efficiently.
7579 if (!T.hasLocalQualifiers()) {
7580 // Handle the common positive case fast.
7581 if (const auto *AT = dyn_cast<ArrayType>(T))
7582 return AT;
7583 }
7584
7585 // Handle the common negative case fast.
7586 if (!isa<ArrayType>(T.getCanonicalType()))
7587 return nullptr;
7588
7589 // Apply any qualifiers from the array type to the element type. This
7590 // implements C99 6.7.3p8: "If the specification of an array type includes
7591 // any type qualifiers, the element type is so qualified, not the array type."
7592
7593 // If we get here, we either have type qualifiers on the type, or we have
7594 // sugar such as a typedef in the way. If we have type qualifiers on the type
7595 // we must propagate them down into the element type.
7596
7597 SplitQualType split = T.getSplitDesugaredType();
7598 Qualifiers qs = split.Quals;
7599
7600 // If we have a simple case, just return now.
7601 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
7602 if (!ATy || qs.empty())
7603 return ATy;
7604
7605 // Otherwise, we have an array and we have qualifiers on it. Push the
7606 // qualifiers into the array element type and return a new array type.
7607 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
7608
7609 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
7610 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
7611 CAT->getSizeExpr(),
7612 CAT->getSizeModifier(),
7613 CAT->getIndexTypeCVRQualifiers()));
7614 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
7615 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
7616 IAT->getSizeModifier(),
7617 IAT->getIndexTypeCVRQualifiers()));
7618
7619 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
7620 return cast<ArrayType>(
7622 DSAT->getSizeExpr(),
7623 DSAT->getSizeModifier(),
7624 DSAT->getIndexTypeCVRQualifiers(),
7625 DSAT->getBracketsRange()));
7626
7627 const auto *VAT = cast<VariableArrayType>(ATy);
7628 return cast<ArrayType>(getVariableArrayType(NewEltTy,
7629 VAT->getSizeExpr(),
7630 VAT->getSizeModifier(),
7631 VAT->getIndexTypeCVRQualifiers(),
7632 VAT->getBracketsRange()));
7633}
7634
7637 return getArrayParameterType(T);
7638 if (T->isArrayType() || T->isFunctionType())
7639 return getDecayedType(T);
7640 return T;
7641}
7642
7646 return T.getUnqualifiedType();
7647}
7648
7650 // C++ [except.throw]p3:
7651 // A throw-expression initializes a temporary object, called the exception
7652 // object, the type of which is determined by removing any top-level
7653 // cv-qualifiers from the static type of the operand of throw and adjusting
7654 // the type from "array of T" or "function returning T" to "pointer to T"
7655 // or "pointer to function returning T", [...]
7657 if (T->isArrayType() || T->isFunctionType())
7658 T = getDecayedType(T);
7659 return T.getUnqualifiedType();
7660}
7661
7662/// getArrayDecayedType - Return the properly qualified result of decaying the
7663/// specified array type to a pointer. This operation is non-trivial when
7664/// handling typedefs etc. The canonical type of "T" must be an array type,
7665/// this returns a pointer to a properly qualified element of the array.
7666///
7667/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
7669 // Get the element type with 'getAsArrayType' so that we don't lose any
7670 // typedefs in the element type of the array. This also handles propagation
7671 // of type qualifiers from the array type into the element type if present
7672 // (C99 6.7.3p8).
7673 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
7674 assert(PrettyArrayType && "Not an array type!");
7675
7676 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
7677
7678 // int x[restrict 4] -> int *restrict
7680 PrettyArrayType->getIndexTypeQualifiers());
7681
7682 // int x[_Nullable] -> int * _Nullable
7683 if (auto Nullability = Ty->getNullability()) {
7684 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
7685 Result, Result);
7686 }
7687 return Result;
7688}
7689
7691 return getBaseElementType(array->getElementType());
7692}
7693
7695 Qualifiers qs;
7696 while (true) {
7697 SplitQualType split = type.getSplitDesugaredType();
7698 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
7699 if (!array) break;
7700
7701 type = array->getElementType();
7703 }
7704
7705 return getQualifiedType(type, qs);
7706}
7707
7708/// getConstantArrayElementCount - Returns number of constant array elements.
7709uint64_t
7711 uint64_t ElementCount = 1;
7712 do {
7713 ElementCount *= CA->getZExtSize();
7714 CA = dyn_cast_or_null<ConstantArrayType>(
7716 } while (CA);
7717 return ElementCount;
7718}
7719
7721 const ArrayInitLoopExpr *AILE) const {
7722 if (!AILE)
7723 return 0;
7724
7725 uint64_t ElementCount = 1;
7726
7727 do {
7728 ElementCount *= AILE->getArraySize().getZExtValue();
7729 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
7730 } while (AILE);
7731
7732 return ElementCount;
7733}
7734
7735/// getFloatingRank - Return a relative rank for floating point types.
7736/// This routine will assert if passed a built-in type that isn't a float.
7738 if (const auto *CT = T->getAs<ComplexType>())
7739 return getFloatingRank(CT->getElementType());
7740
7741 switch (T->castAs<BuiltinType>()->getKind()) {
7742 default: llvm_unreachable("getFloatingRank(): not a floating type");
7743 case BuiltinType::Float16: return Float16Rank;
7744 case BuiltinType::Half: return HalfRank;
7745 case BuiltinType::Float: return FloatRank;
7746 case BuiltinType::Double: return DoubleRank;
7747 case BuiltinType::LongDouble: return LongDoubleRank;
7748 case BuiltinType::Float128: return Float128Rank;
7749 case BuiltinType::BFloat16: return BFloat16Rank;
7750 case BuiltinType::Ibm128: return Ibm128Rank;
7751 }
7752}
7753
7754/// getFloatingTypeOrder - Compare the rank of the two specified floating
7755/// point types, ignoring the domain of the type (i.e. 'double' ==
7756/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
7757/// LHS < RHS, return -1.
7759 FloatingRank LHSR = getFloatingRank(LHS);
7760 FloatingRank RHSR = getFloatingRank(RHS);
7761
7762 if (LHSR == RHSR)
7763 return 0;
7764 if (LHSR > RHSR)
7765 return 1;
7766 return -1;
7767}
7768
7771 return 0;
7772 return getFloatingTypeOrder(LHS, RHS);
7773}
7774
7775/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
7776/// routine will assert if passed a built-in type that isn't an integer or enum,
7777/// or if it is not canonicalized.
7778unsigned ASTContext::getIntegerRank(const Type *T) const {
7779 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
7780
7781 // Results in this 'losing' to any type of the same size, but winning if
7782 // larger.
7783 if (const auto *EIT = dyn_cast<BitIntType>(T))
7784 return 0 + (EIT->getNumBits() << 3);
7785
7786 switch (cast<BuiltinType>(T)->getKind()) {
7787 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
7788 case BuiltinType::Bool:
7789 return 1 + (getIntWidth(BoolTy) << 3);
7790 case BuiltinType::Char_S:
7791 case BuiltinType::Char_U:
7792 case BuiltinType::SChar:
7793 case BuiltinType::UChar:
7794 return 2 + (getIntWidth(CharTy) << 3);
7795 case BuiltinType::Short:
7796 case BuiltinType::UShort:
7797 return 3 + (getIntWidth(ShortTy) << 3);
7798 case BuiltinType::Int:
7799 case BuiltinType::UInt:
7800 return 4 + (getIntWidth(IntTy) << 3);
7801 case BuiltinType::Long:
7802 case BuiltinType::ULong:
7803 return 5 + (getIntWidth(LongTy) << 3);
7804 case BuiltinType::LongLong:
7805 case BuiltinType::ULongLong:
7806 return 6 + (getIntWidth(LongLongTy) << 3);
7807 case BuiltinType::Int128:
7808 case BuiltinType::UInt128:
7809 return 7 + (getIntWidth(Int128Ty) << 3);
7810
7811 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
7812 // their underlying types" [c++20 conv.rank]
7813 case BuiltinType::Char8:
7814 return getIntegerRank(UnsignedCharTy.getTypePtr());
7815 case BuiltinType::Char16:
7816 return getIntegerRank(
7817 getFromTargetType(Target->getChar16Type()).getTypePtr());
7818 case BuiltinType::Char32:
7819 return getIntegerRank(
7820 getFromTargetType(Target->getChar32Type()).getTypePtr());
7821 case BuiltinType::WChar_S:
7822 case BuiltinType::WChar_U:
7823 return getIntegerRank(
7824 getFromTargetType(Target->getWCharType()).getTypePtr());
7825 }
7826}
7827
7828/// Whether this is a promotable bitfield reference according
7829/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
7830///
7831/// \returns the type this bit-field will promote to, or NULL if no
7832/// promotion occurs.
7834 if (E->isTypeDependent() || E->isValueDependent())
7835 return {};
7836
7837 // C++ [conv.prom]p5:
7838 // If the bit-field has an enumerated type, it is treated as any other
7839 // value of that type for promotion purposes.
7841 return {};
7842
7843 // FIXME: We should not do this unless E->refersToBitField() is true. This
7844 // matters in C where getSourceBitField() will find bit-fields for various
7845 // cases where the source expression is not a bit-field designator.
7846
7847 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
7848 if (!Field)
7849 return {};
7850
7851 QualType FT = Field->getType();
7852
7853 uint64_t BitWidth = Field->getBitWidthValue();
7854 uint64_t IntSize = getTypeSize(IntTy);
7855 // C++ [conv.prom]p5:
7856 // A prvalue for an integral bit-field can be converted to a prvalue of type
7857 // int if int can represent all the values of the bit-field; otherwise, it
7858 // can be converted to unsigned int if unsigned int can represent all the
7859 // values of the bit-field. If the bit-field is larger yet, no integral
7860 // promotion applies to it.
7861 // C11 6.3.1.1/2:
7862 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
7863 // If an int can represent all values of the original type (as restricted by
7864 // the width, for a bit-field), the value is converted to an int; otherwise,
7865 // it is converted to an unsigned int.
7866 //
7867 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
7868 // We perform that promotion here to match GCC and C++.
7869 // FIXME: C does not permit promotion of an enum bit-field whose rank is
7870 // greater than that of 'int'. We perform that promotion to match GCC.
7871 //
7872 // C23 6.3.1.1p2:
7873 // The value from a bit-field of a bit-precise integer type is converted to
7874 // the corresponding bit-precise integer type. (The rest is the same as in
7875 // C11.)
7876 if (QualType QT = Field->getType(); QT->isBitIntType())
7877 return QT;
7878
7879 if (BitWidth < IntSize)
7880 return IntTy;
7881
7882 if (BitWidth == IntSize)
7883 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
7884
7885 // Bit-fields wider than int are not subject to promotions, and therefore act
7886 // like the base type. GCC has some weird bugs in this area that we
7887 // deliberately do not follow (GCC follows a pre-standard resolution to
7888 // C's DR315 which treats bit-width as being part of the type, and this leaks
7889 // into their semantics in some cases).
7890 return {};
7891}
7892
7893/// getPromotedIntegerType - Returns the type that Promotable will
7894/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
7895/// integer type.
7897 assert(!Promotable.isNull());
7898 assert(isPromotableIntegerType(Promotable));
7899 if (const auto *ET = Promotable->getAs<EnumType>())
7900 return ET->getDecl()->getPromotionType();
7901
7902 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
7903 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
7904 // (3.9.1) can be converted to a prvalue of the first of the following
7905 // types that can represent all the values of its underlying type:
7906 // int, unsigned int, long int, unsigned long int, long long int, or
7907 // unsigned long long int [...]
7908 // FIXME: Is there some better way to compute this?
7909 if (BT->getKind() == BuiltinType::WChar_S ||
7910 BT->getKind() == BuiltinType::WChar_U ||
7911 BT->getKind() == BuiltinType::Char8 ||
7912 BT->getKind() == BuiltinType::Char16 ||
7913 BT->getKind() == BuiltinType::Char32) {
7914 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
7915 uint64_t FromSize = getTypeSize(BT);
7916 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
7918 for (const auto &PT : PromoteTypes) {
7919 uint64_t ToSize = getTypeSize(PT);
7920 if (FromSize < ToSize ||
7921 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
7922 return PT;
7923 }
7924 llvm_unreachable("char type should fit into long long");
7925 }
7926 }
7927
7928 // At this point, we should have a signed or unsigned integer type.
7929 if (Promotable->isSignedIntegerType())
7930 return IntTy;
7931 uint64_t PromotableSize = getIntWidth(Promotable);
7932 uint64_t IntSize = getIntWidth(IntTy);
7933 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
7934 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
7935}
7936
7937/// Recurses in pointer/array types until it finds an objc retainable
7938/// type and returns its ownership.
7940 while (!T.isNull()) {
7941 if (T.getObjCLifetime() != Qualifiers::OCL_None)
7942 return T.getObjCLifetime();
7943 if (T->isArrayType())
7945 else if (const auto *PT = T->getAs<PointerType>())
7946 T = PT->getPointeeType();
7947 else if (const auto *RT = T->getAs<ReferenceType>())
7948 T = RT->getPointeeType();
7949 else
7950 break;
7951 }
7952
7953 return Qualifiers::OCL_None;
7954}
7955
7956static const Type *getIntegerTypeForEnum(const EnumType *ET) {
7957 // Incomplete enum types are not treated as integer types.
7958 // FIXME: In C++, enum types are never integer types.
7959 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
7960 return ET->getDecl()->getIntegerType().getTypePtr();
7961 return nullptr;
7962}
7963
7964/// getIntegerTypeOrder - Returns the highest ranked integer type:
7965/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
7966/// LHS < RHS, return -1.
7968 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
7969 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
7970
7971 // Unwrap enums to their underlying type.
7972 if (const auto *ET = dyn_cast<EnumType>(LHSC))
7973 LHSC = getIntegerTypeForEnum(ET);
7974 if (const auto *ET = dyn_cast<EnumType>(RHSC))
7975 RHSC = getIntegerTypeForEnum(ET);
7976
7977 if (LHSC == RHSC) return 0;
7978
7979 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
7980 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
7981
7982 unsigned LHSRank = getIntegerRank(LHSC);
7983 unsigned RHSRank = getIntegerRank(RHSC);
7984
7985 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
7986 if (LHSRank == RHSRank) return 0;
7987 return LHSRank > RHSRank ? 1 : -1;
7988 }
7989
7990 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
7991 if (LHSUnsigned) {
7992 // If the unsigned [LHS] type is larger, return it.
7993 if (LHSRank >= RHSRank)
7994 return 1;
7995
7996 // If the signed type can represent all values of the unsigned type, it
7997 // wins. Because we are dealing with 2's complement and types that are
7998 // powers of two larger than each other, this is always safe.
7999 return -1;
8000 }
8001
8002 // If the unsigned [RHS] type is larger, return it.
8003 if (RHSRank >= LHSRank)
8004 return -1;
8005
8006 // If the signed type can represent all values of the unsigned type, it
8007 // wins. Because we are dealing with 2's complement and types that are
8008 // powers of two larger than each other, this is always safe.
8009 return 1;
8010}
8011
8013 if (CFConstantStringTypeDecl)
8014 return CFConstantStringTypeDecl;
8015
8016 assert(!CFConstantStringTagDecl &&
8017 "tag and typedef should be initialized together");
8018 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8019 CFConstantStringTagDecl->startDefinition();
8020
8021 struct {
8022 QualType Type;
8023 const char *Name;
8024 } Fields[5];
8025 unsigned Count = 0;
8026
8027 /// Objective-C ABI
8028 ///
8029 /// typedef struct __NSConstantString_tag {
8030 /// const int *isa;
8031 /// int flags;
8032 /// const char *str;
8033 /// long length;
8034 /// } __NSConstantString;
8035 ///
8036 /// Swift ABI (4.1, 4.2)
8037 ///
8038 /// typedef struct __NSConstantString_tag {
8039 /// uintptr_t _cfisa;
8040 /// uintptr_t _swift_rc;
8041 /// _Atomic(uint64_t) _cfinfoa;
8042 /// const char *_ptr;
8043 /// uint32_t _length;
8044 /// } __NSConstantString;
8045 ///
8046 /// Swift ABI (5.0)
8047 ///
8048 /// typedef struct __NSConstantString_tag {
8049 /// uintptr_t _cfisa;
8050 /// uintptr_t _swift_rc;
8051 /// _Atomic(uint64_t) _cfinfoa;
8052 /// const char *_ptr;
8053 /// uintptr_t _length;
8054 /// } __NSConstantString;
8055
8056 const auto CFRuntime = getLangOpts().CFRuntime;
8057 if (static_cast<unsigned>(CFRuntime) <
8058 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8059 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8060 Fields[Count++] = { IntTy, "flags" };
8061 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8062 Fields[Count++] = { LongTy, "length" };
8063 } else {
8064 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8065 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8066 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8067 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8070 Fields[Count++] = { IntTy, "_ptr" };
8071 else
8072 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8073 }
8074
8075 // Create fields
8076 for (unsigned i = 0; i < Count; ++i) {
8077 FieldDecl *Field =
8078 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8079 SourceLocation(), &Idents.get(Fields[i].Name),
8080 Fields[i].Type, /*TInfo=*/nullptr,
8081 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8082 Field->setAccess(AS_public);
8083 CFConstantStringTagDecl->addDecl(Field);
8084 }
8085
8086 CFConstantStringTagDecl->completeDefinition();
8087 // This type is designed to be compatible with NSConstantString, but cannot
8088 // use the same name, since NSConstantString is an interface.
8089 auto tagType = getTagDeclType(CFConstantStringTagDecl);
8090 CFConstantStringTypeDecl =
8091 buildImplicitTypedef(tagType, "__NSConstantString");
8092
8093 return CFConstantStringTypeDecl;
8094}
8095
8097 if (!CFConstantStringTagDecl)
8098 getCFConstantStringDecl(); // Build the tag and the typedef.
8099 return CFConstantStringTagDecl;
8100}
8101
8102// getCFConstantStringType - Return the type used for constant CFStrings.
8105}
8106
8108 if (ObjCSuperType.isNull()) {
8109 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8110 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8111 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
8112 }
8113 return ObjCSuperType;
8114}
8115
8117 const auto *TD = T->castAs<TypedefType>();
8118 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
8119 const auto *TagType =
8120 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
8121 CFConstantStringTagDecl = TagType->getDecl();
8122}
8123
8125 if (BlockDescriptorType)
8126 return getTagDeclType(BlockDescriptorType);
8127
8128 RecordDecl *RD;
8129 // FIXME: Needs the FlagAppleBlock bit.
8130 RD = buildImplicitRecord("__block_descriptor");
8131 RD->startDefinition();
8132
8133 QualType FieldTypes[] = {
8136 };
8137
8138 static const char *const FieldNames[] = {
8139 "reserved",
8140 "Size"
8141 };
8142
8143 for (size_t i = 0; i < 2; ++i) {
8145 *this, RD, SourceLocation(), SourceLocation(),
8146 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8147 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8148 Field->setAccess(AS_public);
8149 RD->addDecl(Field);
8150 }
8151
8152 RD->completeDefinition();
8153
8154 BlockDescriptorType = RD;
8155
8156 return getTagDeclType(BlockDescriptorType);
8157}
8158
8160 if (BlockDescriptorExtendedType)
8161 return getTagDeclType(BlockDescriptorExtendedType);
8162
8163 RecordDecl *RD;
8164 // FIXME: Needs the FlagAppleBlock bit.
8165 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8166 RD->startDefinition();
8167
8168 QualType FieldTypes[] = {
8173 };
8174
8175 static const char *const FieldNames[] = {
8176 "reserved",
8177 "Size",
8178 "CopyFuncPtr",
8179 "DestroyFuncPtr"
8180 };
8181
8182 for (size_t i = 0; i < 4; ++i) {
8184 *this, RD, SourceLocation(), SourceLocation(),
8185 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8186 /*BitWidth=*/nullptr,
8187 /*Mutable=*/false, ICIS_NoInit);
8188 Field->setAccess(AS_public);
8189 RD->addDecl(Field);
8190 }
8191
8192 RD->completeDefinition();
8193
8194 BlockDescriptorExtendedType = RD;
8195 return getTagDeclType(BlockDescriptorExtendedType);
8196}
8197
8199 const auto *BT = dyn_cast<BuiltinType>(T);
8200
8201 if (!BT) {
8202 if (isa<PipeType>(T))
8203 return OCLTK_Pipe;
8204
8205 return OCLTK_Default;
8206 }
8207
8208 switch (BT->getKind()) {
8209#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8210 case BuiltinType::Id: \
8211 return OCLTK_Image;
8212#include "clang/Basic/OpenCLImageTypes.def"
8213
8214 case BuiltinType::OCLClkEvent:
8215 return OCLTK_ClkEvent;
8216
8217 case BuiltinType::OCLEvent:
8218 return OCLTK_Event;
8219
8220 case BuiltinType::OCLQueue:
8221 return OCLTK_Queue;
8222
8223 case BuiltinType::OCLReserveID:
8224 return OCLTK_ReserveID;
8225
8226 case BuiltinType::OCLSampler:
8227 return OCLTK_Sampler;
8228
8229 default:
8230 return OCLTK_Default;
8231 }
8232}
8233
8235 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8236}
8237
8238/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8239/// requires copy/dispose. Note that this must match the logic
8240/// in buildByrefHelpers.
8242 const VarDecl *D) {
8243 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8244 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8245 if (!copyExpr && record->hasTrivialDestructor()) return false;
8246
8247 return true;
8248 }
8249
8250 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8251 // move or destroy.
8253 return true;
8254
8255 if (!Ty->isObjCRetainableType()) return false;
8256
8257 Qualifiers qs = Ty.getQualifiers();
8258
8259 // If we have lifetime, that dominates.
8260 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8261 switch (lifetime) {
8262 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8263
8264 // These are just bits as far as the runtime is concerned.
8267 return false;
8268
8269 // These cases should have been taken care of when checking the type's
8270 // non-triviality.
8273 llvm_unreachable("impossible");
8274 }
8275 llvm_unreachable("fell out of lifetime switch!");
8276 }
8277 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8279}
8280
8282 Qualifiers::ObjCLifetime &LifeTime,
8283 bool &HasByrefExtendedLayout) const {
8284 if (!getLangOpts().ObjC ||
8285 getLangOpts().getGC() != LangOptions::NonGC)
8286 return false;
8287
8288 HasByrefExtendedLayout = false;
8289 if (Ty->isRecordType()) {
8290 HasByrefExtendedLayout = true;
8291 LifeTime = Qualifiers::OCL_None;
8292 } else if ((LifeTime = Ty.getObjCLifetime())) {
8293 // Honor the ARC qualifiers.
8294 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8295 // The MRR rule.
8297 } else {
8298 LifeTime = Qualifiers::OCL_None;
8299 }
8300 return true;
8301}
8302
8304 assert(Target && "Expected target to be initialized");
8305 const llvm::Triple &T = Target->getTriple();
8306 // Windows is LLP64 rather than LP64
8307 if (T.isOSWindows() && T.isArch64Bit())
8308 return UnsignedLongLongTy;
8309 return UnsignedLongTy;
8310}
8311
8313 assert(Target && "Expected target to be initialized");
8314 const llvm::Triple &T = Target->getTriple();
8315 // Windows is LLP64 rather than LP64
8316 if (T.isOSWindows() && T.isArch64Bit())
8317 return LongLongTy;
8318 return LongTy;
8319}
8320
8322 if (!ObjCInstanceTypeDecl)
8323 ObjCInstanceTypeDecl =
8324 buildImplicitTypedef(getObjCIdType(), "instancetype");
8325 return ObjCInstanceTypeDecl;
8326}
8327
8328// This returns true if a type has been typedefed to BOOL:
8329// typedef <type> BOOL;
8331 if (const auto *TT = dyn_cast<TypedefType>(T))
8332 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8333 return II->isStr("BOOL");
8334
8335 return false;
8336}
8337
8338/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8339/// purpose.
8341 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8342 return CharUnits::Zero();
8343
8345
8346 // Make all integer and enum types at least as large as an int
8347 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8348 sz = std::max(sz, getTypeSizeInChars(IntTy));
8349 // Treat arrays as pointers, since that's how they're passed in.
8350 else if (type->isArrayType())
8352 return sz;
8353}
8354
8356 return getTargetInfo().getCXXABI().isMicrosoft() &&
8357 VD->isStaticDataMember() &&
8359 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
8360}
8361
8364 if (!VD->isInline())
8366
8367 // In almost all cases, it's a weak definition.
8368 auto *First = VD->getFirstDecl();
8369 if (First->isInlineSpecified() || !First->isStaticDataMember())
8371
8372 // If there's a file-context declaration in this translation unit, it's a
8373 // non-discardable definition.
8374 for (auto *D : VD->redecls())
8376 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8378
8379 // If we've not seen one yet, we don't know.
8381}
8382
8383static std::string charUnitsToString(const CharUnits &CU) {
8384 return llvm::itostr(CU.getQuantity());
8385}
8386
8387/// getObjCEncodingForBlock - Return the encoded type for this block
8388/// declaration.
8390 std::string S;
8391
8392 const BlockDecl *Decl = Expr->getBlockDecl();
8393 QualType BlockTy =
8395 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8396 // Encode result type.
8397 if (getLangOpts().EncodeExtendedBlockSig)
8399 true /*Extended*/);
8400 else
8401 getObjCEncodingForType(BlockReturnTy, S);
8402 // Compute size of all parameters.
8403 // Start with computing size of a pointer in number of bytes.
8404 // FIXME: There might(should) be a better way of doing this computation!
8406 CharUnits ParmOffset = PtrSize;
8407 for (auto *PI : Decl->parameters()) {
8408 QualType PType = PI->getType();
8410 if (sz.isZero())
8411 continue;
8412 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8413 ParmOffset += sz;
8414 }
8415 // Size of the argument frame
8416 S += charUnitsToString(ParmOffset);
8417 // Block pointer and offset.
8418 S += "@?0";
8419
8420 // Argument types.
8421 ParmOffset = PtrSize;
8422 for (auto *PVDecl : Decl->parameters()) {
8423 QualType PType = PVDecl->getOriginalType();
8424 if (const auto *AT =
8425 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8426 // Use array's original type only if it has known number of
8427 // elements.
8428 if (!isa<ConstantArrayType>(AT))
8429 PType = PVDecl->getType();
8430 } else if (PType->isFunctionType())
8431 PType = PVDecl->getType();
8432 if (getLangOpts().EncodeExtendedBlockSig)
8434 S, true /*Extended*/);
8435 else
8436 getObjCEncodingForType(PType, S);
8437 S += charUnitsToString(ParmOffset);
8438 ParmOffset += getObjCEncodingTypeSize(PType);
8439 }
8440
8441 return S;
8442}
8443
8444std::string
8446 std::string S;
8447 // Encode result type.
8448 getObjCEncodingForType(Decl->getReturnType(), S);
8449 CharUnits ParmOffset;
8450 // Compute size of all parameters.
8451 for (auto *PI : Decl->parameters()) {
8452 QualType PType = PI->getType();
8454 if (sz.isZero())
8455 continue;
8456
8457 assert(sz.isPositive() &&
8458 "getObjCEncodingForFunctionDecl - Incomplete param type");
8459 ParmOffset += sz;
8460 }
8461 S += charUnitsToString(ParmOffset);
8462 ParmOffset = CharUnits::Zero();
8463
8464 // Argument types.
8465 for (auto *PVDecl : Decl->parameters()) {
8466 QualType PType = PVDecl->getOriginalType();
8467 if (const auto *AT =
8468 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8469 // Use array's original type only if it has known number of
8470 // elements.
8471 if (!isa<ConstantArrayType>(AT))
8472 PType = PVDecl->getType();
8473 } else if (PType->isFunctionType())
8474 PType = PVDecl->getType();
8475 getObjCEncodingForType(PType, S);
8476 S += charUnitsToString(ParmOffset);
8477 ParmOffset += getObjCEncodingTypeSize(PType);
8478 }
8479
8480 return S;
8481}
8482
8483/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8484/// method parameter or return type. If Extended, include class names and
8485/// block object types.
8487 QualType T, std::string& S,
8488 bool Extended) const {
8489 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8491 // Encode parameter type.
8492 ObjCEncOptions Options = ObjCEncOptions()
8493 .setExpandPointedToStructures()
8494 .setExpandStructures()
8495 .setIsOutermostType();
8496 if (Extended)
8497 Options.setEncodeBlockParameters().setEncodeClassNames();
8498 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8499}
8500
8501/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8502/// declaration.
8504 bool Extended) const {
8505 // FIXME: This is not very efficient.
8506 // Encode return type.
8507 std::string S;
8508 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8509 Decl->getReturnType(), S, Extended);
8510 // Compute size of all parameters.
8511 // Start with computing size of a pointer in number of bytes.
8512 // FIXME: There might(should) be a better way of doing this computation!
8514 // The first two arguments (self and _cmd) are pointers; account for
8515 // their size.
8516 CharUnits ParmOffset = 2 * PtrSize;
8517 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8518 E = Decl->sel_param_end(); PI != E; ++PI) {
8519 QualType PType = (*PI)->getType();
8521 if (sz.isZero())
8522 continue;
8523
8524 assert(sz.isPositive() &&
8525 "getObjCEncodingForMethodDecl - Incomplete param type");
8526 ParmOffset += sz;
8527 }
8528 S += charUnitsToString(ParmOffset);
8529 S += "@0:";
8530 S += charUnitsToString(PtrSize);
8531
8532 // Argument types.
8533 ParmOffset = 2 * PtrSize;
8534 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8535 E = Decl->sel_param_end(); PI != E; ++PI) {
8536 const ParmVarDecl *PVDecl = *PI;
8537 QualType PType = PVDecl->getOriginalType();
8538 if (const auto *AT =
8539 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8540 // Use array's original type only if it has known number of
8541 // elements.
8542 if (!isa<ConstantArrayType>(AT))
8543 PType = PVDecl->getType();
8544 } else if (PType->isFunctionType())
8545 PType = PVDecl->getType();
8547 PType, S, Extended);
8548 S += charUnitsToString(ParmOffset);
8549 ParmOffset += getObjCEncodingTypeSize(PType);
8550 }
8551
8552 return S;
8553}
8554
8557 const ObjCPropertyDecl *PD,
8558 const Decl *Container) const {
8559 if (!Container)
8560 return nullptr;
8561 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
8562 for (auto *PID : CID->property_impls())
8563 if (PID->getPropertyDecl() == PD)
8564 return PID;
8565 } else {
8566 const auto *OID = cast<ObjCImplementationDecl>(Container);
8567 for (auto *PID : OID->property_impls())
8568 if (PID->getPropertyDecl() == PD)
8569 return PID;
8570 }
8571 return nullptr;
8572}
8573
8574/// getObjCEncodingForPropertyDecl - Return the encoded type for this
8575/// property declaration. If non-NULL, Container must be either an
8576/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
8577/// NULL when getting encodings for protocol properties.
8578/// Property attributes are stored as a comma-delimited C string. The simple
8579/// attributes readonly and bycopy are encoded as single characters. The
8580/// parametrized attributes, getter=name, setter=name, and ivar=name, are
8581/// encoded as single characters, followed by an identifier. Property types
8582/// are also encoded as a parametrized attribute. The characters used to encode
8583/// these attributes are defined by the following enumeration:
8584/// @code
8585/// enum PropertyAttributes {
8586/// kPropertyReadOnly = 'R', // property is read-only.
8587/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
8588/// kPropertyByref = '&', // property is a reference to the value last assigned
8589/// kPropertyDynamic = 'D', // property is dynamic
8590/// kPropertyGetter = 'G', // followed by getter selector name
8591/// kPropertySetter = 'S', // followed by setter selector name
8592/// kPropertyInstanceVariable = 'V' // followed by instance variable name
8593/// kPropertyType = 'T' // followed by old-style type encoding.
8594/// kPropertyWeak = 'W' // 'weak' property
8595/// kPropertyStrong = 'P' // property GC'able
8596/// kPropertyNonAtomic = 'N' // property non-atomic
8597/// kPropertyOptional = '?' // property optional
8598/// };
8599/// @endcode
8600std::string
8602 const Decl *Container) const {
8603 // Collect information from the property implementation decl(s).
8604 bool Dynamic = false;
8605 ObjCPropertyImplDecl *SynthesizePID = nullptr;
8606
8607 if (ObjCPropertyImplDecl *PropertyImpDecl =
8609 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
8610 Dynamic = true;
8611 else
8612 SynthesizePID = PropertyImpDecl;
8613 }
8614
8615 // FIXME: This is not very efficient.
8616 std::string S = "T";
8617
8618 // Encode result type.
8619 // GCC has some special rules regarding encoding of properties which
8620 // closely resembles encoding of ivars.
8622
8623 if (PD->isOptional())
8624 S += ",?";
8625
8626 if (PD->isReadOnly()) {
8627 S += ",R";
8629 S += ",C";
8631 S += ",&";
8633 S += ",W";
8634 } else {
8635 switch (PD->getSetterKind()) {
8636 case ObjCPropertyDecl::Assign: break;
8637 case ObjCPropertyDecl::Copy: S += ",C"; break;
8638 case ObjCPropertyDecl::Retain: S += ",&"; break;
8639 case ObjCPropertyDecl::Weak: S += ",W"; break;
8640 }
8641 }
8642
8643 // It really isn't clear at all what this means, since properties
8644 // are "dynamic by default".
8645 if (Dynamic)
8646 S += ",D";
8647
8649 S += ",N";
8650
8652 S += ",G";
8653 S += PD->getGetterName().getAsString();
8654 }
8655
8657 S += ",S";
8658 S += PD->getSetterName().getAsString();
8659 }
8660
8661 if (SynthesizePID) {
8662 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
8663 S += ",V";
8664 S += OID->getNameAsString();
8665 }
8666
8667 // FIXME: OBJCGC: weak & strong
8668 return S;
8669}
8670
8671/// getLegacyIntegralTypeEncoding -
8672/// Another legacy compatibility encoding: 32-bit longs are encoded as
8673/// 'l' or 'L' , but not always. For typedefs, we need to use
8674/// 'i' or 'I' instead if encoding a struct field, or a pointer!
8676 if (PointeeTy->getAs<TypedefType>()) {
8677 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
8678 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
8679 PointeeTy = UnsignedIntTy;
8680 else
8681 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
8682 PointeeTy = IntTy;
8683 }
8684 }
8685}
8686
8688 const FieldDecl *Field,
8689 QualType *NotEncodedT) const {
8690 // We follow the behavior of gcc, expanding structures which are
8691 // directly pointed to, and expanding embedded structures. Note that
8692 // these rules are sufficient to prevent recursive encoding of the
8693 // same type.
8694 getObjCEncodingForTypeImpl(T, S,
8695 ObjCEncOptions()
8696 .setExpandPointedToStructures()
8697 .setExpandStructures()
8698 .setIsOutermostType(),
8699 Field, NotEncodedT);
8700}
8701
8703 std::string& S) const {
8704 // Encode result type.
8705 // GCC has some special rules regarding encoding of properties which
8706 // closely resembles encoding of ivars.
8707 getObjCEncodingForTypeImpl(T, S,
8708 ObjCEncOptions()
8709 .setExpandPointedToStructures()
8710 .setExpandStructures()
8711 .setIsOutermostType()
8712 .setEncodingProperty(),
8713 /*Field=*/nullptr);
8714}
8715
8717 const BuiltinType *BT) {
8718 BuiltinType::Kind kind = BT->getKind();
8719 switch (kind) {
8720 case BuiltinType::Void: return 'v';
8721 case BuiltinType::Bool: return 'B';
8722 case BuiltinType::Char8:
8723 case BuiltinType::Char_U:
8724 case BuiltinType::UChar: return 'C';
8725 case BuiltinType::Char16:
8726 case BuiltinType::UShort: return 'S';
8727 case BuiltinType::Char32:
8728 case BuiltinType::UInt: return 'I';
8729 case BuiltinType::ULong:
8730 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
8731 case BuiltinType::UInt128: return 'T';
8732 case BuiltinType::ULongLong: return 'Q';
8733 case BuiltinType::Char_S:
8734 case BuiltinType::SChar: return 'c';
8735 case BuiltinType::Short: return 's';
8736 case BuiltinType::WChar_S:
8737 case BuiltinType::WChar_U:
8738 case BuiltinType::Int: return 'i';
8739 case BuiltinType::Long:
8740 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
8741 case BuiltinType::LongLong: return 'q';
8742 case BuiltinType::Int128: return 't';
8743 case BuiltinType::Float: return 'f';
8744 case BuiltinType::Double: return 'd';
8745 case BuiltinType::LongDouble: return 'D';
8746 case BuiltinType::NullPtr: return '*'; // like char*
8747
8748 case BuiltinType::BFloat16:
8749 case BuiltinType::Float16:
8750 case BuiltinType::Float128:
8751 case BuiltinType::Ibm128:
8752 case BuiltinType::Half:
8753 case BuiltinType::ShortAccum:
8754 case BuiltinType::Accum:
8755 case BuiltinType::LongAccum:
8756 case BuiltinType::UShortAccum:
8757 case BuiltinType::UAccum:
8758 case BuiltinType::ULongAccum:
8759 case BuiltinType::ShortFract:
8760 case BuiltinType::Fract:
8761 case BuiltinType::LongFract:
8762 case BuiltinType::UShortFract:
8763 case BuiltinType::UFract:
8764 case BuiltinType::ULongFract:
8765 case BuiltinType::SatShortAccum:
8766 case BuiltinType::SatAccum:
8767 case BuiltinType::SatLongAccum:
8768 case BuiltinType::SatUShortAccum:
8769 case BuiltinType::SatUAccum:
8770 case BuiltinType::SatULongAccum:
8771 case BuiltinType::SatShortFract:
8772 case BuiltinType::SatFract:
8773 case BuiltinType::SatLongFract:
8774 case BuiltinType::SatUShortFract:
8775 case BuiltinType::SatUFract:
8776 case BuiltinType::SatULongFract:
8777 // FIXME: potentially need @encodes for these!
8778 return ' ';
8779
8780#define SVE_TYPE(Name, Id, SingletonId) \
8781 case BuiltinType::Id:
8782#include "clang/Basic/AArch64SVEACLETypes.def"
8783#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8784#include "clang/Basic/RISCVVTypes.def"
8785#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8786#include "clang/Basic/WebAssemblyReferenceTypes.def"
8787#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
8788#include "clang/Basic/AMDGPUTypes.def"
8789 {
8790 DiagnosticsEngine &Diags = C->getDiagnostics();
8791 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
8792 "cannot yet @encode type %0");
8793 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
8794 return ' ';
8795 }
8796
8797 case BuiltinType::ObjCId:
8798 case BuiltinType::ObjCClass:
8799 case BuiltinType::ObjCSel:
8800 llvm_unreachable("@encoding ObjC primitive type");
8801
8802 // OpenCL and placeholder types don't need @encodings.
8803#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8804 case BuiltinType::Id:
8805#include "clang/Basic/OpenCLImageTypes.def"
8806#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8807 case BuiltinType::Id:
8808#include "clang/Basic/OpenCLExtensionTypes.def"
8809 case BuiltinType::OCLEvent:
8810 case BuiltinType::OCLClkEvent:
8811 case BuiltinType::OCLQueue:
8812 case BuiltinType::OCLReserveID:
8813 case BuiltinType::OCLSampler:
8814 case BuiltinType::Dependent:
8815#define PPC_VECTOR_TYPE(Name, Id, Size) \
8816 case BuiltinType::Id:
8817#include "clang/Basic/PPCTypes.def"
8818#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8819#include "clang/Basic/HLSLIntangibleTypes.def"
8820#define BUILTIN_TYPE(KIND, ID)
8821#define PLACEHOLDER_TYPE(KIND, ID) \
8822 case BuiltinType::KIND:
8823#include "clang/AST/BuiltinTypes.def"
8824 llvm_unreachable("invalid builtin type for @encode");
8825 }
8826 llvm_unreachable("invalid BuiltinType::Kind value");
8827}
8828
8829static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
8830 EnumDecl *Enum = ET->getDecl();
8831
8832 // The encoding of an non-fixed enum type is always 'i', regardless of size.
8833 if (!Enum->isFixed())
8834 return 'i';
8835
8836 // The encoding of a fixed enum type matches its fixed underlying type.
8837 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
8839}
8840
8841static void EncodeBitField(const ASTContext *Ctx, std::string& S,
8842 QualType T, const FieldDecl *FD) {
8843 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
8844 S += 'b';
8845 // The NeXT runtime encodes bit fields as b followed by the number of bits.
8846 // The GNU runtime requires more information; bitfields are encoded as b,
8847 // then the offset (in bits) of the first element, then the type of the
8848 // bitfield, then the size in bits. For example, in this structure:
8849 //
8850 // struct
8851 // {
8852 // int integer;
8853 // int flags:2;
8854 // };
8855 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
8856 // runtime, but b32i2 for the GNU runtime. The reason for this extra
8857 // information is not especially sensible, but we're stuck with it for
8858 // compatibility with GCC, although providing it breaks anything that
8859 // actually uses runtime introspection and wants to work on both runtimes...
8860 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
8861 uint64_t Offset;
8862
8863 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
8864 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
8865 IVD);
8866 } else {
8867 const RecordDecl *RD = FD->getParent();
8868 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
8869 Offset = RL.getFieldOffset(FD->getFieldIndex());
8870 }
8871
8872 S += llvm::utostr(Offset);
8873
8874 if (const auto *ET = T->getAs<EnumType>())
8875 S += ObjCEncodingForEnumType(Ctx, ET);
8876 else {
8877 const auto *BT = T->castAs<BuiltinType>();
8878 S += getObjCEncodingForPrimitiveType(Ctx, BT);
8879 }
8880 }
8881 S += llvm::utostr(FD->getBitWidthValue());
8882}
8883
8884// Helper function for determining whether the encoded type string would include
8885// a template specialization type.
8887 bool VisitBasesAndFields) {
8889
8890 if (auto *PT = T->getAs<PointerType>())
8892 PT->getPointeeType().getTypePtr(), false);
8893
8894 auto *CXXRD = T->getAsCXXRecordDecl();
8895
8896 if (!CXXRD)
8897 return false;
8898
8899 if (isa<ClassTemplateSpecializationDecl>(CXXRD))
8900 return true;
8901
8902 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
8903 return false;
8904
8905 for (const auto &B : CXXRD->bases())
8906 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
8907 true))
8908 return true;
8909
8910 for (auto *FD : CXXRD->fields())
8911 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
8912 true))
8913 return true;
8914
8915 return false;
8916}
8917
8918// FIXME: Use SmallString for accumulating string.
8919void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
8920 const ObjCEncOptions Options,
8921 const FieldDecl *FD,
8922 QualType *NotEncodedT) const {
8924 switch (CT->getTypeClass()) {
8925 case Type::Builtin:
8926 case Type::Enum:
8927 if (FD && FD->isBitField())
8928 return EncodeBitField(this, S, T, FD);
8929 if (const auto *BT = dyn_cast<BuiltinType>(CT))
8930 S += getObjCEncodingForPrimitiveType(this, BT);
8931 else
8932 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
8933 return;
8934
8935 case Type::Complex:
8936 S += 'j';
8937 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
8938 ObjCEncOptions(),
8939 /*Field=*/nullptr);
8940 return;
8941
8942 case Type::Atomic:
8943 S += 'A';
8944 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
8945 ObjCEncOptions(),
8946 /*Field=*/nullptr);
8947 return;
8948
8949 // encoding for pointer or reference types.
8950 case Type::Pointer:
8951 case Type::LValueReference:
8952 case Type::RValueReference: {
8953 QualType PointeeTy;
8954 if (isa<PointerType>(CT)) {
8955 const auto *PT = T->castAs<PointerType>();
8956 if (PT->isObjCSelType()) {
8957 S += ':';
8958 return;
8959 }
8960 PointeeTy = PT->getPointeeType();
8961 } else {
8962 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
8963 }
8964
8965 bool isReadOnly = false;
8966 // For historical/compatibility reasons, the read-only qualifier of the
8967 // pointee gets emitted _before_ the '^'. The read-only qualifier of
8968 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
8969 // Also, do not emit the 'r' for anything but the outermost type!
8970 if (T->getAs<TypedefType>()) {
8971 if (Options.IsOutermostType() && T.isConstQualified()) {
8972 isReadOnly = true;
8973 S += 'r';
8974 }
8975 } else if (Options.IsOutermostType()) {
8976 QualType P = PointeeTy;
8977 while (auto PT = P->getAs<PointerType>())
8978 P = PT->getPointeeType();
8979 if (P.isConstQualified()) {
8980 isReadOnly = true;
8981 S += 'r';
8982 }
8983 }
8984 if (isReadOnly) {
8985 // Another legacy compatibility encoding. Some ObjC qualifier and type
8986 // combinations need to be rearranged.
8987 // Rewrite "in const" from "nr" to "rn"
8988 if (StringRef(S).ends_with("nr"))
8989 S.replace(S.end()-2, S.end(), "rn");
8990 }
8991
8992 if (PointeeTy->isCharType()) {
8993 // char pointer types should be encoded as '*' unless it is a
8994 // type that has been typedef'd to 'BOOL'.
8995 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
8996 S += '*';
8997 return;
8998 }
8999 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
9000 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9001 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
9002 S += '#';
9003 return;
9004 }
9005 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9006 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
9007 S += '@';
9008 return;
9009 }
9010 // If the encoded string for the class includes template names, just emit
9011 // "^v" for pointers to the class.
9012 if (getLangOpts().CPlusPlus &&
9013 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9015 RTy, Options.ExpandPointedToStructures()))) {
9016 S += "^v";
9017 return;
9018 }
9019 // fall through...
9020 }
9021 S += '^';
9023
9024 ObjCEncOptions NewOptions;
9025 if (Options.ExpandPointedToStructures())
9026 NewOptions.setExpandStructures();
9027 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9028 /*Field=*/nullptr, NotEncodedT);
9029 return;
9030 }
9031
9032 case Type::ConstantArray:
9033 case Type::IncompleteArray:
9034 case Type::VariableArray: {
9035 const auto *AT = cast<ArrayType>(CT);
9036
9037 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9038 // Incomplete arrays are encoded as a pointer to the array element.
9039 S += '^';
9040
9041 getObjCEncodingForTypeImpl(
9042 AT->getElementType(), S,
9043 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9044 } else {
9045 S += '[';
9046
9047 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9048 S += llvm::utostr(CAT->getZExtSize());
9049 else {
9050 //Variable length arrays are encoded as a regular array with 0 elements.
9051 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
9052 "Unknown array type!");
9053 S += '0';
9054 }
9055
9056 getObjCEncodingForTypeImpl(
9057 AT->getElementType(), S,
9058 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9059 NotEncodedT);
9060 S += ']';
9061 }
9062 return;
9063 }
9064
9065 case Type::FunctionNoProto:
9066 case Type::FunctionProto:
9067 S += '?';
9068 return;
9069
9070 case Type::Record: {
9071 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9072 S += RDecl->isUnion() ? '(' : '{';
9073 // Anonymous structures print as '?'
9074 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9075 S += II->getName();
9076 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9077 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9078 llvm::raw_string_ostream OS(S);
9079 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9081 }
9082 } else {
9083 S += '?';
9084 }
9085 if (Options.ExpandStructures()) {
9086 S += '=';
9087 if (!RDecl->isUnion()) {
9088 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9089 } else {
9090 for (const auto *Field : RDecl->fields()) {
9091 if (FD) {
9092 S += '"';
9093 S += Field->getNameAsString();
9094 S += '"';
9095 }
9096
9097 // Special case bit-fields.
9098 if (Field->isBitField()) {
9099 getObjCEncodingForTypeImpl(Field->getType(), S,
9100 ObjCEncOptions().setExpandStructures(),
9101 Field);
9102 } else {
9103 QualType qt = Field->getType();
9105 getObjCEncodingForTypeImpl(
9106 qt, S,
9107 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9108 NotEncodedT);
9109 }
9110 }
9111 }
9112 }
9113 S += RDecl->isUnion() ? ')' : '}';
9114 return;
9115 }
9116
9117 case Type::BlockPointer: {
9118 const auto *BT = T->castAs<BlockPointerType>();
9119 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9120 if (Options.EncodeBlockParameters()) {
9121 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9122
9123 S += '<';
9124 // Block return type
9125 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9126 Options.forComponentType(), FD, NotEncodedT);
9127 // Block self
9128 S += "@?";
9129 // Block parameters
9130 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9131 for (const auto &I : FPT->param_types())
9132 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9133 NotEncodedT);
9134 }
9135 S += '>';
9136 }
9137 return;
9138 }
9139
9140 case Type::ObjCObject: {
9141 // hack to match legacy encoding of *id and *Class
9143 if (Ty->isObjCIdType()) {
9144 S += "{objc_object=}";
9145 return;
9146 }
9147 else if (Ty->isObjCClassType()) {
9148 S += "{objc_class=}";
9149 return;
9150 }
9151 // TODO: Double check to make sure this intentionally falls through.
9152 [[fallthrough]];
9153 }
9154
9155 case Type::ObjCInterface: {
9156 // Ignore protocol qualifiers when mangling at this level.
9157 // @encode(class_name)
9158 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9159 S += '{';
9160 S += OI->getObjCRuntimeNameAsString();
9161 if (Options.ExpandStructures()) {
9162 S += '=';
9164 DeepCollectObjCIvars(OI, true, Ivars);
9165 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9166 const FieldDecl *Field = Ivars[i];
9167 if (Field->isBitField())
9168 getObjCEncodingForTypeImpl(Field->getType(), S,
9169 ObjCEncOptions().setExpandStructures(),
9170 Field);
9171 else
9172 getObjCEncodingForTypeImpl(Field->getType(), S,
9173 ObjCEncOptions().setExpandStructures(), FD,
9174 NotEncodedT);
9175 }
9176 }
9177 S += '}';
9178 return;
9179 }
9180
9181 case Type::ObjCObjectPointer: {
9182 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9183 if (OPT->isObjCIdType()) {
9184 S += '@';
9185 return;
9186 }
9187
9188 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9189 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9190 // Since this is a binary compatibility issue, need to consult with
9191 // runtime folks. Fortunately, this is a *very* obscure construct.
9192 S += '#';
9193 return;
9194 }
9195
9196 if (OPT->isObjCQualifiedIdType()) {
9197 getObjCEncodingForTypeImpl(
9198 getObjCIdType(), S,
9199 Options.keepingOnly(ObjCEncOptions()
9200 .setExpandPointedToStructures()
9201 .setExpandStructures()),
9202 FD);
9203 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9204 // Note that we do extended encoding of protocol qualifier list
9205 // Only when doing ivar or property encoding.
9206 S += '"';
9207 for (const auto *I : OPT->quals()) {
9208 S += '<';
9209 S += I->getObjCRuntimeNameAsString();
9210 S += '>';
9211 }
9212 S += '"';
9213 }
9214 return;
9215 }
9216
9217 S += '@';
9218 if (OPT->getInterfaceDecl() &&
9219 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9220 S += '"';
9221 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9222 for (const auto *I : OPT->quals()) {
9223 S += '<';
9224 S += I->getObjCRuntimeNameAsString();
9225 S += '>';
9226 }
9227 S += '"';
9228 }
9229 return;
9230 }
9231
9232 // gcc just blithely ignores member pointers.
9233 // FIXME: we should do better than that. 'M' is available.
9234 case Type::MemberPointer:
9235 // This matches gcc's encoding, even though technically it is insufficient.
9236 //FIXME. We should do a better job than gcc.
9237 case Type::Vector:
9238 case Type::ExtVector:
9239 // Until we have a coherent encoding of these three types, issue warning.
9240 if (NotEncodedT)
9241 *NotEncodedT = T;
9242 return;
9243
9244 case Type::ConstantMatrix:
9245 if (NotEncodedT)
9246 *NotEncodedT = T;
9247 return;
9248
9249 case Type::BitInt:
9250 if (NotEncodedT)
9251 *NotEncodedT = T;
9252 return;
9253
9254 // We could see an undeduced auto type here during error recovery.
9255 // Just ignore it.
9256 case Type::Auto:
9257 case Type::DeducedTemplateSpecialization:
9258 return;
9259
9260 case Type::HLSLAttributedResource:
9261 llvm_unreachable("unexpected type");
9262
9263 case Type::ArrayParameter:
9264 case Type::Pipe:
9265#define ABSTRACT_TYPE(KIND, BASE)
9266#define TYPE(KIND, BASE)
9267#define DEPENDENT_TYPE(KIND, BASE) \
9268 case Type::KIND:
9269#define NON_CANONICAL_TYPE(KIND, BASE) \
9270 case Type::KIND:
9271#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9272 case Type::KIND:
9273#include "clang/AST/TypeNodes.inc"
9274 llvm_unreachable("@encode for dependent type!");
9275 }
9276 llvm_unreachable("bad type kind!");
9277}
9278
9279void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9280 std::string &S,
9281 const FieldDecl *FD,
9282 bool includeVBases,
9283 QualType *NotEncodedT) const {
9284 assert(RDecl && "Expected non-null RecordDecl");
9285 assert(!RDecl->isUnion() && "Should not be called for unions");
9286 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9287 return;
9288
9289 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9290 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9291 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9292
9293 if (CXXRec) {
9294 for (const auto &BI : CXXRec->bases()) {
9295 if (!BI.isVirtual()) {
9296 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9297 if (base->isEmpty())
9298 continue;
9299 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9300 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9301 std::make_pair(offs, base));
9302 }
9303 }
9304 }
9305
9306 for (FieldDecl *Field : RDecl->fields()) {
9307 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9308 continue;
9309 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9310 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9311 std::make_pair(offs, Field));
9312 }
9313
9314 if (CXXRec && includeVBases) {
9315 for (const auto &BI : CXXRec->vbases()) {
9316 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9317 if (base->isEmpty())
9318 continue;
9319 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9320 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9321 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9322 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9323 std::make_pair(offs, base));
9324 }
9325 }
9326
9327 CharUnits size;
9328 if (CXXRec) {
9329 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9330 } else {
9331 size = layout.getSize();
9332 }
9333
9334#ifndef NDEBUG
9335 uint64_t CurOffs = 0;
9336#endif
9337 std::multimap<uint64_t, NamedDecl *>::iterator
9338 CurLayObj = FieldOrBaseOffsets.begin();
9339
9340 if (CXXRec && CXXRec->isDynamicClass() &&
9341 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9342 if (FD) {
9343 S += "\"_vptr$";
9344 std::string recname = CXXRec->getNameAsString();
9345 if (recname.empty()) recname = "?";
9346 S += recname;
9347 S += '"';
9348 }
9349 S += "^^?";
9350#ifndef NDEBUG
9351 CurOffs += getTypeSize(VoidPtrTy);
9352#endif
9353 }
9354
9355 if (!RDecl->hasFlexibleArrayMember()) {
9356 // Mark the end of the structure.
9357 uint64_t offs = toBits(size);
9358 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9359 std::make_pair(offs, nullptr));
9360 }
9361
9362 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9363#ifndef NDEBUG
9364 assert(CurOffs <= CurLayObj->first);
9365 if (CurOffs < CurLayObj->first) {
9366 uint64_t padding = CurLayObj->first - CurOffs;
9367 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9368 // packing/alignment of members is different that normal, in which case
9369 // the encoding will be out-of-sync with the real layout.
9370 // If the runtime switches to just consider the size of types without
9371 // taking into account alignment, we could make padding explicit in the
9372 // encoding (e.g. using arrays of chars). The encoding strings would be
9373 // longer then though.
9374 CurOffs += padding;
9375 }
9376#endif
9377
9378 NamedDecl *dcl = CurLayObj->second;
9379 if (!dcl)
9380 break; // reached end of structure.
9381
9382 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9383 // We expand the bases without their virtual bases since those are going
9384 // in the initial structure. Note that this differs from gcc which
9385 // expands virtual bases each time one is encountered in the hierarchy,
9386 // making the encoding type bigger than it really is.
9387 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9388 NotEncodedT);
9389 assert(!base->isEmpty());
9390#ifndef NDEBUG
9391 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9392#endif
9393 } else {
9394 const auto *field = cast<FieldDecl>(dcl);
9395 if (FD) {
9396 S += '"';
9397 S += field->getNameAsString();
9398 S += '"';
9399 }
9400
9401 if (field->isBitField()) {
9402 EncodeBitField(this, S, field->getType(), field);
9403#ifndef NDEBUG
9404 CurOffs += field->getBitWidthValue();
9405#endif
9406 } else {
9407 QualType qt = field->getType();
9409 getObjCEncodingForTypeImpl(
9410 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9411 FD, NotEncodedT);
9412#ifndef NDEBUG
9413 CurOffs += getTypeSize(field->getType());
9414#endif
9415 }
9416 }
9417 }
9418}
9419
9421 std::string& S) const {
9422 if (QT & Decl::OBJC_TQ_In)
9423 S += 'n';
9424 if (QT & Decl::OBJC_TQ_Inout)
9425 S += 'N';
9426 if (QT & Decl::OBJC_TQ_Out)
9427 S += 'o';
9428 if (QT & Decl::OBJC_TQ_Bycopy)
9429 S += 'O';
9430 if (QT & Decl::OBJC_TQ_Byref)
9431 S += 'R';
9432 if (QT & Decl::OBJC_TQ_Oneway)
9433 S += 'V';
9434}
9435
9437 if (!ObjCIdDecl) {
9440 ObjCIdDecl = buildImplicitTypedef(T, "id");
9441 }
9442 return ObjCIdDecl;
9443}
9444
9446 if (!ObjCSelDecl) {
9448 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9449 }
9450 return ObjCSelDecl;
9451}
9452
9454 if (!ObjCClassDecl) {
9457 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9458 }
9459 return ObjCClassDecl;
9460}
9461
9463 if (!ObjCProtocolClassDecl) {
9464 ObjCProtocolClassDecl
9467 &Idents.get("Protocol"),
9468 /*typeParamList=*/nullptr,
9469 /*PrevDecl=*/nullptr,
9470 SourceLocation(), true);
9471 }
9472
9473 return ObjCProtocolClassDecl;
9474}
9475
9476//===----------------------------------------------------------------------===//
9477// __builtin_va_list Construction Functions
9478//===----------------------------------------------------------------------===//
9479
9481 StringRef Name) {
9482 // typedef char* __builtin[_ms]_va_list;
9483 QualType T = Context->getPointerType(Context->CharTy);
9484 return Context->buildImplicitTypedef(T, Name);
9485}
9486
9488 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9489}
9490
9492 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9493}
9494
9496 // typedef void* __builtin_va_list;
9497 QualType T = Context->getPointerType(Context->VoidTy);
9498 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9499}
9500
9501static TypedefDecl *
9503 // struct __va_list
9504 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9505 if (Context->getLangOpts().CPlusPlus) {
9506 // namespace std { struct __va_list {
9507 auto *NS = NamespaceDecl::Create(
9508 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9509 /*Inline=*/false, SourceLocation(), SourceLocation(),
9510 &Context->Idents.get("std"),
9511 /*PrevDecl=*/nullptr, /*Nested=*/false);
9512 NS->setImplicit();
9513 VaListTagDecl->setDeclContext(NS);
9514 }
9515
9516 VaListTagDecl->startDefinition();
9517
9518 const size_t NumFields = 5;
9519 QualType FieldTypes[NumFields];
9520 const char *FieldNames[NumFields];
9521
9522 // void *__stack;
9523 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9524 FieldNames[0] = "__stack";
9525
9526 // void *__gr_top;
9527 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9528 FieldNames[1] = "__gr_top";
9529
9530 // void *__vr_top;
9531 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9532 FieldNames[2] = "__vr_top";
9533
9534 // int __gr_offs;
9535 FieldTypes[3] = Context->IntTy;
9536 FieldNames[3] = "__gr_offs";
9537
9538 // int __vr_offs;
9539 FieldTypes[4] = Context->IntTy;
9540 FieldNames[4] = "__vr_offs";
9541
9542 // Create fields
9543 for (unsigned i = 0; i < NumFields; ++i) {
9544 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9545 VaListTagDecl,
9548 &Context->Idents.get(FieldNames[i]),
9549 FieldTypes[i], /*TInfo=*/nullptr,
9550 /*BitWidth=*/nullptr,
9551 /*Mutable=*/false,
9552 ICIS_NoInit);
9553 Field->setAccess(AS_public);
9554 VaListTagDecl->addDecl(Field);
9555 }
9556 VaListTagDecl->completeDefinition();
9557 Context->VaListTagDecl = VaListTagDecl;
9558 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9559
9560 // } __builtin_va_list;
9561 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9562}
9563
9565 // typedef struct __va_list_tag {
9566 RecordDecl *VaListTagDecl;
9567
9568 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9569 VaListTagDecl->startDefinition();
9570
9571 const size_t NumFields = 5;
9572 QualType FieldTypes[NumFields];
9573 const char *FieldNames[NumFields];
9574
9575 // unsigned char gpr;
9576 FieldTypes[0] = Context->UnsignedCharTy;
9577 FieldNames[0] = "gpr";
9578
9579 // unsigned char fpr;
9580 FieldTypes[1] = Context->UnsignedCharTy;
9581 FieldNames[1] = "fpr";
9582
9583 // unsigned short reserved;
9584 FieldTypes[2] = Context->UnsignedShortTy;
9585 FieldNames[2] = "reserved";
9586
9587 // void* overflow_arg_area;
9588 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9589 FieldNames[3] = "overflow_arg_area";
9590
9591 // void* reg_save_area;
9592 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
9593 FieldNames[4] = "reg_save_area";
9594
9595 // Create fields
9596 for (unsigned i = 0; i < NumFields; ++i) {
9597 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
9600 &Context->Idents.get(FieldNames[i]),
9601 FieldTypes[i], /*TInfo=*/nullptr,
9602 /*BitWidth=*/nullptr,
9603 /*Mutable=*/false,
9604 ICIS_NoInit);
9605 Field->setAccess(AS_public);
9606 VaListTagDecl->addDecl(Field);
9607 }
9608 VaListTagDecl->completeDefinition();
9609 Context->VaListTagDecl = VaListTagDecl;
9610 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9611
9612 // } __va_list_tag;
9613 TypedefDecl *VaListTagTypedefDecl =
9614 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9615
9616 QualType VaListTagTypedefType =
9617 Context->getTypedefType(VaListTagTypedefDecl);
9618
9619 // typedef __va_list_tag __builtin_va_list[1];
9620 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9621 QualType VaListTagArrayType = Context->getConstantArrayType(
9622 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9623 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9624}
9625
9626static TypedefDecl *
9628 // struct __va_list_tag {
9629 RecordDecl *VaListTagDecl;
9630 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9631 VaListTagDecl->startDefinition();
9632
9633 const size_t NumFields = 4;
9634 QualType FieldTypes[NumFields];
9635 const char *FieldNames[NumFields];
9636
9637 // unsigned gp_offset;
9638 FieldTypes[0] = Context->UnsignedIntTy;
9639 FieldNames[0] = "gp_offset";
9640
9641 // unsigned fp_offset;
9642 FieldTypes[1] = Context->UnsignedIntTy;
9643 FieldNames[1] = "fp_offset";
9644
9645 // void* overflow_arg_area;
9646 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9647 FieldNames[2] = "overflow_arg_area";
9648
9649 // void* reg_save_area;
9650 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9651 FieldNames[3] = "reg_save_area";
9652
9653 // Create fields
9654 for (unsigned i = 0; i < NumFields; ++i) {
9655 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9656 VaListTagDecl,
9659 &Context->Idents.get(FieldNames[i]),
9660 FieldTypes[i], /*TInfo=*/nullptr,
9661 /*BitWidth=*/nullptr,
9662 /*Mutable=*/false,
9663 ICIS_NoInit);
9664 Field->setAccess(AS_public);
9665 VaListTagDecl->addDecl(Field);
9666 }
9667 VaListTagDecl->completeDefinition();
9668 Context->VaListTagDecl = VaListTagDecl;
9669 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9670
9671 // };
9672
9673 // typedef struct __va_list_tag __builtin_va_list[1];
9674 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9675 QualType VaListTagArrayType = Context->getConstantArrayType(
9676 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9677 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9678}
9679
9681 // typedef int __builtin_va_list[4];
9682 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
9683 QualType IntArrayType = Context->getConstantArrayType(
9684 Context->IntTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9685 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
9686}
9687
9688static TypedefDecl *
9690 // struct __va_list
9691 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
9692 if (Context->getLangOpts().CPlusPlus) {
9693 // namespace std { struct __va_list {
9694 NamespaceDecl *NS;
9695 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
9696 Context->getTranslationUnitDecl(),
9697 /*Inline=*/false, SourceLocation(),
9698 SourceLocation(), &Context->Idents.get("std"),
9699 /*PrevDecl=*/nullptr, /*Nested=*/false);
9700 NS->setImplicit();
9701 VaListDecl->setDeclContext(NS);
9702 }
9703
9704 VaListDecl->startDefinition();
9705
9706 // void * __ap;
9707 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9708 VaListDecl,
9711 &Context->Idents.get("__ap"),
9712 Context->getPointerType(Context->VoidTy),
9713 /*TInfo=*/nullptr,
9714 /*BitWidth=*/nullptr,
9715 /*Mutable=*/false,
9716 ICIS_NoInit);
9717 Field->setAccess(AS_public);
9718 VaListDecl->addDecl(Field);
9719
9720 // };
9721 VaListDecl->completeDefinition();
9722 Context->VaListTagDecl = VaListDecl;
9723
9724 // typedef struct __va_list __builtin_va_list;
9725 QualType T = Context->getRecordType(VaListDecl);
9726 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9727}
9728
9729static TypedefDecl *
9731 // struct __va_list_tag {
9732 RecordDecl *VaListTagDecl;
9733 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9734 VaListTagDecl->startDefinition();
9735
9736 const size_t NumFields = 4;
9737 QualType FieldTypes[NumFields];
9738 const char *FieldNames[NumFields];
9739
9740 // long __gpr;
9741 FieldTypes[0] = Context->LongTy;
9742 FieldNames[0] = "__gpr";
9743
9744 // long __fpr;
9745 FieldTypes[1] = Context->LongTy;
9746 FieldNames[1] = "__fpr";
9747
9748 // void *__overflow_arg_area;
9749 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9750 FieldNames[2] = "__overflow_arg_area";
9751
9752 // void *__reg_save_area;
9753 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9754 FieldNames[3] = "__reg_save_area";
9755
9756 // Create fields
9757 for (unsigned i = 0; i < NumFields; ++i) {
9758 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9759 VaListTagDecl,
9762 &Context->Idents.get(FieldNames[i]),
9763 FieldTypes[i], /*TInfo=*/nullptr,
9764 /*BitWidth=*/nullptr,
9765 /*Mutable=*/false,
9766 ICIS_NoInit);
9767 Field->setAccess(AS_public);
9768 VaListTagDecl->addDecl(Field);
9769 }
9770 VaListTagDecl->completeDefinition();
9771 Context->VaListTagDecl = VaListTagDecl;
9772 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9773
9774 // };
9775
9776 // typedef __va_list_tag __builtin_va_list[1];
9777 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9778 QualType VaListTagArrayType = Context->getConstantArrayType(
9779 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9780
9781 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9782}
9783
9785 // typedef struct __va_list_tag {
9786 RecordDecl *VaListTagDecl;
9787 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9788 VaListTagDecl->startDefinition();
9789
9790 const size_t NumFields = 3;
9791 QualType FieldTypes[NumFields];
9792 const char *FieldNames[NumFields];
9793
9794 // void *CurrentSavedRegisterArea;
9795 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9796 FieldNames[0] = "__current_saved_reg_area_pointer";
9797
9798 // void *SavedRegAreaEnd;
9799 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9800 FieldNames[1] = "__saved_reg_area_end_pointer";
9801
9802 // void *OverflowArea;
9803 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9804 FieldNames[2] = "__overflow_area_pointer";
9805
9806 // Create fields
9807 for (unsigned i = 0; i < NumFields; ++i) {
9809 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
9810 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
9811 /*TInfo=*/nullptr,
9812 /*BitWidth=*/nullptr,
9813 /*Mutable=*/false, ICIS_NoInit);
9814 Field->setAccess(AS_public);
9815 VaListTagDecl->addDecl(Field);
9816 }
9817 VaListTagDecl->completeDefinition();
9818 Context->VaListTagDecl = VaListTagDecl;
9819 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9820
9821 // } __va_list_tag;
9822 TypedefDecl *VaListTagTypedefDecl =
9823 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9824
9825 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
9826
9827 // typedef __va_list_tag __builtin_va_list[1];
9828 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9829 QualType VaListTagArrayType = Context->getConstantArrayType(
9830 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9831
9832 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9833}
9834
9835static TypedefDecl *
9837 // typedef struct __va_list_tag {
9838 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9839
9840 VaListTagDecl->startDefinition();
9841
9842 // int* __va_stk;
9843 // int* __va_reg;
9844 // int __va_ndx;
9845 constexpr size_t NumFields = 3;
9846 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
9847 Context->getPointerType(Context->IntTy),
9848 Context->IntTy};
9849 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
9850
9851 // Create fields
9852 for (unsigned i = 0; i < NumFields; ++i) {
9854 *Context, VaListTagDecl, SourceLocation(), SourceLocation(),
9855 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
9856 /*BitWidth=*/nullptr,
9857 /*Mutable=*/false, ICIS_NoInit);
9858 Field->setAccess(AS_public);
9859 VaListTagDecl->addDecl(Field);
9860 }
9861 VaListTagDecl->completeDefinition();
9862 Context->VaListTagDecl = VaListTagDecl;
9863 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9864
9865 // } __va_list_tag;
9866 TypedefDecl *VaListTagTypedefDecl =
9867 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9868
9869 return VaListTagTypedefDecl;
9870}
9871
9874 switch (Kind) {
9876 return CreateCharPtrBuiltinVaListDecl(Context);
9878 return CreateVoidPtrBuiltinVaListDecl(Context);
9880 return CreateAArch64ABIBuiltinVaListDecl(Context);
9882 return CreatePowerABIBuiltinVaListDecl(Context);
9884 return CreateX86_64ABIBuiltinVaListDecl(Context);
9886 return CreatePNaClABIBuiltinVaListDecl(Context);
9888 return CreateAAPCSABIBuiltinVaListDecl(Context);
9890 return CreateSystemZBuiltinVaListDecl(Context);
9892 return CreateHexagonBuiltinVaListDecl(Context);
9894 return CreateXtensaABIBuiltinVaListDecl(Context);
9895 }
9896
9897 llvm_unreachable("Unhandled __builtin_va_list type kind");
9898}
9899
9901 if (!BuiltinVaListDecl) {
9902 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
9903 assert(BuiltinVaListDecl->isImplicit());
9904 }
9905
9906 return BuiltinVaListDecl;
9907}
9908
9910 // Force the creation of VaListTagDecl by building the __builtin_va_list
9911 // declaration.
9912 if (!VaListTagDecl)
9913 (void)getBuiltinVaListDecl();
9914
9915 return VaListTagDecl;
9916}
9917
9919 if (!BuiltinMSVaListDecl)
9920 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
9921
9922 return BuiltinMSVaListDecl;
9923}
9924
9926 // Allow redecl custom type checking builtin for HLSL.
9927 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
9929 return true;
9931}
9932
9934 assert(ObjCConstantStringType.isNull() &&
9935 "'NSConstantString' type already set!");
9936
9937 ObjCConstantStringType = getObjCInterfaceType(Decl);
9938}
9939
9940/// Retrieve the template name that corresponds to a non-empty
9941/// lookup.
9944 UnresolvedSetIterator End) const {
9945 unsigned size = End - Begin;
9946 assert(size > 1 && "set is not overloaded!");
9947
9948 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
9949 size * sizeof(FunctionTemplateDecl*));
9950 auto *OT = new (memory) OverloadedTemplateStorage(size);
9951
9952 NamedDecl **Storage = OT->getStorage();
9953 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
9954 NamedDecl *D = *I;
9955 assert(isa<FunctionTemplateDecl>(D) ||
9956 isa<UnresolvedUsingValueDecl>(D) ||
9957 (isa<UsingShadowDecl>(D) &&
9958 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
9959 *Storage++ = D;
9960 }
9961
9962 return TemplateName(OT);
9963}
9964
9965/// Retrieve a template name representing an unqualified-id that has been
9966/// assumed to name a template for ADL purposes.
9968 auto *OT = new (*this) AssumedTemplateStorage(Name);
9969 return TemplateName(OT);
9970}
9971
9972/// Retrieve the template name that represents a qualified
9973/// template name such as \c std::vector.
9975 bool TemplateKeyword,
9976 TemplateName Template) const {
9977 assert(Template.getKind() == TemplateName::Template ||
9978 Template.getKind() == TemplateName::UsingTemplate);
9979
9980 // FIXME: Canonicalization?
9981 llvm::FoldingSetNodeID ID;
9982 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
9983
9984 void *InsertPos = nullptr;
9986 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9987 if (!QTN) {
9988 QTN = new (*this, alignof(QualifiedTemplateName))
9989 QualifiedTemplateName(NNS, TemplateKeyword, Template);
9990 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
9991 }
9992
9993 return TemplateName(QTN);
9994}
9995
9996/// Retrieve the template name that represents a dependent
9997/// template name such as \c MetaFun::template apply.
10000 const IdentifierInfo *Name) const {
10001 assert((!NNS || NNS->isDependent()) &&
10002 "Nested name specifier must be dependent");
10003
10004 llvm::FoldingSetNodeID ID;
10005 DependentTemplateName::Profile(ID, NNS, Name);
10006
10007 void *InsertPos = nullptr;
10009 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10010
10011 if (QTN)
10012 return TemplateName(QTN);
10013
10015 if (CanonNNS == NNS) {
10016 QTN = new (*this, alignof(DependentTemplateName))
10017 DependentTemplateName(NNS, Name);
10018 } else {
10019 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
10020 QTN = new (*this, alignof(DependentTemplateName))
10021 DependentTemplateName(NNS, Name, Canon);
10022 DependentTemplateName *CheckQTN =
10023 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10024 assert(!CheckQTN && "Dependent type name canonicalization broken");
10025 (void)CheckQTN;
10026 }
10027
10028 DependentTemplateNames.InsertNode(QTN, InsertPos);
10029 return TemplateName(QTN);
10030}
10031
10032/// Retrieve the template name that represents a dependent
10033/// template name such as \c MetaFun::template operator+.
10036 OverloadedOperatorKind Operator) const {
10037 assert((!NNS || NNS->isDependent()) &&
10038 "Nested name specifier must be dependent");
10039
10040 llvm::FoldingSetNodeID ID;
10041 DependentTemplateName::Profile(ID, NNS, Operator);
10042
10043 void *InsertPos = nullptr;
10045 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10046
10047 if (QTN)
10048 return TemplateName(QTN);
10049
10051 if (CanonNNS == NNS) {
10052 QTN = new (*this, alignof(DependentTemplateName))
10053 DependentTemplateName(NNS, Operator);
10054 } else {
10055 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
10056 QTN = new (*this, alignof(DependentTemplateName))
10057 DependentTemplateName(NNS, Operator, Canon);
10058
10059 DependentTemplateName *CheckQTN
10060 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10061 assert(!CheckQTN && "Dependent template name canonicalization broken");
10062 (void)CheckQTN;
10063 }
10064
10065 DependentTemplateNames.InsertNode(QTN, InsertPos);
10066 return TemplateName(QTN);
10067}
10068
10070 TemplateName Replacement, Decl *AssociatedDecl, unsigned Index,
10071 std::optional<unsigned> PackIndex) const {
10072 llvm::FoldingSetNodeID ID;
10073 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10074 Index, PackIndex);
10075
10076 void *insertPos = nullptr;
10078 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10079
10080 if (!subst) {
10081 subst = new (*this) SubstTemplateTemplateParmStorage(
10082 Replacement, AssociatedDecl, Index, PackIndex);
10083 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10084 }
10085
10086 return TemplateName(subst);
10087}
10088
10091 Decl *AssociatedDecl,
10092 unsigned Index, bool Final) const {
10093 auto &Self = const_cast<ASTContext &>(*this);
10094 llvm::FoldingSetNodeID ID;
10096 AssociatedDecl, Index, Final);
10097
10098 void *InsertPos = nullptr;
10100 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10101
10102 if (!Subst) {
10103 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10104 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10105 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10106 }
10107
10108 return TemplateName(Subst);
10109}
10110
10111/// Retrieve the template name that represents a template name
10112/// deduced from a specialization.
10115 DefaultArguments DefaultArgs) const {
10116 if (!DefaultArgs)
10117 return Underlying;
10118
10119 llvm::FoldingSetNodeID ID;
10120 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10121
10122 void *InsertPos = nullptr;
10124 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10125 if (!DTS) {
10126 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10127 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10128 alignof(DeducedTemplateStorage));
10129 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10130 DeducedTemplates.InsertNode(DTS, InsertPos);
10131 }
10132 return TemplateName(DTS);
10133}
10134
10135/// getFromTargetType - Given one of the integer types provided by
10136/// TargetInfo, produce the corresponding type. The unsigned @p Type
10137/// is actually a value of type @c TargetInfo::IntType.
10138CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10139 switch (Type) {
10140 case TargetInfo::NoInt: return {};
10143 case TargetInfo::SignedShort: return ShortTy;
10145 case TargetInfo::SignedInt: return IntTy;
10147 case TargetInfo::SignedLong: return LongTy;
10151 }
10152
10153 llvm_unreachable("Unhandled TargetInfo::IntType value");
10154}
10155
10156//===----------------------------------------------------------------------===//
10157// Type Predicates.
10158//===----------------------------------------------------------------------===//
10159
10160/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10161/// garbage collection attribute.
10162///
10164 if (getLangOpts().getGC() == LangOptions::NonGC)
10165 return Qualifiers::GCNone;
10166
10167 assert(getLangOpts().ObjC);
10168 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10169
10170 // Default behaviour under objective-C's gc is for ObjC pointers
10171 // (or pointers to them) be treated as though they were declared
10172 // as __strong.
10173 if (GCAttrs == Qualifiers::GCNone) {
10175 return Qualifiers::Strong;
10176 else if (Ty->isPointerType())
10178 } else {
10179 // It's not valid to set GC attributes on anything that isn't a
10180 // pointer.
10181#ifndef NDEBUG
10183 while (const auto *AT = dyn_cast<ArrayType>(CT))
10184 CT = AT->getElementType();
10185 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10186#endif
10187 }
10188 return GCAttrs;
10189}
10190
10191//===----------------------------------------------------------------------===//
10192// Type Compatibility Testing
10193//===----------------------------------------------------------------------===//
10194
10195/// areCompatVectorTypes - Return true if the two specified vector types are
10196/// compatible.
10197static bool areCompatVectorTypes(const VectorType *LHS,
10198 const VectorType *RHS) {
10199 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10200 return LHS->getElementType() == RHS->getElementType() &&
10201 LHS->getNumElements() == RHS->getNumElements();
10202}
10203
10204/// areCompatMatrixTypes - Return true if the two specified matrix types are
10205/// compatible.
10207 const ConstantMatrixType *RHS) {
10208 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10209 return LHS->getElementType() == RHS->getElementType() &&
10210 LHS->getNumRows() == RHS->getNumRows() &&
10211 LHS->getNumColumns() == RHS->getNumColumns();
10212}
10213
10215 QualType SecondVec) {
10216 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10217 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10218
10219 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10220 return true;
10221
10222 // Treat Neon vector types and most AltiVec vector types as if they are the
10223 // equivalent GCC vector types.
10224 const auto *First = FirstVec->castAs<VectorType>();
10225 const auto *Second = SecondVec->castAs<VectorType>();
10226 if (First->getNumElements() == Second->getNumElements() &&
10227 hasSameType(First->getElementType(), Second->getElementType()) &&
10228 First->getVectorKind() != VectorKind::AltiVecPixel &&
10229 First->getVectorKind() != VectorKind::AltiVecBool &&
10232 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10233 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10236 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10238 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10240 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10242 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10244 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10246 return true;
10247
10248 return false;
10249}
10250
10251/// getSVETypeSize - Return SVE vector or predicate register size.
10252static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
10253 assert(Ty->isSveVLSBuiltinType() && "Invalid SVE Type");
10254 if (Ty->getKind() == BuiltinType::SveBool ||
10255 Ty->getKind() == BuiltinType::SveCount)
10256 return (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth();
10257 return Context.getLangOpts().VScaleMin * 128;
10258}
10259
10261 QualType SecondType) {
10262 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10263 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10264 if (const auto *VT = SecondType->getAs<VectorType>()) {
10265 // Predicates have the same representation as uint8 so we also have to
10266 // check the kind to make these types incompatible.
10267 if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
10268 return BT->getKind() == BuiltinType::SveBool;
10269 else if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
10270 return VT->getElementType().getCanonicalType() ==
10271 FirstType->getSveEltType(*this);
10272 else if (VT->getVectorKind() == VectorKind::Generic)
10273 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) &&
10274 hasSameType(VT->getElementType(),
10275 getBuiltinVectorTypeInfo(BT).ElementType);
10276 }
10277 }
10278 return false;
10279 };
10280
10281 return IsValidCast(FirstType, SecondType) ||
10282 IsValidCast(SecondType, FirstType);
10283}
10284
10286 QualType SecondType) {
10287 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10288 const auto *BT = FirstType->getAs<BuiltinType>();
10289 if (!BT)
10290 return false;
10291
10292 const auto *VecTy = SecondType->getAs<VectorType>();
10293 if (VecTy && (VecTy->getVectorKind() == VectorKind::SveFixedLengthData ||
10294 VecTy->getVectorKind() == VectorKind::Generic)) {
10296 getLangOpts().getLaxVectorConversions();
10297
10298 // Can not convert between sve predicates and sve vectors because of
10299 // different size.
10300 if (BT->getKind() == BuiltinType::SveBool &&
10301 VecTy->getVectorKind() == VectorKind::SveFixedLengthData)
10302 return false;
10303
10304 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
10305 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
10306 // converts to VLAT and VLAT implicitly converts to GNUT."
10307 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
10308 // predicates.
10309 if (VecTy->getVectorKind() == VectorKind::Generic &&
10310 getTypeSize(SecondType) != getSVETypeSize(*this, BT))
10311 return false;
10312
10313 // If -flax-vector-conversions=all is specified, the types are
10314 // certainly compatible.
10316 return true;
10317
10318 // If -flax-vector-conversions=integer is specified, the types are
10319 // compatible if the elements are integer types.
10321 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10322 FirstType->getSveEltType(*this)->isIntegerType();
10323 }
10324
10325 return false;
10326 };
10327
10328 return IsLaxCompatible(FirstType, SecondType) ||
10329 IsLaxCompatible(SecondType, FirstType);
10330}
10331
10332/// getRVVTypeSize - Return RVV vector register size.
10333static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10334 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10335 auto VScale = Context.getTargetInfo().getVScaleRange(Context.getLangOpts());
10336 if (!VScale)
10337 return 0;
10338
10340
10341 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10342 if (Info.ElementType == Context.BoolTy)
10343 EltSize = 1;
10344
10345 uint64_t MinElts = Info.EC.getKnownMinValue();
10346 return VScale->first * MinElts * EltSize;
10347}
10348
10350 QualType SecondType) {
10351 assert(
10352 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10353 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10354 "Expected RVV builtin type and vector type!");
10355
10356 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10357 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10358 if (const auto *VT = SecondType->getAs<VectorType>()) {
10359 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10361 return FirstType->isRVVVLSBuiltinType() &&
10362 Info.ElementType == BoolTy &&
10363 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10364 }
10365 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10367 return FirstType->isRVVVLSBuiltinType() &&
10368 Info.ElementType == BoolTy &&
10369 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10370 }
10371 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10373 return FirstType->isRVVVLSBuiltinType() &&
10374 Info.ElementType == BoolTy &&
10375 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10376 }
10377 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10379 return FirstType->isRVVVLSBuiltinType() &&
10380 Info.ElementType == BoolTy &&
10381 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10382 }
10383 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10384 VT->getVectorKind() == VectorKind::Generic)
10385 return FirstType->isRVVVLSBuiltinType() &&
10386 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10387 hasSameType(VT->getElementType(),
10388 getBuiltinVectorTypeInfo(BT).ElementType);
10389 }
10390 }
10391 return false;
10392 };
10393
10394 return IsValidCast(FirstType, SecondType) ||
10395 IsValidCast(SecondType, FirstType);
10396}
10397
10399 QualType SecondType) {
10400 assert(
10401 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10402 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10403 "Expected RVV builtin type and vector type!");
10404
10405 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10406 const auto *BT = FirstType->getAs<BuiltinType>();
10407 if (!BT)
10408 return false;
10409
10410 if (!BT->isRVVVLSBuiltinType())
10411 return false;
10412
10413 const auto *VecTy = SecondType->getAs<VectorType>();
10414 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10416 getLangOpts().getLaxVectorConversions();
10417
10418 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10419 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10420 return false;
10421
10422 // If -flax-vector-conversions=all is specified, the types are
10423 // certainly compatible.
10425 return true;
10426
10427 // If -flax-vector-conversions=integer is specified, the types are
10428 // compatible if the elements are integer types.
10430 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10431 FirstType->getRVVEltType(*this)->isIntegerType();
10432 }
10433
10434 return false;
10435 };
10436
10437 return IsLaxCompatible(FirstType, SecondType) ||
10438 IsLaxCompatible(SecondType, FirstType);
10439}
10440
10442 while (true) {
10443 // __strong id
10444 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10445 if (Attr->getAttrKind() == attr::ObjCOwnership)
10446 return true;
10447
10448 Ty = Attr->getModifiedType();
10449
10450 // X *__strong (...)
10451 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10452 Ty = Paren->getInnerType();
10453
10454 // We do not want to look through typedefs, typeof(expr),
10455 // typeof(type), or any other way that the type is somehow
10456 // abstracted.
10457 } else {
10458 return false;
10459 }
10460 }
10461}
10462
10463//===----------------------------------------------------------------------===//
10464// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10465//===----------------------------------------------------------------------===//
10466
10467/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10468/// inheritance hierarchy of 'rProto'.
10469bool
10471 ObjCProtocolDecl *rProto) const {
10472 if (declaresSameEntity(lProto, rProto))
10473 return true;
10474 for (auto *PI : rProto->protocols())
10475 if (ProtocolCompatibleWithProtocol(lProto, PI))
10476 return true;
10477 return false;
10478}
10479
10480/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10481/// Class<pr1, ...>.
10483 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10484 for (auto *lhsProto : lhs->quals()) {
10485 bool match = false;
10486 for (auto *rhsProto : rhs->quals()) {
10487 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10488 match = true;
10489 break;
10490 }
10491 }
10492 if (!match)
10493 return false;
10494 }
10495 return true;
10496}
10497
10498/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10499/// ObjCQualifiedIDType.
10501 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10502 bool compare) {
10503 // Allow id<P..> and an 'id' in all cases.
10504 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10505 return true;
10506
10507 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10508 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10510 return false;
10511
10512 if (lhs->isObjCQualifiedIdType()) {
10513 if (rhs->qual_empty()) {
10514 // If the RHS is a unqualified interface pointer "NSString*",
10515 // make sure we check the class hierarchy.
10516 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10517 for (auto *I : lhs->quals()) {
10518 // when comparing an id<P> on lhs with a static type on rhs,
10519 // see if static class implements all of id's protocols, directly or
10520 // through its super class and categories.
10521 if (!rhsID->ClassImplementsProtocol(I, true))
10522 return false;
10523 }
10524 }
10525 // If there are no qualifiers and no interface, we have an 'id'.
10526 return true;
10527 }
10528 // Both the right and left sides have qualifiers.
10529 for (auto *lhsProto : lhs->quals()) {
10530 bool match = false;
10531
10532 // when comparing an id<P> on lhs with a static type on rhs,
10533 // see if static class implements all of id's protocols, directly or
10534 // through its super class and categories.
10535 for (auto *rhsProto : rhs->quals()) {
10536 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10537 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10538 match = true;
10539 break;
10540 }
10541 }
10542 // If the RHS is a qualified interface pointer "NSString<P>*",
10543 // make sure we check the class hierarchy.
10544 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10545 for (auto *I : lhs->quals()) {
10546 // when comparing an id<P> on lhs with a static type on rhs,
10547 // see if static class implements all of id's protocols, directly or
10548 // through its super class and categories.
10549 if (rhsID->ClassImplementsProtocol(I, true)) {
10550 match = true;
10551 break;
10552 }
10553 }
10554 }
10555 if (!match)
10556 return false;
10557 }
10558
10559 return true;
10560 }
10561
10562 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10563
10564 if (lhs->getInterfaceType()) {
10565 // If both the right and left sides have qualifiers.
10566 for (auto *lhsProto : lhs->quals()) {
10567 bool match = false;
10568
10569 // when comparing an id<P> on rhs with a static type on lhs,
10570 // see if static class implements all of id's protocols, directly or
10571 // through its super class and categories.
10572 // First, lhs protocols in the qualifier list must be found, direct
10573 // or indirect in rhs's qualifier list or it is a mismatch.
10574 for (auto *rhsProto : rhs->quals()) {
10575 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10576 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10577 match = true;
10578 break;
10579 }
10580 }
10581 if (!match)
10582 return false;
10583 }
10584
10585 // Static class's protocols, or its super class or category protocols
10586 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10587 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10588 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10589 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10590 // This is rather dubious but matches gcc's behavior. If lhs has
10591 // no type qualifier and its class has no static protocol(s)
10592 // assume that it is mismatch.
10593 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10594 return false;
10595 for (auto *lhsProto : LHSInheritedProtocols) {
10596 bool match = false;
10597 for (auto *rhsProto : rhs->quals()) {
10598 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10599 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10600 match = true;
10601 break;
10602 }
10603 }
10604 if (!match)
10605 return false;
10606 }
10607 }
10608 return true;
10609 }
10610 return false;
10611}
10612
10613/// canAssignObjCInterfaces - Return true if the two interface types are
10614/// compatible for assignment from RHS to LHS. This handles validation of any
10615/// protocol qualifiers on the LHS or RHS.
10617 const ObjCObjectPointerType *RHSOPT) {
10618 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10619 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10620
10621 // If either type represents the built-in 'id' type, return true.
10622 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10623 return true;
10624
10625 // Function object that propagates a successful result or handles
10626 // __kindof types.
10627 auto finish = [&](bool succeeded) -> bool {
10628 if (succeeded)
10629 return true;
10630
10631 if (!RHS->isKindOfType())
10632 return false;
10633
10634 // Strip off __kindof and protocol qualifiers, then check whether
10635 // we can assign the other way.
10637 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10638 };
10639
10640 // Casts from or to id<P> are allowed when the other side has compatible
10641 // protocols.
10642 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
10643 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
10644 }
10645
10646 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
10647 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
10648 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
10649 }
10650
10651 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
10652 if (LHS->isObjCClass() && RHS->isObjCClass()) {
10653 return true;
10654 }
10655
10656 // If we have 2 user-defined types, fall into that path.
10657 if (LHS->getInterface() && RHS->getInterface()) {
10658 return finish(canAssignObjCInterfaces(LHS, RHS));
10659 }
10660
10661 return false;
10662}
10663
10664/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
10665/// for providing type-safety for objective-c pointers used to pass/return
10666/// arguments in block literals. When passed as arguments, passing 'A*' where
10667/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
10668/// not OK. For the return type, the opposite is not OK.
10670 const ObjCObjectPointerType *LHSOPT,
10671 const ObjCObjectPointerType *RHSOPT,
10672 bool BlockReturnType) {
10673
10674 // Function object that propagates a successful result or handles
10675 // __kindof types.
10676 auto finish = [&](bool succeeded) -> bool {
10677 if (succeeded)
10678 return true;
10679
10680 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
10681 if (!Expected->isKindOfType())
10682 return false;
10683
10684 // Strip off __kindof and protocol qualifiers, then check whether
10685 // we can assign the other way.
10687 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
10688 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
10689 BlockReturnType);
10690 };
10691
10692 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
10693 return true;
10694
10695 if (LHSOPT->isObjCBuiltinType()) {
10696 return finish(RHSOPT->isObjCBuiltinType() ||
10697 RHSOPT->isObjCQualifiedIdType());
10698 }
10699
10700 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
10701 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
10702 // Use for block parameters previous type checking for compatibility.
10703 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
10704 // Or corrected type checking as in non-compat mode.
10705 (!BlockReturnType &&
10706 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
10707 else
10709 (BlockReturnType ? LHSOPT : RHSOPT),
10710 (BlockReturnType ? RHSOPT : LHSOPT), false));
10711 }
10712
10713 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
10714 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
10715 if (LHS && RHS) { // We have 2 user-defined types.
10716 if (LHS != RHS) {
10717 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
10718 return finish(BlockReturnType);
10719 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
10720 return finish(!BlockReturnType);
10721 }
10722 else
10723 return true;
10724 }
10725 return false;
10726}
10727
10728/// Comparison routine for Objective-C protocols to be used with
10729/// llvm::array_pod_sort.
10731 ObjCProtocolDecl * const *rhs) {
10732 return (*lhs)->getName().compare((*rhs)->getName());
10733}
10734
10735/// getIntersectionOfProtocols - This routine finds the intersection of set
10736/// of protocols inherited from two distinct objective-c pointer objects with
10737/// the given common base.
10738/// It is used to build composite qualifier list of the composite type of
10739/// the conditional expression involving two objective-c pointer objects.
10740static
10742 const ObjCInterfaceDecl *CommonBase,
10743 const ObjCObjectPointerType *LHSOPT,
10744 const ObjCObjectPointerType *RHSOPT,
10745 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
10746
10747 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10748 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10749 assert(LHS->getInterface() && "LHS must have an interface base");
10750 assert(RHS->getInterface() && "RHS must have an interface base");
10751
10752 // Add all of the protocols for the LHS.
10754
10755 // Start with the protocol qualifiers.
10756 for (auto *proto : LHS->quals()) {
10757 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
10758 }
10759
10760 // Also add the protocols associated with the LHS interface.
10761 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
10762
10763 // Add all of the protocols for the RHS.
10765
10766 // Start with the protocol qualifiers.
10767 for (auto *proto : RHS->quals()) {
10768 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
10769 }
10770
10771 // Also add the protocols associated with the RHS interface.
10772 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
10773
10774 // Compute the intersection of the collected protocol sets.
10775 for (auto *proto : LHSProtocolSet) {
10776 if (RHSProtocolSet.count(proto))
10777 IntersectionSet.push_back(proto);
10778 }
10779
10780 // Compute the set of protocols that is implied by either the common type or
10781 // the protocols within the intersection.
10783 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
10784
10785 // Remove any implied protocols from the list of inherited protocols.
10786 if (!ImpliedProtocols.empty()) {
10787 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
10788 return ImpliedProtocols.contains(proto);
10789 });
10790 }
10791
10792 // Sort the remaining protocols by name.
10793 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
10795}
10796
10797/// Determine whether the first type is a subtype of the second.
10799 QualType rhs) {
10800 // Common case: two object pointers.
10801 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
10802 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
10803 if (lhsOPT && rhsOPT)
10804 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
10805
10806 // Two block pointers.
10807 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
10808 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
10809 if (lhsBlock && rhsBlock)
10810 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
10811
10812 // If either is an unqualified 'id' and the other is a block, it's
10813 // acceptable.
10814 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
10815 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
10816 return true;
10817
10818 return false;
10819}
10820
10821// Check that the given Objective-C type argument lists are equivalent.
10823 const ObjCInterfaceDecl *iface,
10824 ArrayRef<QualType> lhsArgs,
10825 ArrayRef<QualType> rhsArgs,
10826 bool stripKindOf) {
10827 if (lhsArgs.size() != rhsArgs.size())
10828 return false;
10829
10830 ObjCTypeParamList *typeParams = iface->getTypeParamList();
10831 if (!typeParams)
10832 return false;
10833
10834 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
10835 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
10836 continue;
10837
10838 switch (typeParams->begin()[i]->getVariance()) {
10840 if (!stripKindOf ||
10841 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
10842 rhsArgs[i].stripObjCKindOfType(ctx))) {
10843 return false;
10844 }
10845 break;
10846
10848 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
10849 return false;
10850 break;
10851
10853 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
10854 return false;
10855 break;
10856 }
10857 }
10858
10859 return true;
10860}
10861
10863 const ObjCObjectPointerType *Lptr,
10864 const ObjCObjectPointerType *Rptr) {
10865 const ObjCObjectType *LHS = Lptr->getObjectType();
10866 const ObjCObjectType *RHS = Rptr->getObjectType();
10867 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
10868 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
10869
10870 if (!LDecl || !RDecl)
10871 return {};
10872
10873 // When either LHS or RHS is a kindof type, we should return a kindof type.
10874 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
10875 // kindof(A).
10876 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
10877
10878 // Follow the left-hand side up the class hierarchy until we either hit a
10879 // root or find the RHS. Record the ancestors in case we don't find it.
10880 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
10881 LHSAncestors;
10882 while (true) {
10883 // Record this ancestor. We'll need this if the common type isn't in the
10884 // path from the LHS to the root.
10885 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
10886
10887 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
10888 // Get the type arguments.
10889 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
10890 bool anyChanges = false;
10891 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10892 // Both have type arguments, compare them.
10893 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10894 LHS->getTypeArgs(), RHS->getTypeArgs(),
10895 /*stripKindOf=*/true))
10896 return {};
10897 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10898 // If only one has type arguments, the result will not have type
10899 // arguments.
10900 LHSTypeArgs = {};
10901 anyChanges = true;
10902 }
10903
10904 // Compute the intersection of protocols.
10906 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
10907 Protocols);
10908 if (!Protocols.empty())
10909 anyChanges = true;
10910
10911 // If anything in the LHS will have changed, build a new result type.
10912 // If we need to return a kindof type but LHS is not a kindof type, we
10913 // build a new result type.
10914 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
10916 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
10917 anyKindOf || LHS->isKindOfType());
10919 }
10920
10921 return getObjCObjectPointerType(QualType(LHS, 0));
10922 }
10923
10924 // Find the superclass.
10925 QualType LHSSuperType = LHS->getSuperClassType();
10926 if (LHSSuperType.isNull())
10927 break;
10928
10929 LHS = LHSSuperType->castAs<ObjCObjectType>();
10930 }
10931
10932 // We didn't find anything by following the LHS to its root; now check
10933 // the RHS against the cached set of ancestors.
10934 while (true) {
10935 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
10936 if (KnownLHS != LHSAncestors.end()) {
10937 LHS = KnownLHS->second;
10938
10939 // Get the type arguments.
10940 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
10941 bool anyChanges = false;
10942 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10943 // Both have type arguments, compare them.
10944 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10945 LHS->getTypeArgs(), RHS->getTypeArgs(),
10946 /*stripKindOf=*/true))
10947 return {};
10948 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10949 // If only one has type arguments, the result will not have type
10950 // arguments.
10951 RHSTypeArgs = {};
10952 anyChanges = true;
10953 }
10954
10955 // Compute the intersection of protocols.
10957 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
10958 Protocols);
10959 if (!Protocols.empty())
10960 anyChanges = true;
10961
10962 // If we need to return a kindof type but RHS is not a kindof type, we
10963 // build a new result type.
10964 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
10966 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
10967 anyKindOf || RHS->isKindOfType());
10969 }
10970
10971 return getObjCObjectPointerType(QualType(RHS, 0));
10972 }
10973
10974 // Find the superclass of the RHS.
10975 QualType RHSSuperType = RHS->getSuperClassType();
10976 if (RHSSuperType.isNull())
10977 break;
10978
10979 RHS = RHSSuperType->castAs<ObjCObjectType>();
10980 }
10981
10982 return {};
10983}
10984
10986 const ObjCObjectType *RHS) {
10987 assert(LHS->getInterface() && "LHS is not an interface type");
10988 assert(RHS->getInterface() && "RHS is not an interface type");
10989
10990 // Verify that the base decls are compatible: the RHS must be a subclass of
10991 // the LHS.
10992 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
10993 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
10994 if (!IsSuperClass)
10995 return false;
10996
10997 // If the LHS has protocol qualifiers, determine whether all of them are
10998 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
10999 // LHS).
11000 if (LHS->getNumProtocols() > 0) {
11001 // OK if conversion of LHS to SuperClass results in narrowing of types
11002 // ; i.e., SuperClass may implement at least one of the protocols
11003 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11004 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11005 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11006 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11007 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11008 // qualifiers.
11009 for (auto *RHSPI : RHS->quals())
11010 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11011 // If there is no protocols associated with RHS, it is not a match.
11012 if (SuperClassInheritedProtocols.empty())
11013 return false;
11014
11015 for (const auto *LHSProto : LHS->quals()) {
11016 bool SuperImplementsProtocol = false;
11017 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11018 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11019 SuperImplementsProtocol = true;
11020 break;
11021 }
11022 if (!SuperImplementsProtocol)
11023 return false;
11024 }
11025 }
11026
11027 // If the LHS is specialized, we may need to check type arguments.
11028 if (LHS->isSpecialized()) {
11029 // Follow the superclass chain until we've matched the LHS class in the
11030 // hierarchy. This substitutes type arguments through.
11031 const ObjCObjectType *RHSSuper = RHS;
11032 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11033 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11034
11035 // If the RHS is specializd, compare type arguments.
11036 if (RHSSuper->isSpecialized() &&
11037 !sameObjCTypeArgs(*this, LHS->getInterface(),
11038 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11039 /*stripKindOf=*/true)) {
11040 return false;
11041 }
11042 }
11043
11044 return true;
11045}
11046
11048 // get the "pointed to" types
11049 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11050 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11051
11052 if (!LHSOPT || !RHSOPT)
11053 return false;
11054
11055 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11056 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11057}
11058
11061 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11062 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11063}
11064
11065/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11066/// both shall have the identically qualified version of a compatible type.
11067/// C99 6.2.7p1: Two types have compatible types if their types are the
11068/// same. See 6.7.[2,3,5] for additional rules.
11070 bool CompareUnqualified) {
11071 if (getLangOpts().CPlusPlus)
11072 return hasSameType(LHS, RHS);
11073
11074 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11075}
11076
11078 return typesAreCompatible(LHS, RHS);
11079}
11080
11082 return !mergeTypes(LHS, RHS, true).isNull();
11083}
11084
11085/// mergeTransparentUnionType - if T is a transparent union type and a member
11086/// of T is compatible with SubType, return the merged type, else return
11087/// QualType()
11089 bool OfBlockPointer,
11090 bool Unqualified) {
11091 if (const RecordType *UT = T->getAsUnionType()) {
11092 RecordDecl *UD = UT->getDecl();
11093 if (UD->hasAttr<TransparentUnionAttr>()) {
11094 for (const auto *I : UD->fields()) {
11095 QualType ET = I->getType().getUnqualifiedType();
11096 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11097 if (!MT.isNull())
11098 return MT;
11099 }
11100 }
11101 }
11102
11103 return {};
11104}
11105
11106/// mergeFunctionParameterTypes - merge two types which appear as function
11107/// parameter types
11109 bool OfBlockPointer,
11110 bool Unqualified) {
11111 // GNU extension: two types are compatible if they appear as a function
11112 // argument, one of the types is a transparent union type and the other
11113 // type is compatible with a union member
11114 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11115 Unqualified);
11116 if (!lmerge.isNull())
11117 return lmerge;
11118
11119 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11120 Unqualified);
11121 if (!rmerge.isNull())
11122 return rmerge;
11123
11124 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11125}
11126
11128 bool OfBlockPointer, bool Unqualified,
11129 bool AllowCXX,
11130 bool IsConditionalOperator) {
11131 const auto *lbase = lhs->castAs<FunctionType>();
11132 const auto *rbase = rhs->castAs<FunctionType>();
11133 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11134 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11135 bool allLTypes = true;
11136 bool allRTypes = true;
11137
11138 // Check return type
11139 QualType retType;
11140 if (OfBlockPointer) {
11141 QualType RHS = rbase->getReturnType();
11142 QualType LHS = lbase->getReturnType();
11143 bool UnqualifiedResult = Unqualified;
11144 if (!UnqualifiedResult)
11145 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11146 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11147 }
11148 else
11149 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11150 Unqualified);
11151 if (retType.isNull())
11152 return {};
11153
11154 if (Unqualified)
11155 retType = retType.getUnqualifiedType();
11156
11157 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11158 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11159 if (Unqualified) {
11160 LRetType = LRetType.getUnqualifiedType();
11161 RRetType = RRetType.getUnqualifiedType();
11162 }
11163
11164 if (getCanonicalType(retType) != LRetType)
11165 allLTypes = false;
11166 if (getCanonicalType(retType) != RRetType)
11167 allRTypes = false;
11168
11169 // FIXME: double check this
11170 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11171 // rbase->getRegParmAttr() != 0 &&
11172 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11173 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11174 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11175
11176 // Compatible functions must have compatible calling conventions
11177 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11178 return {};
11179
11180 // Regparm is part of the calling convention.
11181 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11182 return {};
11183 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11184 return {};
11185
11186 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11187 return {};
11188 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11189 return {};
11190 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11191 return {};
11192
11193 // When merging declarations, it's common for supplemental information like
11194 // attributes to only be present in one of the declarations, and we generally
11195 // want type merging to preserve the union of information. So a merged
11196 // function type should be noreturn if it was noreturn in *either* operand
11197 // type.
11198 //
11199 // But for the conditional operator, this is backwards. The result of the
11200 // operator could be either operand, and its type should conservatively
11201 // reflect that. So a function type in a composite type is noreturn only
11202 // if it's noreturn in *both* operand types.
11203 //
11204 // Arguably, noreturn is a kind of subtype, and the conditional operator
11205 // ought to produce the most specific common supertype of its operand types.
11206 // That would differ from this rule in contravariant positions. However,
11207 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11208 // as a practical matter, it would only affect C code that does abstraction of
11209 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11210 // say the least. So we use the simpler rule.
11211 bool NoReturn = IsConditionalOperator
11212 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11213 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11214 if (lbaseInfo.getNoReturn() != NoReturn)
11215 allLTypes = false;
11216 if (rbaseInfo.getNoReturn() != NoReturn)
11217 allRTypes = false;
11218
11219 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11220
11221 std::optional<FunctionEffectSet> MergedFX;
11222
11223 if (lproto && rproto) { // two C99 style function prototypes
11224 assert((AllowCXX ||
11225 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11226 "C++ shouldn't be here");
11227 // Compatible functions must have the same number of parameters
11228 if (lproto->getNumParams() != rproto->getNumParams())
11229 return {};
11230
11231 // Variadic and non-variadic functions aren't compatible
11232 if (lproto->isVariadic() != rproto->isVariadic())
11233 return {};
11234
11235 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11236 return {};
11237
11238 // Function effects are handled similarly to noreturn, see above.
11239 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11240 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11241 if (LHSFX != RHSFX) {
11242 if (IsConditionalOperator)
11243 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11244 else {
11246 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11247 // Here we're discarding a possible error due to conflicts in the effect
11248 // sets. But we're not in a context where we can report it. The
11249 // operation does however guarantee maintenance of invariants.
11250 }
11251 if (*MergedFX != LHSFX)
11252 allLTypes = false;
11253 if (*MergedFX != RHSFX)
11254 allRTypes = false;
11255 }
11256
11258 bool canUseLeft, canUseRight;
11259 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11260 newParamInfos))
11261 return {};
11262
11263 if (!canUseLeft)
11264 allLTypes = false;
11265 if (!canUseRight)
11266 allRTypes = false;
11267
11268 // Check parameter type compatibility
11270 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11271 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11272 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11274 lParamType, rParamType, OfBlockPointer, Unqualified);
11275 if (paramType.isNull())
11276 return {};
11277
11278 if (Unqualified)
11279 paramType = paramType.getUnqualifiedType();
11280
11281 types.push_back(paramType);
11282 if (Unqualified) {
11283 lParamType = lParamType.getUnqualifiedType();
11284 rParamType = rParamType.getUnqualifiedType();
11285 }
11286
11287 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11288 allLTypes = false;
11289 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11290 allRTypes = false;
11291 }
11292
11293 if (allLTypes) return lhs;
11294 if (allRTypes) return rhs;
11295
11296 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11297 EPI.ExtInfo = einfo;
11298 EPI.ExtParameterInfos =
11299 newParamInfos.empty() ? nullptr : newParamInfos.data();
11300 if (MergedFX)
11301 EPI.FunctionEffects = *MergedFX;
11302 return getFunctionType(retType, types, EPI);
11303 }
11304
11305 if (lproto) allRTypes = false;
11306 if (rproto) allLTypes = false;
11307
11308 const FunctionProtoType *proto = lproto ? lproto : rproto;
11309 if (proto) {
11310 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11311 if (proto->isVariadic())
11312 return {};
11313 // Check that the types are compatible with the types that
11314 // would result from default argument promotions (C99 6.7.5.3p15).
11315 // The only types actually affected are promotable integer
11316 // types and floats, which would be passed as a different
11317 // type depending on whether the prototype is visible.
11318 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11319 QualType paramTy = proto->getParamType(i);
11320
11321 // Look at the converted type of enum types, since that is the type used
11322 // to pass enum values.
11323 if (const auto *Enum = paramTy->getAs<EnumType>()) {
11324 paramTy = Enum->getDecl()->getIntegerType();
11325 if (paramTy.isNull())
11326 return {};
11327 }
11328
11329 if (isPromotableIntegerType(paramTy) ||
11330 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11331 return {};
11332 }
11333
11334 if (allLTypes) return lhs;
11335 if (allRTypes) return rhs;
11336
11338 EPI.ExtInfo = einfo;
11339 if (MergedFX)
11340 EPI.FunctionEffects = *MergedFX;
11341 return getFunctionType(retType, proto->getParamTypes(), EPI);
11342 }
11343
11344 if (allLTypes) return lhs;
11345 if (allRTypes) return rhs;
11346 return getFunctionNoProtoType(retType, einfo);
11347}
11348
11349/// Given that we have an enum type and a non-enum type, try to merge them.
11351 QualType other, bool isBlockReturnType) {
11352 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11353 // a signed integer type, or an unsigned integer type.
11354 // Compatibility is based on the underlying type, not the promotion
11355 // type.
11356 QualType underlyingType = ET->getDecl()->getIntegerType();
11357 if (underlyingType.isNull())
11358 return {};
11359 if (Context.hasSameType(underlyingType, other))
11360 return other;
11361
11362 // In block return types, we're more permissive and accept any
11363 // integral type of the same size.
11364 if (isBlockReturnType && other->isIntegerType() &&
11365 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11366 return other;
11367
11368 return {};
11369}
11370
11371QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11372 bool Unqualified, bool BlockReturnType,
11373 bool IsConditionalOperator) {
11374 // For C++ we will not reach this code with reference types (see below),
11375 // for OpenMP variant call overloading we might.
11376 //
11377 // C++ [expr]: If an expression initially has the type "reference to T", the
11378 // type is adjusted to "T" prior to any further analysis, the expression
11379 // designates the object or function denoted by the reference, and the
11380 // expression is an lvalue unless the reference is an rvalue reference and
11381 // the expression is a function call (possibly inside parentheses).
11382 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11383 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11384 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11385 LHS->getTypeClass() == RHS->getTypeClass())
11386 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11387 OfBlockPointer, Unqualified, BlockReturnType);
11388 if (LHSRefTy || RHSRefTy)
11389 return {};
11390
11391 if (Unqualified) {
11392 LHS = LHS.getUnqualifiedType();
11393 RHS = RHS.getUnqualifiedType();
11394 }
11395
11396 QualType LHSCan = getCanonicalType(LHS),
11397 RHSCan = getCanonicalType(RHS);
11398
11399 // If two types are identical, they are compatible.
11400 if (LHSCan == RHSCan)
11401 return LHS;
11402
11403 // If the qualifiers are different, the types aren't compatible... mostly.
11404 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11405 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11406 if (LQuals != RQuals) {
11407 // If any of these qualifiers are different, we have a type
11408 // mismatch.
11409 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11410 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11411 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11412 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11413 return {};
11414
11415 // Exactly one GC qualifier difference is allowed: __strong is
11416 // okay if the other type has no GC qualifier but is an Objective
11417 // C object pointer (i.e. implicitly strong by default). We fix
11418 // this by pretending that the unqualified type was actually
11419 // qualified __strong.
11420 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11421 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11422 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11423
11424 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11425 return {};
11426
11427 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11429 }
11430 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11432 }
11433 return {};
11434 }
11435
11436 // Okay, qualifiers are equal.
11437
11438 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11439 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11440
11441 // We want to consider the two function types to be the same for these
11442 // comparisons, just force one to the other.
11443 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11444 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11445
11446 // Same as above for arrays
11447 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11448 LHSClass = Type::ConstantArray;
11449 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11450 RHSClass = Type::ConstantArray;
11451
11452 // ObjCInterfaces are just specialized ObjCObjects.
11453 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11454 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11455
11456 // Canonicalize ExtVector -> Vector.
11457 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11458 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11459
11460 // If the canonical type classes don't match.
11461 if (LHSClass != RHSClass) {
11462 // Note that we only have special rules for turning block enum
11463 // returns into block int returns, not vice-versa.
11464 if (const auto *ETy = LHS->getAs<EnumType>()) {
11465 return mergeEnumWithInteger(*this, ETy, RHS, false);
11466 }
11467 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
11468 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11469 }
11470 // allow block pointer type to match an 'id' type.
11471 if (OfBlockPointer && !BlockReturnType) {
11472 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11473 return LHS;
11474 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11475 return RHS;
11476 }
11477 // Allow __auto_type to match anything; it merges to the type with more
11478 // information.
11479 if (const auto *AT = LHS->getAs<AutoType>()) {
11480 if (!AT->isDeduced() && AT->isGNUAutoType())
11481 return RHS;
11482 }
11483 if (const auto *AT = RHS->getAs<AutoType>()) {
11484 if (!AT->isDeduced() && AT->isGNUAutoType())
11485 return LHS;
11486 }
11487 return {};
11488 }
11489
11490 // The canonical type classes match.
11491 switch (LHSClass) {
11492#define TYPE(Class, Base)
11493#define ABSTRACT_TYPE(Class, Base)
11494#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11495#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11496#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11497#include "clang/AST/TypeNodes.inc"
11498 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11499
11500 case Type::Auto:
11501 case Type::DeducedTemplateSpecialization:
11502 case Type::LValueReference:
11503 case Type::RValueReference:
11504 case Type::MemberPointer:
11505 llvm_unreachable("C++ should never be in mergeTypes");
11506
11507 case Type::ObjCInterface:
11508 case Type::IncompleteArray:
11509 case Type::VariableArray:
11510 case Type::FunctionProto:
11511 case Type::ExtVector:
11512 llvm_unreachable("Types are eliminated above");
11513
11514 case Type::Pointer:
11515 {
11516 // Merge two pointer types, while trying to preserve typedef info
11517 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11518 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11519 if (Unqualified) {
11520 LHSPointee = LHSPointee.getUnqualifiedType();
11521 RHSPointee = RHSPointee.getUnqualifiedType();
11522 }
11523 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11524 Unqualified);
11525 if (ResultType.isNull())
11526 return {};
11527 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11528 return LHS;
11529 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11530 return RHS;
11531 return getPointerType(ResultType);
11532 }
11533 case Type::BlockPointer:
11534 {
11535 // Merge two block pointer types, while trying to preserve typedef info
11536 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11537 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11538 if (Unqualified) {
11539 LHSPointee = LHSPointee.getUnqualifiedType();
11540 RHSPointee = RHSPointee.getUnqualifiedType();
11541 }
11542 if (getLangOpts().OpenCL) {
11543 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11544 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11545 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11546 // 6.12.5) thus the following check is asymmetric.
11547 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
11548 return {};
11549 LHSPteeQual.removeAddressSpace();
11550 RHSPteeQual.removeAddressSpace();
11551 LHSPointee =
11552 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11553 RHSPointee =
11554 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11555 }
11556 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11557 Unqualified);
11558 if (ResultType.isNull())
11559 return {};
11560 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11561 return LHS;
11562 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11563 return RHS;
11564 return getBlockPointerType(ResultType);
11565 }
11566 case Type::Atomic:
11567 {
11568 // Merge two pointer types, while trying to preserve typedef info
11569 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
11570 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
11571 if (Unqualified) {
11572 LHSValue = LHSValue.getUnqualifiedType();
11573 RHSValue = RHSValue.getUnqualifiedType();
11574 }
11575 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
11576 Unqualified);
11577 if (ResultType.isNull())
11578 return {};
11579 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
11580 return LHS;
11581 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
11582 return RHS;
11583 return getAtomicType(ResultType);
11584 }
11585 case Type::ConstantArray:
11586 {
11587 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
11588 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
11589 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
11590 return {};
11591
11592 QualType LHSElem = getAsArrayType(LHS)->getElementType();
11593 QualType RHSElem = getAsArrayType(RHS)->getElementType();
11594 if (Unqualified) {
11595 LHSElem = LHSElem.getUnqualifiedType();
11596 RHSElem = RHSElem.getUnqualifiedType();
11597 }
11598
11599 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
11600 if (ResultType.isNull())
11601 return {};
11602
11603 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
11604 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
11605
11606 // If either side is a variable array, and both are complete, check whether
11607 // the current dimension is definite.
11608 if (LVAT || RVAT) {
11609 auto SizeFetch = [this](const VariableArrayType* VAT,
11610 const ConstantArrayType* CAT)
11611 -> std::pair<bool,llvm::APInt> {
11612 if (VAT) {
11613 std::optional<llvm::APSInt> TheInt;
11614 Expr *E = VAT->getSizeExpr();
11615 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
11616 return std::make_pair(true, *TheInt);
11617 return std::make_pair(false, llvm::APSInt());
11618 }
11619 if (CAT)
11620 return std::make_pair(true, CAT->getSize());
11621 return std::make_pair(false, llvm::APInt());
11622 };
11623
11624 bool HaveLSize, HaveRSize;
11625 llvm::APInt LSize, RSize;
11626 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
11627 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
11628 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
11629 return {}; // Definite, but unequal, array dimension
11630 }
11631
11632 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11633 return LHS;
11634 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11635 return RHS;
11636 if (LCAT)
11637 return getConstantArrayType(ResultType, LCAT->getSize(),
11638 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
11639 if (RCAT)
11640 return getConstantArrayType(ResultType, RCAT->getSize(),
11641 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
11642 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11643 return LHS;
11644 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11645 return RHS;
11646 if (LVAT) {
11647 // FIXME: This isn't correct! But tricky to implement because
11648 // the array's size has to be the size of LHS, but the type
11649 // has to be different.
11650 return LHS;
11651 }
11652 if (RVAT) {
11653 // FIXME: This isn't correct! But tricky to implement because
11654 // the array's size has to be the size of RHS, but the type
11655 // has to be different.
11656 return RHS;
11657 }
11658 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
11659 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
11660 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
11661 }
11662 case Type::FunctionNoProto:
11663 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
11664 /*AllowCXX=*/false, IsConditionalOperator);
11665 case Type::Record:
11666 case Type::Enum:
11667 return {};
11668 case Type::Builtin:
11669 // Only exactly equal builtin types are compatible, which is tested above.
11670 return {};
11671 case Type::Complex:
11672 // Distinct complex types are incompatible.
11673 return {};
11674 case Type::Vector:
11675 // FIXME: The merged type should be an ExtVector!
11676 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
11677 RHSCan->castAs<VectorType>()))
11678 return LHS;
11679 return {};
11680 case Type::ConstantMatrix:
11682 RHSCan->castAs<ConstantMatrixType>()))
11683 return LHS;
11684 return {};
11685 case Type::ObjCObject: {
11686 // Check if the types are assignment compatible.
11687 // FIXME: This should be type compatibility, e.g. whether
11688 // "LHS x; RHS x;" at global scope is legal.
11690 RHS->castAs<ObjCObjectType>()))
11691 return LHS;
11692 return {};
11693 }
11694 case Type::ObjCObjectPointer:
11695 if (OfBlockPointer) {
11698 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
11699 return LHS;
11700 return {};
11701 }
11704 return LHS;
11705 return {};
11706 case Type::Pipe:
11707 assert(LHS != RHS &&
11708 "Equivalent pipe types should have already been handled!");
11709 return {};
11710 case Type::ArrayParameter:
11711 assert(LHS != RHS &&
11712 "Equivalent ArrayParameter types should have already been handled!");
11713 return {};
11714 case Type::BitInt: {
11715 // Merge two bit-precise int types, while trying to preserve typedef info.
11716 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
11717 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
11718 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
11719 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
11720
11721 // Like unsigned/int, shouldn't have a type if they don't match.
11722 if (LHSUnsigned != RHSUnsigned)
11723 return {};
11724
11725 if (LHSBits != RHSBits)
11726 return {};
11727 return LHS;
11728 }
11729 case Type::HLSLAttributedResource: {
11730 const HLSLAttributedResourceType *LHSTy =
11732 const HLSLAttributedResourceType *RHSTy =
11734 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
11735 LHSTy->getWrappedType()->isHLSLResourceType() &&
11736 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
11737
11738 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
11739 LHSTy->getContainedType() == RHSTy->getContainedType())
11740 return LHS;
11741 return {};
11742 }
11743 }
11744
11745 llvm_unreachable("Invalid Type::Class!");
11746}
11747
11749 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
11750 bool &CanUseFirst, bool &CanUseSecond,
11752 assert(NewParamInfos.empty() && "param info list not empty");
11753 CanUseFirst = CanUseSecond = true;
11754 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
11755 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
11756
11757 // Fast path: if the first type doesn't have ext parameter infos,
11758 // we match if and only if the second type also doesn't have them.
11759 if (!FirstHasInfo && !SecondHasInfo)
11760 return true;
11761
11762 bool NeedParamInfo = false;
11763 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
11764 : SecondFnType->getExtParameterInfos().size();
11765
11766 for (size_t I = 0; I < E; ++I) {
11767 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
11768 if (FirstHasInfo)
11769 FirstParam = FirstFnType->getExtParameterInfo(I);
11770 if (SecondHasInfo)
11771 SecondParam = SecondFnType->getExtParameterInfo(I);
11772
11773 // Cannot merge unless everything except the noescape flag matches.
11774 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
11775 return false;
11776
11777 bool FirstNoEscape = FirstParam.isNoEscape();
11778 bool SecondNoEscape = SecondParam.isNoEscape();
11779 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
11780 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
11781 if (NewParamInfos.back().getOpaqueValue())
11782 NeedParamInfo = true;
11783 if (FirstNoEscape != IsNoEscape)
11784 CanUseFirst = false;
11785 if (SecondNoEscape != IsNoEscape)
11786 CanUseSecond = false;
11787 }
11788
11789 if (!NeedParamInfo)
11790 NewParamInfos.clear();
11791
11792 return true;
11793}
11794
11796 ObjCLayouts[CD] = nullptr;
11797}
11798
11799/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
11800/// 'RHS' attributes and returns the merged version; including for function
11801/// return types.
11803 QualType LHSCan = getCanonicalType(LHS),
11804 RHSCan = getCanonicalType(RHS);
11805 // If two types are identical, they are compatible.
11806 if (LHSCan == RHSCan)
11807 return LHS;
11808 if (RHSCan->isFunctionType()) {
11809 if (!LHSCan->isFunctionType())
11810 return {};
11811 QualType OldReturnType =
11812 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
11813 QualType NewReturnType =
11814 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
11815 QualType ResReturnType =
11816 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
11817 if (ResReturnType.isNull())
11818 return {};
11819 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
11820 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
11821 // In either case, use OldReturnType to build the new function type.
11822 const auto *F = LHS->castAs<FunctionType>();
11823 if (const auto *FPT = cast<FunctionProtoType>(F)) {
11824 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11825 EPI.ExtInfo = getFunctionExtInfo(LHS);
11826 QualType ResultType =
11827 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
11828 return ResultType;
11829 }
11830 }
11831 return {};
11832 }
11833
11834 // If the qualifiers are different, the types can still be merged.
11835 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11836 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11837 if (LQuals != RQuals) {
11838 // If any of these qualifiers are different, we have a type mismatch.
11839 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11840 LQuals.getAddressSpace() != RQuals.getAddressSpace())
11841 return {};
11842
11843 // Exactly one GC qualifier difference is allowed: __strong is
11844 // okay if the other type has no GC qualifier but is an Objective
11845 // C object pointer (i.e. implicitly strong by default). We fix
11846 // this by pretending that the unqualified type was actually
11847 // qualified __strong.
11848 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11849 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11850 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11851
11852 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11853 return {};
11854
11855 if (GC_L == Qualifiers::Strong)
11856 return LHS;
11857 if (GC_R == Qualifiers::Strong)
11858 return RHS;
11859 return {};
11860 }
11861
11862 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
11863 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11864 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11865 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
11866 if (ResQT == LHSBaseQT)
11867 return LHS;
11868 if (ResQT == RHSBaseQT)
11869 return RHS;
11870 }
11871 return {};
11872}
11873
11874//===----------------------------------------------------------------------===//
11875// Integer Predicates
11876//===----------------------------------------------------------------------===//
11877
11879 if (const auto *ET = T->getAs<EnumType>())
11880 T = ET->getDecl()->getIntegerType();
11881 if (T->isBooleanType())
11882 return 1;
11883 if (const auto *EIT = T->getAs<BitIntType>())
11884 return EIT->getNumBits();
11885 // For builtin types, just use the standard type sizing method
11886 return (unsigned)getTypeSize(T);
11887}
11888
11890 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11891 T->isFixedPointType()) &&
11892 "Unexpected type");
11893
11894 // Turn <4 x signed int> -> <4 x unsigned int>
11895 if (const auto *VTy = T->getAs<VectorType>())
11896 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
11897 VTy->getNumElements(), VTy->getVectorKind());
11898
11899 // For _BitInt, return an unsigned _BitInt with same width.
11900 if (const auto *EITy = T->getAs<BitIntType>())
11901 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
11902
11903 // For enums, get the underlying integer type of the enum, and let the general
11904 // integer type signchanging code handle it.
11905 if (const auto *ETy = T->getAs<EnumType>())
11906 T = ETy->getDecl()->getIntegerType();
11907
11908 switch (T->castAs<BuiltinType>()->getKind()) {
11909 case BuiltinType::Char_U:
11910 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
11911 case BuiltinType::Char_S:
11912 case BuiltinType::SChar:
11913 case BuiltinType::Char8:
11914 return UnsignedCharTy;
11915 case BuiltinType::Short:
11916 return UnsignedShortTy;
11917 case BuiltinType::Int:
11918 return UnsignedIntTy;
11919 case BuiltinType::Long:
11920 return UnsignedLongTy;
11921 case BuiltinType::LongLong:
11922 return UnsignedLongLongTy;
11923 case BuiltinType::Int128:
11924 return UnsignedInt128Ty;
11925 // wchar_t is special. It is either signed or not, but when it's signed,
11926 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
11927 // version of its underlying type instead.
11928 case BuiltinType::WChar_S:
11929 return getUnsignedWCharType();
11930
11931 case BuiltinType::ShortAccum:
11932 return UnsignedShortAccumTy;
11933 case BuiltinType::Accum:
11934 return UnsignedAccumTy;
11935 case BuiltinType::LongAccum:
11936 return UnsignedLongAccumTy;
11937 case BuiltinType::SatShortAccum:
11939 case BuiltinType::SatAccum:
11940 return SatUnsignedAccumTy;
11941 case BuiltinType::SatLongAccum:
11943 case BuiltinType::ShortFract:
11944 return UnsignedShortFractTy;
11945 case BuiltinType::Fract:
11946 return UnsignedFractTy;
11947 case BuiltinType::LongFract:
11948 return UnsignedLongFractTy;
11949 case BuiltinType::SatShortFract:
11951 case BuiltinType::SatFract:
11952 return SatUnsignedFractTy;
11953 case BuiltinType::SatLongFract:
11955 default:
11958 "Unexpected signed integer or fixed point type");
11959 return T;
11960 }
11961}
11962
11964 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11965 T->isFixedPointType()) &&
11966 "Unexpected type");
11967
11968 // Turn <4 x unsigned int> -> <4 x signed int>
11969 if (const auto *VTy = T->getAs<VectorType>())
11970 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
11971 VTy->getNumElements(), VTy->getVectorKind());
11972
11973 // For _BitInt, return a signed _BitInt with same width.
11974 if (const auto *EITy = T->getAs<BitIntType>())
11975 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
11976
11977 // For enums, get the underlying integer type of the enum, and let the general
11978 // integer type signchanging code handle it.
11979 if (const auto *ETy = T->getAs<EnumType>())
11980 T = ETy->getDecl()->getIntegerType();
11981
11982 switch (T->castAs<BuiltinType>()->getKind()) {
11983 case BuiltinType::Char_S:
11984 // Plain `char` is mapped to `signed char` even if it's already signed
11985 case BuiltinType::Char_U:
11986 case BuiltinType::UChar:
11987 case BuiltinType::Char8:
11988 return SignedCharTy;
11989 case BuiltinType::UShort:
11990 return ShortTy;
11991 case BuiltinType::UInt:
11992 return IntTy;
11993 case BuiltinType::ULong:
11994 return LongTy;
11995 case BuiltinType::ULongLong:
11996 return LongLongTy;
11997 case BuiltinType::UInt128:
11998 return Int128Ty;
11999 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12000 // there's no matching "signed wchar_t". Therefore we return the signed
12001 // version of its underlying type instead.
12002 case BuiltinType::WChar_U:
12003 return getSignedWCharType();
12004
12005 case BuiltinType::UShortAccum:
12006 return ShortAccumTy;
12007 case BuiltinType::UAccum:
12008 return AccumTy;
12009 case BuiltinType::ULongAccum:
12010 return LongAccumTy;
12011 case BuiltinType::SatUShortAccum:
12012 return SatShortAccumTy;
12013 case BuiltinType::SatUAccum:
12014 return SatAccumTy;
12015 case BuiltinType::SatULongAccum:
12016 return SatLongAccumTy;
12017 case BuiltinType::UShortFract:
12018 return ShortFractTy;
12019 case BuiltinType::UFract:
12020 return FractTy;
12021 case BuiltinType::ULongFract:
12022 return LongFractTy;
12023 case BuiltinType::SatUShortFract:
12024 return SatShortFractTy;
12025 case BuiltinType::SatUFract:
12026 return SatFractTy;
12027 case BuiltinType::SatULongFract:
12028 return SatLongFractTy;
12029 default:
12030 assert(
12032 "Unexpected signed integer or fixed point type");
12033 return T;
12034 }
12035}
12036
12038
12040 QualType ReturnType) {}
12041
12042//===----------------------------------------------------------------------===//
12043// Builtin Type Computation
12044//===----------------------------------------------------------------------===//
12045
12046/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12047/// pointer over the consumed characters. This returns the resultant type. If
12048/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12049/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12050/// a vector of "i*".
12051///
12052/// RequiresICE is filled in on return to indicate whether the value is required
12053/// to be an Integer Constant Expression.
12054static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12056 bool &RequiresICE,
12057 bool AllowTypeModifiers) {
12058 // Modifiers.
12059 int HowLong = 0;
12060 bool Signed = false, Unsigned = false;
12061 RequiresICE = false;
12062
12063 // Read the prefixed modifiers first.
12064 bool Done = false;
12065 #ifndef NDEBUG
12066 bool IsSpecial = false;
12067 #endif
12068 while (!Done) {
12069 switch (*Str++) {
12070 default: Done = true; --Str; break;
12071 case 'I':
12072 RequiresICE = true;
12073 break;
12074 case 'S':
12075 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12076 assert(!Signed && "Can't use 'S' modifier multiple times!");
12077 Signed = true;
12078 break;
12079 case 'U':
12080 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12081 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12082 Unsigned = true;
12083 break;
12084 case 'L':
12085 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12086 assert(HowLong <= 2 && "Can't have LLLL modifier");
12087 ++HowLong;
12088 break;
12089 case 'N':
12090 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12091 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12092 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12093 #ifndef NDEBUG
12094 IsSpecial = true;
12095 #endif
12096 if (Context.getTargetInfo().getLongWidth() == 32)
12097 ++HowLong;
12098 break;
12099 case 'W':
12100 // This modifier represents int64 type.
12101 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12102 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12103 #ifndef NDEBUG
12104 IsSpecial = true;
12105 #endif
12106 switch (Context.getTargetInfo().getInt64Type()) {
12107 default:
12108 llvm_unreachable("Unexpected integer type");
12110 HowLong = 1;
12111 break;
12113 HowLong = 2;
12114 break;
12115 }
12116 break;
12117 case 'Z':
12118 // This modifier represents int32 type.
12119 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12120 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12121 #ifndef NDEBUG
12122 IsSpecial = true;
12123 #endif
12124 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12125 default:
12126 llvm_unreachable("Unexpected integer type");
12128 HowLong = 0;
12129 break;
12131 HowLong = 1;
12132 break;
12134 HowLong = 2;
12135 break;
12136 }
12137 break;
12138 case 'O':
12139 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12140 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12141 #ifndef NDEBUG
12142 IsSpecial = true;
12143 #endif
12144 if (Context.getLangOpts().OpenCL)
12145 HowLong = 1;
12146 else
12147 HowLong = 2;
12148 break;
12149 }
12150 }
12151
12152 QualType Type;
12153
12154 // Read the base type.
12155 switch (*Str++) {
12156 default: llvm_unreachable("Unknown builtin type letter!");
12157 case 'x':
12158 assert(HowLong == 0 && !Signed && !Unsigned &&
12159 "Bad modifiers used with 'x'!");
12160 Type = Context.Float16Ty;
12161 break;
12162 case 'y':
12163 assert(HowLong == 0 && !Signed && !Unsigned &&
12164 "Bad modifiers used with 'y'!");
12165 Type = Context.BFloat16Ty;
12166 break;
12167 case 'v':
12168 assert(HowLong == 0 && !Signed && !Unsigned &&
12169 "Bad modifiers used with 'v'!");
12170 Type = Context.VoidTy;
12171 break;
12172 case 'h':
12173 assert(HowLong == 0 && !Signed && !Unsigned &&
12174 "Bad modifiers used with 'h'!");
12175 Type = Context.HalfTy;
12176 break;
12177 case 'f':
12178 assert(HowLong == 0 && !Signed && !Unsigned &&
12179 "Bad modifiers used with 'f'!");
12180 Type = Context.FloatTy;
12181 break;
12182 case 'd':
12183 assert(HowLong < 3 && !Signed && !Unsigned &&
12184 "Bad modifiers used with 'd'!");
12185 if (HowLong == 1)
12186 Type = Context.LongDoubleTy;
12187 else if (HowLong == 2)
12188 Type = Context.Float128Ty;
12189 else
12190 Type = Context.DoubleTy;
12191 break;
12192 case 's':
12193 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12194 if (Unsigned)
12195 Type = Context.UnsignedShortTy;
12196 else
12197 Type = Context.ShortTy;
12198 break;
12199 case 'i':
12200 if (HowLong == 3)
12201 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12202 else if (HowLong == 2)
12203 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12204 else if (HowLong == 1)
12205 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12206 else
12207 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12208 break;
12209 case 'c':
12210 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12211 if (Signed)
12212 Type = Context.SignedCharTy;
12213 else if (Unsigned)
12214 Type = Context.UnsignedCharTy;
12215 else
12216 Type = Context.CharTy;
12217 break;
12218 case 'b': // boolean
12219 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12220 Type = Context.BoolTy;
12221 break;
12222 case 'z': // size_t.
12223 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12224 Type = Context.getSizeType();
12225 break;
12226 case 'w': // wchar_t.
12227 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12228 Type = Context.getWideCharType();
12229 break;
12230 case 'F':
12231 Type = Context.getCFConstantStringType();
12232 break;
12233 case 'G':
12234 Type = Context.getObjCIdType();
12235 break;
12236 case 'H':
12237 Type = Context.getObjCSelType();
12238 break;
12239 case 'M':
12240 Type = Context.getObjCSuperType();
12241 break;
12242 case 'a':
12243 Type = Context.getBuiltinVaListType();
12244 assert(!Type.isNull() && "builtin va list type not initialized!");
12245 break;
12246 case 'A':
12247 // This is a "reference" to a va_list; however, what exactly
12248 // this means depends on how va_list is defined. There are two
12249 // different kinds of va_list: ones passed by value, and ones
12250 // passed by reference. An example of a by-value va_list is
12251 // x86, where va_list is a char*. An example of by-ref va_list
12252 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12253 // we want this argument to be a char*&; for x86-64, we want
12254 // it to be a __va_list_tag*.
12255 Type = Context.getBuiltinVaListType();
12256 assert(!Type.isNull() && "builtin va list type not initialized!");
12257 if (Type->isArrayType())
12258 Type = Context.getArrayDecayedType(Type);
12259 else
12260 Type = Context.getLValueReferenceType(Type);
12261 break;
12262 case 'q': {
12263 char *End;
12264 unsigned NumElements = strtoul(Str, &End, 10);
12265 assert(End != Str && "Missing vector size");
12266 Str = End;
12267
12268 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12269 RequiresICE, false);
12270 assert(!RequiresICE && "Can't require vector ICE");
12271
12272 Type = Context.getScalableVectorType(ElementType, NumElements);
12273 break;
12274 }
12275 case 'Q': {
12276 switch (*Str++) {
12277 case 'a': {
12278 Type = Context.SveCountTy;
12279 break;
12280 }
12281 case 'b': {
12282 Type = Context.AMDGPUBufferRsrcTy;
12283 break;
12284 }
12285 default:
12286 llvm_unreachable("Unexpected target builtin type");
12287 }
12288 break;
12289 }
12290 case 'V': {
12291 char *End;
12292 unsigned NumElements = strtoul(Str, &End, 10);
12293 assert(End != Str && "Missing vector size");
12294 Str = End;
12295
12296 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12297 RequiresICE, false);
12298 assert(!RequiresICE && "Can't require vector ICE");
12299
12300 // TODO: No way to make AltiVec vectors in builtins yet.
12301 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12302 break;
12303 }
12304 case 'E': {
12305 char *End;
12306
12307 unsigned NumElements = strtoul(Str, &End, 10);
12308 assert(End != Str && "Missing vector size");
12309
12310 Str = End;
12311
12312 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12313 false);
12314 Type = Context.getExtVectorType(ElementType, NumElements);
12315 break;
12316 }
12317 case 'X': {
12318 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12319 false);
12320 assert(!RequiresICE && "Can't require complex ICE");
12321 Type = Context.getComplexType(ElementType);
12322 break;
12323 }
12324 case 'Y':
12325 Type = Context.getPointerDiffType();
12326 break;
12327 case 'P':
12328 Type = Context.getFILEType();
12329 if (Type.isNull()) {
12331 return {};
12332 }
12333 break;
12334 case 'J':
12335 if (Signed)
12336 Type = Context.getsigjmp_bufType();
12337 else
12338 Type = Context.getjmp_bufType();
12339
12340 if (Type.isNull()) {
12342 return {};
12343 }
12344 break;
12345 case 'K':
12346 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12347 Type = Context.getucontext_tType();
12348
12349 if (Type.isNull()) {
12351 return {};
12352 }
12353 break;
12354 case 'p':
12355 Type = Context.getProcessIDType();
12356 break;
12357 }
12358
12359 // If there are modifiers and if we're allowed to parse them, go for it.
12360 Done = !AllowTypeModifiers;
12361 while (!Done) {
12362 switch (char c = *Str++) {
12363 default: Done = true; --Str; break;
12364 case '*':
12365 case '&': {
12366 // Both pointers and references can have their pointee types
12367 // qualified with an address space.
12368 char *End;
12369 unsigned AddrSpace = strtoul(Str, &End, 10);
12370 if (End != Str) {
12371 // Note AddrSpace == 0 is not the same as an unspecified address space.
12372 Type = Context.getAddrSpaceQualType(
12373 Type,
12374 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12375 Str = End;
12376 }
12377 if (c == '*')
12378 Type = Context.getPointerType(Type);
12379 else
12380 Type = Context.getLValueReferenceType(Type);
12381 break;
12382 }
12383 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12384 case 'C':
12385 Type = Type.withConst();
12386 break;
12387 case 'D':
12388 Type = Context.getVolatileType(Type);
12389 break;
12390 case 'R':
12391 Type = Type.withRestrict();
12392 break;
12393 }
12394 }
12395
12396 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12397 "Integer constant 'I' type must be an integer");
12398
12399 return Type;
12400}
12401
12402// On some targets such as PowerPC, some of the builtins are defined with custom
12403// type descriptors for target-dependent types. These descriptors are decoded in
12404// other functions, but it may be useful to be able to fall back to default
12405// descriptor decoding to define builtins mixing target-dependent and target-
12406// independent types. This function allows decoding one type descriptor with
12407// default decoding.
12408QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12409 GetBuiltinTypeError &Error, bool &RequireICE,
12410 bool AllowTypeModifiers) const {
12411 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12412}
12413
12414/// GetBuiltinType - Return the type for the specified builtin.
12416 GetBuiltinTypeError &Error,
12417 unsigned *IntegerConstantArgs) const {
12418 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12419 if (TypeStr[0] == '\0') {
12420 Error = GE_Missing_type;
12421 return {};
12422 }
12423
12424 SmallVector<QualType, 8> ArgTypes;
12425
12426 bool RequiresICE = false;
12427 Error = GE_None;
12428 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12429 RequiresICE, true);
12430 if (Error != GE_None)
12431 return {};
12432
12433 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12434
12435 while (TypeStr[0] && TypeStr[0] != '.') {
12436 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12437 if (Error != GE_None)
12438 return {};
12439
12440 // If this argument is required to be an IntegerConstantExpression and the
12441 // caller cares, fill in the bitmask we return.
12442 if (RequiresICE && IntegerConstantArgs)
12443 *IntegerConstantArgs |= 1 << ArgTypes.size();
12444
12445 // Do array -> pointer decay. The builtin should use the decayed type.
12446 if (Ty->isArrayType())
12447 Ty = getArrayDecayedType(Ty);
12448
12449 ArgTypes.push_back(Ty);
12450 }
12451
12452 if (Id == Builtin::BI__GetExceptionInfo)
12453 return {};
12454
12455 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12456 "'.' should only occur at end of builtin type list!");
12457
12458 bool Variadic = (TypeStr[0] == '.');
12459
12461 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
12462 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
12463
12464
12465 // We really shouldn't be making a no-proto type here.
12466 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12467 return getFunctionNoProtoType(ResType, EI);
12468
12470 EPI.ExtInfo = EI;
12471 EPI.Variadic = Variadic;
12473 EPI.ExceptionSpec.Type =
12475
12476 return getFunctionType(ResType, ArgTypes, EPI);
12477}
12478
12480 const FunctionDecl *FD) {
12481 if (!FD->isExternallyVisible())
12482 return GVA_Internal;
12483
12484 // Non-user-provided functions get emitted as weak definitions with every
12485 // use, no matter whether they've been explicitly instantiated etc.
12486 if (!FD->isUserProvided())
12487 return GVA_DiscardableODR;
12488
12490 switch (FD->getTemplateSpecializationKind()) {
12491 case TSK_Undeclared:
12494 break;
12495
12497 return GVA_StrongODR;
12498
12499 // C++11 [temp.explicit]p10:
12500 // [ Note: The intent is that an inline function that is the subject of
12501 // an explicit instantiation declaration will still be implicitly
12502 // instantiated when used so that the body can be considered for
12503 // inlining, but that no out-of-line copy of the inline function would be
12504 // generated in the translation unit. -- end note ]
12507
12510 break;
12511 }
12512
12513 if (!FD->isInlined())
12514 return External;
12515
12516 if ((!Context.getLangOpts().CPlusPlus &&
12517 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12518 !FD->hasAttr<DLLExportAttr>()) ||
12519 FD->hasAttr<GNUInlineAttr>()) {
12520 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12521
12522 // GNU or C99 inline semantics. Determine whether this symbol should be
12523 // externally visible.
12525 return External;
12526
12527 // C99 inline semantics, where the symbol is not externally visible.
12529 }
12530
12531 // Functions specified with extern and inline in -fms-compatibility mode
12532 // forcibly get emitted. While the body of the function cannot be later
12533 // replaced, the function definition cannot be discarded.
12534 if (FD->isMSExternInline())
12535 return GVA_StrongODR;
12536
12537 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12538 isa<CXXConstructorDecl>(FD) &&
12539 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
12540 // Our approach to inheriting constructors is fundamentally different from
12541 // that used by the MS ABI, so keep our inheriting constructor thunks
12542 // internal rather than trying to pick an unambiguous mangling for them.
12543 return GVA_Internal;
12544
12545 return GVA_DiscardableODR;
12546}
12547
12549 const Decl *D, GVALinkage L) {
12550 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
12551 // dllexport/dllimport on inline functions.
12552 if (D->hasAttr<DLLImportAttr>()) {
12553 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
12555 } else if (D->hasAttr<DLLExportAttr>()) {
12556 if (L == GVA_DiscardableODR)
12557 return GVA_StrongODR;
12558 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
12559 // Device-side functions with __global__ attribute must always be
12560 // visible externally so they can be launched from host.
12561 if (D->hasAttr<CUDAGlobalAttr>() &&
12562 (L == GVA_DiscardableODR || L == GVA_Internal))
12563 return GVA_StrongODR;
12564 // Single source offloading languages like CUDA/HIP need to be able to
12565 // access static device variables from host code of the same compilation
12566 // unit. This is done by externalizing the static variable with a shared
12567 // name between the host and device compilation which is the same for the
12568 // same compilation unit whereas different among different compilation
12569 // units.
12570 if (Context.shouldExternalize(D))
12571 return GVA_StrongExternal;
12572 }
12573 return L;
12574}
12575
12576/// Adjust the GVALinkage for a declaration based on what an external AST source
12577/// knows about whether there can be other definitions of this declaration.
12578static GVALinkage
12580 GVALinkage L) {
12581 ExternalASTSource *Source = Ctx.getExternalSource();
12582 if (!Source)
12583 return L;
12584
12585 switch (Source->hasExternalDefinitions(D)) {
12587 // Other translation units rely on us to provide the definition.
12588 if (L == GVA_DiscardableODR)
12589 return GVA_StrongODR;
12590 break;
12591
12594
12596 break;
12597 }
12598 return L;
12599}
12600
12604 basicGVALinkageForFunction(*this, FD)));
12605}
12606
12608 const VarDecl *VD) {
12609 // As an extension for interactive REPLs, make sure constant variables are
12610 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
12611 // marking them as internal.
12612 if (Context.getLangOpts().CPlusPlus &&
12613 Context.getLangOpts().IncrementalExtensions &&
12614 VD->getType().isConstQualified() &&
12615 !VD->getType().isVolatileQualified() && !VD->isInline() &&
12616 !isa<VarTemplateSpecializationDecl>(VD) && !VD->getDescribedVarTemplate())
12617 return GVA_DiscardableODR;
12618
12619 if (!VD->isExternallyVisible())
12620 return GVA_Internal;
12621
12622 if (VD->isStaticLocal()) {
12623 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
12624 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
12625 LexicalContext = LexicalContext->getLexicalParent();
12626
12627 // ObjC Blocks can create local variables that don't have a FunctionDecl
12628 // LexicalContext.
12629 if (!LexicalContext)
12630 return GVA_DiscardableODR;
12631
12632 // Otherwise, let the static local variable inherit its linkage from the
12633 // nearest enclosing function.
12634 auto StaticLocalLinkage =
12635 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
12636
12637 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
12638 // be emitted in any object with references to the symbol for the object it
12639 // contains, whether inline or out-of-line."
12640 // Similar behavior is observed with MSVC. An alternative ABI could use
12641 // StrongODR/AvailableExternally to match the function, but none are
12642 // known/supported currently.
12643 if (StaticLocalLinkage == GVA_StrongODR ||
12644 StaticLocalLinkage == GVA_AvailableExternally)
12645 return GVA_DiscardableODR;
12646 return StaticLocalLinkage;
12647 }
12648
12649 // MSVC treats in-class initialized static data members as definitions.
12650 // By giving them non-strong linkage, out-of-line definitions won't
12651 // cause link errors.
12653 return GVA_DiscardableODR;
12654
12655 // Most non-template variables have strong linkage; inline variables are
12656 // linkonce_odr or (occasionally, for compatibility) weak_odr.
12657 GVALinkage StrongLinkage;
12658 switch (Context.getInlineVariableDefinitionKind(VD)) {
12660 StrongLinkage = GVA_StrongExternal;
12661 break;
12664 StrongLinkage = GVA_DiscardableODR;
12665 break;
12667 StrongLinkage = GVA_StrongODR;
12668 break;
12669 }
12670
12671 switch (VD->getTemplateSpecializationKind()) {
12672 case TSK_Undeclared:
12673 return StrongLinkage;
12674
12676 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12677 VD->isStaticDataMember()
12679 : StrongLinkage;
12680
12682 return GVA_StrongODR;
12683
12686
12688 return GVA_DiscardableODR;
12689 }
12690
12691 llvm_unreachable("Invalid Linkage!");
12692}
12693
12697 basicGVALinkageForVariable(*this, VD)));
12698}
12699
12701 if (const auto *VD = dyn_cast<VarDecl>(D)) {
12702 if (!VD->isFileVarDecl())
12703 return false;
12704 // Global named register variables (GNU extension) are never emitted.
12705 if (VD->getStorageClass() == SC_Register)
12706 return false;
12707 if (VD->getDescribedVarTemplate() ||
12708 isa<VarTemplatePartialSpecializationDecl>(VD))
12709 return false;
12710 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
12711 // We never need to emit an uninstantiated function template.
12712 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12713 return false;
12714 } else if (isa<PragmaCommentDecl>(D))
12715 return true;
12716 else if (isa<PragmaDetectMismatchDecl>(D))
12717 return true;
12718 else if (isa<OMPRequiresDecl>(D))
12719 return true;
12720 else if (isa<OMPThreadPrivateDecl>(D))
12721 return !D->getDeclContext()->isDependentContext();
12722 else if (isa<OMPAllocateDecl>(D))
12723 return !D->getDeclContext()->isDependentContext();
12724 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
12725 return !D->getDeclContext()->isDependentContext();
12726 else if (isa<ImportDecl>(D))
12727 return true;
12728 else
12729 return false;
12730
12731 // If this is a member of a class template, we do not need to emit it.
12733 return false;
12734
12735 // Weak references don't produce any output by themselves.
12736 if (D->hasAttr<WeakRefAttr>())
12737 return false;
12738
12739 // Aliases and used decls are required.
12740 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
12741 return true;
12742
12743 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
12744 // Forward declarations aren't required.
12745 if (!FD->doesThisDeclarationHaveABody())
12746 return FD->doesDeclarationForceExternallyVisibleDefinition();
12747
12748 // Constructors and destructors are required.
12749 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
12750 return true;
12751
12752 // The key function for a class is required. This rule only comes
12753 // into play when inline functions can be key functions, though.
12754 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12755 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12756 const CXXRecordDecl *RD = MD->getParent();
12757 if (MD->isOutOfLine() && RD->isDynamicClass()) {
12758 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
12759 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
12760 return true;
12761 }
12762 }
12763 }
12764
12766
12767 // static, static inline, always_inline, and extern inline functions can
12768 // always be deferred. Normal inline functions can be deferred in C99/C++.
12769 // Implicit template instantiations can also be deferred in C++.
12771 }
12772
12773 const auto *VD = cast<VarDecl>(D);
12774 assert(VD->isFileVarDecl() && "Expected file scoped var");
12775
12776 // If the decl is marked as `declare target to`, it should be emitted for the
12777 // host and for the device.
12778 if (LangOpts.OpenMP &&
12779 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
12780 return true;
12781
12782 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
12784 return false;
12785
12786 if (VD->shouldEmitInExternalSource())
12787 return false;
12788
12789 // Variables that can be needed in other TUs are required.
12792 return true;
12793
12794 // We never need to emit a variable that is available in another TU.
12796 return false;
12797
12798 // Variables that have destruction with side-effects are required.
12799 if (VD->needsDestruction(*this))
12800 return true;
12801
12802 // Variables that have initialization with side-effects are required.
12803 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
12804 // We can get a value-dependent initializer during error recovery.
12805 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
12806 return true;
12807
12808 // Likewise, variables with tuple-like bindings are required if their
12809 // bindings have side-effects.
12810 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
12811 for (const auto *BD : DD->bindings())
12812 if (const auto *BindingVD = BD->getHoldingVar())
12813 if (DeclMustBeEmitted(BindingVD))
12814 return true;
12815
12816 return false;
12817}
12818
12820 const FunctionDecl *FD,
12821 llvm::function_ref<void(FunctionDecl *)> Pred) const {
12822 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
12823 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
12824 FD = FD->getMostRecentDecl();
12825 // FIXME: The order of traversal here matters and depends on the order of
12826 // lookup results, which happens to be (mostly) oldest-to-newest, but we
12827 // shouldn't rely on that.
12828 for (auto *CurDecl :
12830 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
12831 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
12832 SeenDecls.insert(CurFD).second) {
12833 Pred(CurFD);
12834 }
12835 }
12836}
12837
12839 bool IsCXXMethod,
12840 bool IsBuiltin) const {
12841 // Pass through to the C++ ABI object
12842 if (IsCXXMethod)
12843 return ABI->getDefaultMethodCallConv(IsVariadic);
12844
12845 // Builtins ignore user-specified default calling convention and remain the
12846 // Target's default calling convention.
12847 if (!IsBuiltin) {
12848 switch (LangOpts.getDefaultCallingConv()) {
12850 break;
12852 return CC_C;
12854 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
12855 return CC_X86FastCall;
12856 break;
12858 if (!IsVariadic)
12859 return CC_X86StdCall;
12860 break;
12862 // __vectorcall cannot be applied to variadic functions.
12863 if (!IsVariadic)
12864 return CC_X86VectorCall;
12865 break;
12867 // __regcall cannot be applied to variadic functions.
12868 if (!IsVariadic)
12869 return CC_X86RegCall;
12870 break;
12872 if (!IsVariadic)
12873 return CC_M68kRTD;
12874 break;
12875 }
12876 }
12877 return Target->getDefaultCallingConv();
12878}
12879
12881 // Pass through to the C++ ABI object
12882 return ABI->isNearlyEmpty(RD);
12883}
12884
12886 if (!VTContext.get()) {
12887 auto ABI = Target->getCXXABI();
12888 if (ABI.isMicrosoft())
12889 VTContext.reset(new MicrosoftVTableContext(*this));
12890 else {
12891 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
12894 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
12895 }
12896 }
12897 return VTContext.get();
12898}
12899
12901 if (!T)
12902 T = Target;
12903 switch (T->getCXXABI().getKind()) {
12904 case TargetCXXABI::AppleARM64:
12905 case TargetCXXABI::Fuchsia:
12906 case TargetCXXABI::GenericAArch64:
12907 case TargetCXXABI::GenericItanium:
12908 case TargetCXXABI::GenericARM:
12909 case TargetCXXABI::GenericMIPS:
12910 case TargetCXXABI::iOS:
12911 case TargetCXXABI::WebAssembly:
12912 case TargetCXXABI::WatchOS:
12913 case TargetCXXABI::XL:
12915 case TargetCXXABI::Microsoft:
12917 }
12918 llvm_unreachable("Unsupported ABI");
12919}
12920
12922 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
12923 "Device mangle context does not support Microsoft mangling.");
12924 switch (T.getCXXABI().getKind()) {
12925 case TargetCXXABI::AppleARM64:
12926 case TargetCXXABI::Fuchsia:
12927 case TargetCXXABI::GenericAArch64:
12928 case TargetCXXABI::GenericItanium:
12929 case TargetCXXABI::GenericARM:
12930 case TargetCXXABI::GenericMIPS:
12931 case TargetCXXABI::iOS:
12932 case TargetCXXABI::WebAssembly:
12933 case TargetCXXABI::WatchOS:
12934 case TargetCXXABI::XL:
12936 *this, getDiagnostics(),
12937 [](ASTContext &, const NamedDecl *ND) -> std::optional<unsigned> {
12938 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
12939 return RD->getDeviceLambdaManglingNumber();
12940 return std::nullopt;
12941 },
12942 /*IsAux=*/true);
12943 case TargetCXXABI::Microsoft:
12945 /*IsAux=*/true);
12946 }
12947 llvm_unreachable("Unsupported ABI");
12948}
12949
12950CXXABI::~CXXABI() = default;
12951
12953 return ASTRecordLayouts.getMemorySize() +
12954 llvm::capacity_in_bytes(ObjCLayouts) +
12955 llvm::capacity_in_bytes(KeyFunctions) +
12956 llvm::capacity_in_bytes(ObjCImpls) +
12957 llvm::capacity_in_bytes(BlockVarCopyInits) +
12958 llvm::capacity_in_bytes(DeclAttrs) +
12959 llvm::capacity_in_bytes(TemplateOrInstantiation) +
12960 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
12961 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
12962 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
12963 llvm::capacity_in_bytes(OverriddenMethods) +
12964 llvm::capacity_in_bytes(Types) +
12965 llvm::capacity_in_bytes(VariableArrayTypes);
12966}
12967
12968/// getIntTypeForBitwidth -
12969/// sets integer QualTy according to specified details:
12970/// bitwidth, signed/unsigned.
12971/// Returns empty type if there is no appropriate target types.
12973 unsigned Signed) const {
12975 CanQualType QualTy = getFromTargetType(Ty);
12976 if (!QualTy && DestWidth == 128)
12977 return Signed ? Int128Ty : UnsignedInt128Ty;
12978 return QualTy;
12979}
12980
12981/// getRealTypeForBitwidth -
12982/// sets floating point QualTy according to specified bitwidth.
12983/// Returns empty type if there is no appropriate target types.
12985 FloatModeKind ExplicitType) const {
12986 FloatModeKind Ty =
12987 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
12988 switch (Ty) {
12990 return HalfTy;
12992 return FloatTy;
12994 return DoubleTy;
12996 return LongDoubleTy;
12998 return Float128Ty;
13000 return Ibm128Ty;
13002 return {};
13003 }
13004
13005 llvm_unreachable("Unhandled TargetInfo::RealType value");
13006}
13007
13008void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13009 if (Number <= 1)
13010 return;
13011
13012 MangleNumbers[ND] = Number;
13013
13014 if (Listener)
13015 Listener->AddedManglingNumber(ND, Number);
13016}
13017
13019 bool ForAuxTarget) const {
13020 auto I = MangleNumbers.find(ND);
13021 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13022 // CUDA/HIP host compilation encodes host and device mangling numbers
13023 // as lower and upper half of 32 bit integer.
13024 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13025 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13026 } else {
13027 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13028 "number for aux target");
13029 }
13030 return Res > 1 ? Res : 1;
13031}
13032
13033void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13034 if (Number <= 1)
13035 return;
13036
13037 StaticLocalNumbers[VD] = Number;
13038
13039 if (Listener)
13040 Listener->AddedStaticLocalNumbers(VD, Number);
13041}
13042
13044 auto I = StaticLocalNumbers.find(VD);
13045 return I != StaticLocalNumbers.end() ? I->second : 1;
13046}
13047
13050 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13051 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13052 if (!MCtx)
13054 return *MCtx;
13055}
13056
13059 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13060 std::unique_ptr<MangleNumberingContext> &MCtx =
13061 ExtraMangleNumberingContexts[D];
13062 if (!MCtx)
13064 return *MCtx;
13065}
13066
13067std::unique_ptr<MangleNumberingContext>
13069 return ABI->createMangleNumberingContext();
13070}
13071
13072const CXXConstructorDecl *
13074 return ABI->getCopyConstructorForExceptionObject(
13075 cast<CXXRecordDecl>(RD->getFirstDecl()));
13076}
13077
13079 CXXConstructorDecl *CD) {
13080 return ABI->addCopyConstructorForExceptionObject(
13081 cast<CXXRecordDecl>(RD->getFirstDecl()),
13082 cast<CXXConstructorDecl>(CD->getFirstDecl()));
13083}
13084
13086 TypedefNameDecl *DD) {
13087 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13088}
13089
13092 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13093}
13094
13096 DeclaratorDecl *DD) {
13097 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13098}
13099
13101 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13102}
13103
13104void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
13105 ParamIndices[D] = index;
13106}
13107
13109 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13110 assert(I != ParamIndices.end() &&
13111 "ParmIndices lacks entry set by ParmVarDecl");
13112 return I->second;
13113}
13114
13116 unsigned Length) const {
13117 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13118 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13119 EltTy = EltTy.withConst();
13120
13121 EltTy = adjustStringLiteralBaseType(EltTy);
13122
13123 // Get an array type for the string, according to C99 6.4.5. This includes
13124 // the null terminator character.
13125 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13126 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13127}
13128
13131 StringLiteral *&Result = StringLiteralCache[Key];
13132 if (!Result)
13134 *this, Key, StringLiteralKind::Ordinary,
13135 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13136 SourceLocation());
13137 return Result;
13138}
13139
13140MSGuidDecl *
13142 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13143
13144 llvm::FoldingSetNodeID ID;
13145 MSGuidDecl::Profile(ID, Parts);
13146
13147 void *InsertPos;
13148 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13149 return Existing;
13150
13151 QualType GUIDType = getMSGuidType().withConst();
13152 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13153 MSGuidDecls.InsertNode(New, InsertPos);
13154 return New;
13155}
13156
13159 const APValue &APVal) const {
13160 llvm::FoldingSetNodeID ID;
13162
13163 void *InsertPos;
13164 if (UnnamedGlobalConstantDecl *Existing =
13165 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13166 return Existing;
13167
13169 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13170 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13171 return New;
13172}
13173
13176 assert(T->isRecordType() && "template param object of unexpected type");
13177
13178 // C++ [temp.param]p8:
13179 // [...] a static storage duration object of type 'const T' [...]
13180 T.addConst();
13181
13182 llvm::FoldingSetNodeID ID;
13184
13185 void *InsertPos;
13186 if (TemplateParamObjectDecl *Existing =
13187 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13188 return Existing;
13189
13190 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13191 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13192 return New;
13193}
13194
13196 const llvm::Triple &T = getTargetInfo().getTriple();
13197 if (!T.isOSDarwin())
13198 return false;
13199
13200 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13201 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13202 return false;
13203
13204 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13205 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13206 uint64_t Size = sizeChars.getQuantity();
13207 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13208 unsigned Align = alignChars.getQuantity();
13209 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13210 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13211}
13212
13213bool
13215 const ObjCMethodDecl *MethodImpl) {
13216 // No point trying to match an unavailable/deprecated mothod.
13217 if (MethodDecl->hasAttr<UnavailableAttr>()
13218 || MethodDecl->hasAttr<DeprecatedAttr>())
13219 return false;
13220 if (MethodDecl->getObjCDeclQualifier() !=
13221 MethodImpl->getObjCDeclQualifier())
13222 return false;
13223 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13224 return false;
13225
13226 if (MethodDecl->param_size() != MethodImpl->param_size())
13227 return false;
13228
13229 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13230 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13231 EF = MethodDecl->param_end();
13232 IM != EM && IF != EF; ++IM, ++IF) {
13233 const ParmVarDecl *DeclVar = (*IF);
13234 const ParmVarDecl *ImplVar = (*IM);
13235 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13236 return false;
13237 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13238 return false;
13239 }
13240
13241 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13242}
13243
13245 LangAS AS;
13247 AS = LangAS::Default;
13248 else
13249 AS = QT->getPointeeType().getAddressSpace();
13250
13252}
13253
13256}
13257
13258bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13259 if (X == Y)
13260 return true;
13261 if (!X || !Y)
13262 return false;
13263 llvm::FoldingSetNodeID IDX, IDY;
13264 X->Profile(IDX, *this, /*Canonical=*/true);
13265 Y->Profile(IDY, *this, /*Canonical=*/true);
13266 return IDX == IDY;
13267}
13268
13269// The getCommon* helpers return, for given 'same' X and Y entities given as
13270// inputs, another entity which is also the 'same' as the inputs, but which
13271// is closer to the canonical form of the inputs, each according to a given
13272// criteria.
13273// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13274// the regular ones.
13275
13277 if (!declaresSameEntity(X, Y))
13278 return nullptr;
13279 for (const Decl *DX : X->redecls()) {
13280 // If we reach Y before reaching the first decl, that means X is older.
13281 if (DX == Y)
13282 return X;
13283 // If we reach the first decl, then Y is older.
13284 if (DX->isFirstDecl())
13285 return Y;
13286 }
13287 llvm_unreachable("Corrupt redecls chain");
13288}
13289
13290template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13291static T *getCommonDecl(T *X, T *Y) {
13292 return cast_or_null<T>(
13293 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13294 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13295}
13296
13297template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13298static T *getCommonDeclChecked(T *X, T *Y) {
13299 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13300 const_cast<Decl *>(cast<Decl>(Y))));
13301}
13302
13304 TemplateName Y,
13305 bool IgnoreDeduced = false) {
13306 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13307 return X;
13308 // FIXME: There are cases here where we could find a common template name
13309 // with more sugar. For example one could be a SubstTemplateTemplate*
13310 // replacing the other.
13311 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13312 if (CX.getAsVoidPointer() !=
13314 return TemplateName();
13315 return CX;
13316}
13317
13320 bool IgnoreDeduced) {
13321 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13322 assert(R.getAsVoidPointer() != nullptr);
13323 return R;
13324}
13325
13327 ArrayRef<QualType> Ys, bool Unqualified = false) {
13328 assert(Xs.size() == Ys.size());
13329 SmallVector<QualType, 8> Rs(Xs.size());
13330 for (size_t I = 0; I < Rs.size(); ++I)
13331 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13332 return Rs;
13333}
13334
13335template <class T>
13336static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13337 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13338 : SourceLocation();
13339}
13340
13342 const TemplateArgument &X,
13343 const TemplateArgument &Y) {
13344 if (X.getKind() != Y.getKind())
13345 return TemplateArgument();
13346
13347 switch (X.getKind()) {
13349 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13350 return TemplateArgument();
13351 return TemplateArgument(
13352 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13354 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13355 return TemplateArgument();
13356 return TemplateArgument(
13357 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13358 /*Unqualified=*/true);
13360 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13361 return TemplateArgument();
13362 // FIXME: Try to keep the common sugar.
13363 return X;
13365 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13366 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13367 if (!CTN.getAsVoidPointer())
13368 return TemplateArgument();
13369 return TemplateArgument(CTN);
13370 }
13372 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13374 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13375 if (!CTN.getAsVoidPointer())
13376 return TemplateName();
13377 auto NExpX = X.getNumTemplateExpansions();
13378 assert(NExpX == Y.getNumTemplateExpansions());
13379 return TemplateArgument(CTN, NExpX);
13380 }
13381 default:
13382 // FIXME: Handle the other argument kinds.
13383 return X;
13384 }
13385}
13386
13391 if (Xs.size() != Ys.size())
13392 return true;
13393 R.resize(Xs.size());
13394 for (size_t I = 0; I < R.size(); ++I) {
13395 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
13396 if (R[I].isNull())
13397 return true;
13398 }
13399 return false;
13400}
13401
13406 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
13407 assert(!Different);
13408 (void)Different;
13409 return R;
13410}
13411
13412template <class T>
13414 return X->getKeyword() == Y->getKeyword() ? X->getKeyword()
13416}
13417
13418template <class T>
13420 const T *Y) {
13421 // FIXME: Try to keep the common NNS sugar.
13422 return X->getQualifier() == Y->getQualifier()
13423 ? X->getQualifier()
13424 : Ctx.getCanonicalNestedNameSpecifier(X->getQualifier());
13425}
13426
13427template <class T>
13428static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y) {
13429 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
13430}
13431
13432template <class T>
13434 Qualifiers &QX, const T *Y,
13435 Qualifiers &QY) {
13436 QualType EX = X->getElementType(), EY = Y->getElementType();
13437 QualType R = Ctx.getCommonSugaredType(EX, EY,
13438 /*Unqualified=*/true);
13439 Qualifiers RQ = R.getQualifiers();
13440 QX += EX.getQualifiers() - RQ;
13441 QY += EY.getQualifiers() - RQ;
13442 return R;
13443}
13444
13445template <class T>
13446static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y) {
13447 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
13448}
13449
13450template <class T> static auto *getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y) {
13451 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
13452 return X->getSizeExpr();
13453}
13454
13455static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
13456 assert(X->getSizeModifier() == Y->getSizeModifier());
13457 return X->getSizeModifier();
13458}
13459
13461 const ArrayType *Y) {
13462 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
13463 return X->getIndexTypeCVRQualifiers();
13464}
13465
13466// Merges two type lists such that the resulting vector will contain
13467// each type (in a canonical sense) only once, in the order they appear
13468// from X to Y. If they occur in both X and Y, the result will contain
13469// the common sugared type between them.
13472 llvm::DenseMap<QualType, unsigned> Found;
13473 for (auto Ts : {X, Y}) {
13474 for (QualType T : Ts) {
13475 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
13476 if (!Res.second) {
13477 QualType &U = Out[Res.first->second];
13478 U = Ctx.getCommonSugaredType(U, T);
13479 } else {
13480 Out.emplace_back(T);
13481 }
13482 }
13483 }
13484}
13485
13489 SmallVectorImpl<QualType> &ExceptionTypeStorage,
13490 bool AcceptDependent) {
13491 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
13492
13493 // If either of them can throw anything, that is the result.
13494 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
13495 if (EST1 == I)
13496 return ESI1;
13497 if (EST2 == I)
13498 return ESI2;
13499 }
13500
13501 // If either of them is non-throwing, the result is the other.
13502 for (auto I :
13504 if (EST1 == I)
13505 return ESI2;
13506 if (EST2 == I)
13507 return ESI1;
13508 }
13509
13510 // If we're left with value-dependent computed noexcept expressions, we're
13511 // stuck. Before C++17, we can just drop the exception specification entirely,
13512 // since it's not actually part of the canonical type. And this should never
13513 // happen in C++17, because it would mean we were computing the composite
13514 // pointer type of dependent types, which should never happen.
13515 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
13516 assert(AcceptDependent &&
13517 "computing composite pointer type of dependent types");
13519 }
13520
13521 // Switch over the possibilities so that people adding new values know to
13522 // update this function.
13523 switch (EST1) {
13524 case EST_None:
13525 case EST_DynamicNone:
13526 case EST_MSAny:
13527 case EST_BasicNoexcept:
13529 case EST_NoexceptFalse:
13530 case EST_NoexceptTrue:
13531 case EST_NoThrow:
13532 llvm_unreachable("These ESTs should be handled above");
13533
13534 case EST_Dynamic: {
13535 // This is the fun case: both exception specifications are dynamic. Form
13536 // the union of the two lists.
13537 assert(EST2 == EST_Dynamic && "other cases should already be handled");
13538 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
13539 ESI2.Exceptions);
13541 Result.Exceptions = ExceptionTypeStorage;
13542 return Result;
13543 }
13544
13545 case EST_Unevaluated:
13546 case EST_Uninstantiated:
13547 case EST_Unparsed:
13548 llvm_unreachable("shouldn't see unresolved exception specifications here");
13549 }
13550
13551 llvm_unreachable("invalid ExceptionSpecificationType");
13552}
13553
13555 Qualifiers &QX, const Type *Y,
13556 Qualifiers &QY) {
13557 Type::TypeClass TC = X->getTypeClass();
13558 assert(TC == Y->getTypeClass());
13559 switch (TC) {
13560#define UNEXPECTED_TYPE(Class, Kind) \
13561 case Type::Class: \
13562 llvm_unreachable("Unexpected " Kind ": " #Class);
13563
13564#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
13565#define TYPE(Class, Base)
13566#include "clang/AST/TypeNodes.inc"
13567
13568#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
13569 SUGAR_FREE_TYPE(Builtin)
13570 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
13571 SUGAR_FREE_TYPE(DependentBitInt)
13574 SUGAR_FREE_TYPE(ObjCInterface)
13576 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
13577 SUGAR_FREE_TYPE(UnresolvedUsing)
13578 SUGAR_FREE_TYPE(HLSLAttributedResource)
13579#undef SUGAR_FREE_TYPE
13580#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
13581 NON_UNIQUE_TYPE(TypeOfExpr)
13582 NON_UNIQUE_TYPE(VariableArray)
13583#undef NON_UNIQUE_TYPE
13584
13585 UNEXPECTED_TYPE(TypeOf, "sugar")
13586
13587#undef UNEXPECTED_TYPE
13588
13589 case Type::Auto: {
13590 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13591 assert(AX->getDeducedType().isNull());
13592 assert(AY->getDeducedType().isNull());
13593 assert(AX->getKeyword() == AY->getKeyword());
13594 assert(AX->isInstantiationDependentType() ==
13595 AY->isInstantiationDependentType());
13596 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
13597 AY->getTypeConstraintArguments());
13598 return Ctx.getAutoType(QualType(), AX->getKeyword(),
13600 AX->containsUnexpandedParameterPack(),
13601 getCommonDeclChecked(AX->getTypeConstraintConcept(),
13602 AY->getTypeConstraintConcept()),
13603 As);
13604 }
13605 case Type::IncompleteArray: {
13606 const auto *AX = cast<IncompleteArrayType>(X),
13607 *AY = cast<IncompleteArrayType>(Y);
13608 return Ctx.getIncompleteArrayType(
13609 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13611 }
13612 case Type::DependentSizedArray: {
13613 const auto *AX = cast<DependentSizedArrayType>(X),
13614 *AY = cast<DependentSizedArrayType>(Y);
13615 return Ctx.getDependentSizedArrayType(
13616 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13617 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
13619 AX->getBracketsRange() == AY->getBracketsRange()
13620 ? AX->getBracketsRange()
13621 : SourceRange());
13622 }
13623 case Type::ConstantArray: {
13624 const auto *AX = cast<ConstantArrayType>(X),
13625 *AY = cast<ConstantArrayType>(Y);
13626 assert(AX->getSize() == AY->getSize());
13627 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13628 ? AX->getSizeExpr()
13629 : nullptr;
13630 return Ctx.getConstantArrayType(
13631 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
13633 }
13634 case Type::ArrayParameter: {
13635 const auto *AX = cast<ArrayParameterType>(X),
13636 *AY = cast<ArrayParameterType>(Y);
13637 assert(AX->getSize() == AY->getSize());
13638 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13639 ? AX->getSizeExpr()
13640 : nullptr;
13641 auto ArrayTy = Ctx.getConstantArrayType(
13642 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
13644 return Ctx.getArrayParameterType(ArrayTy);
13645 }
13646 case Type::Atomic: {
13647 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
13648 return Ctx.getAtomicType(
13649 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
13650 }
13651 case Type::Complex: {
13652 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
13653 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
13654 }
13655 case Type::Pointer: {
13656 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
13657 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
13658 }
13659 case Type::BlockPointer: {
13660 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
13661 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
13662 }
13663 case Type::ObjCObjectPointer: {
13664 const auto *PX = cast<ObjCObjectPointerType>(X),
13665 *PY = cast<ObjCObjectPointerType>(Y);
13666 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
13667 }
13668 case Type::MemberPointer: {
13669 const auto *PX = cast<MemberPointerType>(X),
13670 *PY = cast<MemberPointerType>(Y);
13671 return Ctx.getMemberPointerType(
13672 getCommonPointeeType(Ctx, PX, PY),
13673 Ctx.getCommonSugaredType(QualType(PX->getClass(), 0),
13674 QualType(PY->getClass(), 0))
13675 .getTypePtr());
13676 }
13677 case Type::LValueReference: {
13678 const auto *PX = cast<LValueReferenceType>(X),
13679 *PY = cast<LValueReferenceType>(Y);
13680 // FIXME: Preserve PointeeTypeAsWritten.
13681 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
13682 PX->isSpelledAsLValue() ||
13683 PY->isSpelledAsLValue());
13684 }
13685 case Type::RValueReference: {
13686 const auto *PX = cast<RValueReferenceType>(X),
13687 *PY = cast<RValueReferenceType>(Y);
13688 // FIXME: Preserve PointeeTypeAsWritten.
13689 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
13690 }
13691 case Type::DependentAddressSpace: {
13692 const auto *PX = cast<DependentAddressSpaceType>(X),
13693 *PY = cast<DependentAddressSpaceType>(Y);
13694 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
13695 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
13696 PX->getAddrSpaceExpr(),
13697 getCommonAttrLoc(PX, PY));
13698 }
13699 case Type::FunctionNoProto: {
13700 const auto *FX = cast<FunctionNoProtoType>(X),
13701 *FY = cast<FunctionNoProtoType>(Y);
13702 assert(FX->getExtInfo() == FY->getExtInfo());
13703 return Ctx.getFunctionNoProtoType(
13704 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
13705 FX->getExtInfo());
13706 }
13707 case Type::FunctionProto: {
13708 const auto *FX = cast<FunctionProtoType>(X),
13709 *FY = cast<FunctionProtoType>(Y);
13710 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
13711 EPIY = FY->getExtProtoInfo();
13712 assert(EPIX.ExtInfo == EPIY.ExtInfo);
13713 assert(EPIX.ExtParameterInfos == EPIY.ExtParameterInfos);
13714 assert(EPIX.RefQualifier == EPIY.RefQualifier);
13715 assert(EPIX.TypeQuals == EPIY.TypeQuals);
13716 assert(EPIX.Variadic == EPIY.Variadic);
13717
13718 // FIXME: Can we handle an empty EllipsisLoc?
13719 // Use emtpy EllipsisLoc if X and Y differ.
13720
13721 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
13722
13723 QualType R =
13724 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
13725 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
13726 /*Unqualified=*/true);
13727
13728 SmallVector<QualType, 8> Exceptions;
13730 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
13731 return Ctx.getFunctionType(R, P, EPIX);
13732 }
13733 case Type::ObjCObject: {
13734 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
13735 assert(
13736 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
13737 OY->getProtocols().begin(), OY->getProtocols().end(),
13738 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
13739 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
13740 }) &&
13741 "protocol lists must be the same");
13742 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
13743 OY->getTypeArgsAsWritten());
13744 return Ctx.getObjCObjectType(
13745 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
13746 OX->getProtocols(),
13747 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
13748 }
13749 case Type::ConstantMatrix: {
13750 const auto *MX = cast<ConstantMatrixType>(X),
13751 *MY = cast<ConstantMatrixType>(Y);
13752 assert(MX->getNumRows() == MY->getNumRows());
13753 assert(MX->getNumColumns() == MY->getNumColumns());
13754 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
13755 MX->getNumRows(), MX->getNumColumns());
13756 }
13757 case Type::DependentSizedMatrix: {
13758 const auto *MX = cast<DependentSizedMatrixType>(X),
13759 *MY = cast<DependentSizedMatrixType>(Y);
13760 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
13761 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
13762 return Ctx.getDependentSizedMatrixType(
13763 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
13764 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
13765 }
13766 case Type::Vector: {
13767 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
13768 assert(VX->getNumElements() == VY->getNumElements());
13769 assert(VX->getVectorKind() == VY->getVectorKind());
13770 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
13771 VX->getNumElements(), VX->getVectorKind());
13772 }
13773 case Type::ExtVector: {
13774 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
13775 assert(VX->getNumElements() == VY->getNumElements());
13776 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
13777 VX->getNumElements());
13778 }
13779 case Type::DependentSizedExtVector: {
13780 const auto *VX = cast<DependentSizedExtVectorType>(X),
13781 *VY = cast<DependentSizedExtVectorType>(Y);
13783 getCommonSizeExpr(Ctx, VX, VY),
13784 getCommonAttrLoc(VX, VY));
13785 }
13786 case Type::DependentVector: {
13787 const auto *VX = cast<DependentVectorType>(X),
13788 *VY = cast<DependentVectorType>(Y);
13789 assert(VX->getVectorKind() == VY->getVectorKind());
13790 return Ctx.getDependentVectorType(
13791 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
13792 getCommonAttrLoc(VX, VY), VX->getVectorKind());
13793 }
13794 case Type::InjectedClassName: {
13795 const auto *IX = cast<InjectedClassNameType>(X),
13796 *IY = cast<InjectedClassNameType>(Y);
13797 return Ctx.getInjectedClassNameType(
13798 getCommonDeclChecked(IX->getDecl(), IY->getDecl()),
13799 Ctx.getCommonSugaredType(IX->getInjectedSpecializationType(),
13800 IY->getInjectedSpecializationType()));
13801 }
13802 case Type::TemplateSpecialization: {
13803 const auto *TX = cast<TemplateSpecializationType>(X),
13804 *TY = cast<TemplateSpecializationType>(Y);
13805 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13806 TY->template_arguments());
13808 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
13809 TY->getTemplateName(),
13810 /*IgnoreDeduced=*/true),
13811 As, X->getCanonicalTypeInternal());
13812 }
13813 case Type::Decltype: {
13814 const auto *DX = cast<DecltypeType>(X);
13815 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
13816 assert(DX->isDependentType());
13817 assert(DY->isDependentType());
13818 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
13819 // As Decltype is not uniqued, building a common type would be wasteful.
13820 return QualType(DX, 0);
13821 }
13822 case Type::PackIndexing: {
13823 const auto *DX = cast<PackIndexingType>(X);
13824 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
13825 assert(DX->isDependentType());
13826 assert(DY->isDependentType());
13827 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
13828 return QualType(DX, 0);
13829 }
13830 case Type::DependentName: {
13831 const auto *NX = cast<DependentNameType>(X),
13832 *NY = cast<DependentNameType>(Y);
13833 assert(NX->getIdentifier() == NY->getIdentifier());
13834 return Ctx.getDependentNameType(
13835 getCommonTypeKeyword(NX, NY), getCommonNNS(Ctx, NX, NY),
13836 NX->getIdentifier(), NX->getCanonicalTypeInternal());
13837 }
13838 case Type::DependentTemplateSpecialization: {
13839 const auto *TX = cast<DependentTemplateSpecializationType>(X),
13840 *TY = cast<DependentTemplateSpecializationType>(Y);
13841 assert(TX->getIdentifier() == TY->getIdentifier());
13842 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13843 TY->template_arguments());
13845 getCommonTypeKeyword(TX, TY), getCommonNNS(Ctx, TX, TY),
13846 TX->getIdentifier(), As);
13847 }
13848 case Type::UnaryTransform: {
13849 const auto *TX = cast<UnaryTransformType>(X),
13850 *TY = cast<UnaryTransformType>(Y);
13851 assert(TX->getUTTKind() == TY->getUTTKind());
13852 return Ctx.getUnaryTransformType(
13853 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
13854 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
13855 TY->getUnderlyingType()),
13856 TX->getUTTKind());
13857 }
13858 case Type::PackExpansion: {
13859 const auto *PX = cast<PackExpansionType>(X),
13860 *PY = cast<PackExpansionType>(Y);
13861 assert(PX->getNumExpansions() == PY->getNumExpansions());
13862 return Ctx.getPackExpansionType(
13863 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
13864 PX->getNumExpansions(), false);
13865 }
13866 case Type::Pipe: {
13867 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
13868 assert(PX->isReadOnly() == PY->isReadOnly());
13869 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
13871 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
13872 }
13873 case Type::TemplateTypeParm: {
13874 const auto *TX = cast<TemplateTypeParmType>(X),
13875 *TY = cast<TemplateTypeParmType>(Y);
13876 assert(TX->getDepth() == TY->getDepth());
13877 assert(TX->getIndex() == TY->getIndex());
13878 assert(TX->isParameterPack() == TY->isParameterPack());
13879 return Ctx.getTemplateTypeParmType(
13880 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
13881 getCommonDecl(TX->getDecl(), TY->getDecl()));
13882 }
13883 }
13884 llvm_unreachable("Unknown Type Class");
13885}
13886
13888 const Type *Y,
13889 SplitQualType Underlying) {
13890 Type::TypeClass TC = X->getTypeClass();
13891 if (TC != Y->getTypeClass())
13892 return QualType();
13893 switch (TC) {
13894#define UNEXPECTED_TYPE(Class, Kind) \
13895 case Type::Class: \
13896 llvm_unreachable("Unexpected " Kind ": " #Class);
13897#define TYPE(Class, Base)
13898#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
13899#include "clang/AST/TypeNodes.inc"
13900
13901#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
13904 CANONICAL_TYPE(BlockPointer)
13905 CANONICAL_TYPE(Builtin)
13907 CANONICAL_TYPE(ConstantArray)
13908 CANONICAL_TYPE(ArrayParameter)
13909 CANONICAL_TYPE(ConstantMatrix)
13911 CANONICAL_TYPE(ExtVector)
13912 CANONICAL_TYPE(FunctionNoProto)
13913 CANONICAL_TYPE(FunctionProto)
13914 CANONICAL_TYPE(IncompleteArray)
13915 CANONICAL_TYPE(HLSLAttributedResource)
13916 CANONICAL_TYPE(LValueReference)
13917 CANONICAL_TYPE(MemberPointer)
13918 CANONICAL_TYPE(ObjCInterface)
13919 CANONICAL_TYPE(ObjCObject)
13920 CANONICAL_TYPE(ObjCObjectPointer)
13924 CANONICAL_TYPE(RValueReference)
13925 CANONICAL_TYPE(VariableArray)
13927#undef CANONICAL_TYPE
13928
13929#undef UNEXPECTED_TYPE
13930
13931 case Type::Adjusted: {
13932 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
13933 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
13934 if (!Ctx.hasSameType(OX, OY))
13935 return QualType();
13936 // FIXME: It's inefficient to have to unify the original types.
13937 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
13938 Ctx.getQualifiedType(Underlying));
13939 }
13940 case Type::Decayed: {
13941 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
13942 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
13943 if (!Ctx.hasSameType(OX, OY))
13944 return QualType();
13945 // FIXME: It's inefficient to have to unify the original types.
13946 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
13947 Ctx.getQualifiedType(Underlying));
13948 }
13949 case Type::Attributed: {
13950 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
13951 AttributedType::Kind Kind = AX->getAttrKind();
13952 if (Kind != AY->getAttrKind())
13953 return QualType();
13954 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
13955 if (!Ctx.hasSameType(MX, MY))
13956 return QualType();
13957 // FIXME: It's inefficient to have to unify the modified types.
13958 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
13959 Ctx.getQualifiedType(Underlying),
13960 AX->getAttr());
13961 }
13962 case Type::BTFTagAttributed: {
13963 const auto *BX = cast<BTFTagAttributedType>(X);
13964 const BTFTypeTagAttr *AX = BX->getAttr();
13965 // The attribute is not uniqued, so just compare the tag.
13966 if (AX->getBTFTypeTag() !=
13967 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
13968 return QualType();
13969 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
13970 }
13971 case Type::Auto: {
13972 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13973
13974 AutoTypeKeyword KW = AX->getKeyword();
13975 if (KW != AY->getKeyword())
13976 return QualType();
13977
13978 ConceptDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
13979 AY->getTypeConstraintConcept());
13981 if (CD &&
13982 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
13983 AY->getTypeConstraintArguments())) {
13984 CD = nullptr; // The arguments differ, so make it unconstrained.
13985 As.clear();
13986 }
13987
13988 // Both auto types can't be dependent, otherwise they wouldn't have been
13989 // sugar. This implies they can't contain unexpanded packs either.
13990 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
13991 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
13992 }
13993 case Type::PackIndexing:
13994 case Type::Decltype:
13995 return QualType();
13996 case Type::DeducedTemplateSpecialization:
13997 // FIXME: Try to merge these.
13998 return QualType();
13999
14000 case Type::Elaborated: {
14001 const auto *EX = cast<ElaboratedType>(X), *EY = cast<ElaboratedType>(Y);
14002 return Ctx.getElaboratedType(
14003 ::getCommonTypeKeyword(EX, EY), ::getCommonNNS(Ctx, EX, EY),
14004 Ctx.getQualifiedType(Underlying),
14005 ::getCommonDecl(EX->getOwnedTagDecl(), EY->getOwnedTagDecl()));
14006 }
14007 case Type::MacroQualified: {
14008 const auto *MX = cast<MacroQualifiedType>(X),
14009 *MY = cast<MacroQualifiedType>(Y);
14010 const IdentifierInfo *IX = MX->getMacroIdentifier();
14011 if (IX != MY->getMacroIdentifier())
14012 return QualType();
14013 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14014 }
14015 case Type::SubstTemplateTypeParm: {
14016 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14017 *SY = cast<SubstTemplateTypeParmType>(Y);
14018 Decl *CD =
14019 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14020 if (!CD)
14021 return QualType();
14022 unsigned Index = SX->getIndex();
14023 if (Index != SY->getIndex())
14024 return QualType();
14025 auto PackIndex = SX->getPackIndex();
14026 if (PackIndex != SY->getPackIndex())
14027 return QualType();
14028 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14029 CD, Index, PackIndex);
14030 }
14031 case Type::ObjCTypeParam:
14032 // FIXME: Try to merge these.
14033 return QualType();
14034 case Type::Paren:
14035 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14036
14037 case Type::TemplateSpecialization: {
14038 const auto *TX = cast<TemplateSpecializationType>(X),
14039 *TY = cast<TemplateSpecializationType>(Y);
14040 TemplateName CTN =
14041 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14042 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14043 if (!CTN.getAsVoidPointer())
14044 return QualType();
14046 if (getCommonTemplateArguments(Ctx, Args, TX->template_arguments(),
14047 TY->template_arguments()))
14048 return QualType();
14049 return Ctx.getTemplateSpecializationType(CTN, Args,
14050 Ctx.getQualifiedType(Underlying));
14051 }
14052 case Type::Typedef: {
14053 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14054 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14055 if (!CD)
14056 return QualType();
14057 return Ctx.getTypedefType(CD, Ctx.getQualifiedType(Underlying));
14058 }
14059 case Type::TypeOf: {
14060 // The common sugar between two typeof expressions, where one is
14061 // potentially a typeof_unqual and the other is not, we unify to the
14062 // qualified type as that retains the most information along with the type.
14063 // We only return a typeof_unqual type when both types are unqual types.
14065 if (cast<TypeOfType>(X)->getKind() == cast<TypeOfType>(Y)->getKind() &&
14066 cast<TypeOfType>(X)->getKind() == TypeOfKind::Unqualified)
14068 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14069 }
14070 case Type::TypeOfExpr:
14071 return QualType();
14072
14073 case Type::UnaryTransform: {
14074 const auto *UX = cast<UnaryTransformType>(X),
14075 *UY = cast<UnaryTransformType>(Y);
14076 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14077 if (KX != UY->getUTTKind())
14078 return QualType();
14079 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14080 if (!Ctx.hasSameType(BX, BY))
14081 return QualType();
14082 // FIXME: It's inefficient to have to unify the base types.
14083 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14084 Ctx.getQualifiedType(Underlying), KX);
14085 }
14086 case Type::Using: {
14087 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14088 const UsingShadowDecl *CD =
14089 ::getCommonDecl(UX->getFoundDecl(), UY->getFoundDecl());
14090 if (!CD)
14091 return QualType();
14092 return Ctx.getUsingType(CD, Ctx.getQualifiedType(Underlying));
14093 }
14094 case Type::CountAttributed: {
14095 const auto *DX = cast<CountAttributedType>(X),
14096 *DY = cast<CountAttributedType>(Y);
14097 if (DX->isCountInBytes() != DY->isCountInBytes())
14098 return QualType();
14099 if (DX->isOrNull() != DY->isOrNull())
14100 return QualType();
14101 Expr *CEX = DX->getCountExpr();
14102 Expr *CEY = DY->getCountExpr();
14103 llvm::ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14104 if (Ctx.hasSameExpr(CEX, CEY))
14105 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14106 DX->isCountInBytes(), DX->isOrNull(),
14107 CDX);
14108 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14109 return QualType();
14110 // Two declarations with the same integer constant may still differ in their
14111 // expression pointers, so we need to evaluate them.
14112 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14113 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14114 if (VX != VY)
14115 return QualType();
14116 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14117 DX->isCountInBytes(), DX->isOrNull(),
14118 CDX);
14119 }
14120 }
14121 llvm_unreachable("Unhandled Type Class");
14122}
14123
14124static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14126 while (true) {
14127 QTotal.addConsistentQualifiers(T.Quals);
14129 if (NT == QualType(T.Ty, 0))
14130 break;
14131 R.push_back(T);
14132 T = NT.split();
14133 }
14134 return R;
14135}
14136
14138 bool Unqualified) {
14139 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14140 if (X == Y)
14141 return X;
14142 if (!Unqualified) {
14143 if (X.isCanonical())
14144 return X;
14145 if (Y.isCanonical())
14146 return Y;
14147 }
14148
14149 SplitQualType SX = X.split(), SY = Y.split();
14150 Qualifiers QX, QY;
14151 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14152 // until we reach their underlying "canonical nodes". Note these are not
14153 // necessarily canonical types, as they may still have sugared properties.
14154 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14155 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14156 if (SX.Ty != SY.Ty) {
14157 // The canonical nodes differ. Build a common canonical node out of the two,
14158 // unifying their sugar. This may recurse back here.
14159 SX.Ty =
14160 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14161 } else {
14162 // The canonical nodes were identical: We may have desugared too much.
14163 // Add any common sugar back in.
14164 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14165 QX -= SX.Quals;
14166 QY -= SY.Quals;
14167 SX = Xs.pop_back_val();
14168 SY = Ys.pop_back_val();
14169 }
14170 }
14171 if (Unqualified)
14173 else
14174 assert(QX == QY);
14175
14176 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14177 // related. Walk up these nodes, unifying them and adding the result.
14178 while (!Xs.empty() && !Ys.empty()) {
14179 auto Underlying = SplitQualType(
14180 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14181 SX = Xs.pop_back_val();
14182 SY = Ys.pop_back_val();
14183 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14185 // Stop at the first pair which is unrelated.
14186 if (!SX.Ty) {
14187 SX.Ty = Underlying.Ty;
14188 break;
14189 }
14190 QX -= Underlying.Quals;
14191 };
14192
14193 // Add back the missing accumulated qualifiers, which were stripped off
14194 // with the sugar nodes we could not unify.
14195 QualType R = getQualifiedType(SX.Ty, QX);
14196 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14197 return R;
14198}
14199
14201 assert(Ty->isFixedPointType());
14202
14204 return Ty;
14205
14206 switch (Ty->castAs<BuiltinType>()->getKind()) {
14207 default:
14208 llvm_unreachable("Not a saturated fixed point type!");
14209 case BuiltinType::SatShortAccum:
14210 return ShortAccumTy;
14211 case BuiltinType::SatAccum:
14212 return AccumTy;
14213 case BuiltinType::SatLongAccum:
14214 return LongAccumTy;
14215 case BuiltinType::SatUShortAccum:
14216 return UnsignedShortAccumTy;
14217 case BuiltinType::SatUAccum:
14218 return UnsignedAccumTy;
14219 case BuiltinType::SatULongAccum:
14220 return UnsignedLongAccumTy;
14221 case BuiltinType::SatShortFract:
14222 return ShortFractTy;
14223 case BuiltinType::SatFract:
14224 return FractTy;
14225 case BuiltinType::SatLongFract:
14226 return LongFractTy;
14227 case BuiltinType::SatUShortFract:
14228 return UnsignedShortFractTy;
14229 case BuiltinType::SatUFract:
14230 return UnsignedFractTy;
14231 case BuiltinType::SatULongFract:
14232 return UnsignedLongFractTy;
14233 }
14234}
14235
14237 assert(Ty->isFixedPointType());
14238
14239 if (Ty->isSaturatedFixedPointType()) return Ty;
14240
14241 switch (Ty->castAs<BuiltinType>()->getKind()) {
14242 default:
14243 llvm_unreachable("Not a fixed point type!");
14244 case BuiltinType::ShortAccum:
14245 return SatShortAccumTy;
14246 case BuiltinType::Accum:
14247 return SatAccumTy;
14248 case BuiltinType::LongAccum:
14249 return SatLongAccumTy;
14250 case BuiltinType::UShortAccum:
14252 case BuiltinType::UAccum:
14253 return SatUnsignedAccumTy;
14254 case BuiltinType::ULongAccum:
14256 case BuiltinType::ShortFract:
14257 return SatShortFractTy;
14258 case BuiltinType::Fract:
14259 return SatFractTy;
14260 case BuiltinType::LongFract:
14261 return SatLongFractTy;
14262 case BuiltinType::UShortFract:
14264 case BuiltinType::UFract:
14265 return SatUnsignedFractTy;
14266 case BuiltinType::ULongFract:
14268 }
14269}
14270
14272 if (LangOpts.OpenCL)
14274
14275 if (LangOpts.CUDA)
14277
14278 return getLangASFromTargetAS(AS);
14279}
14280
14281// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
14282// doesn't include ASTContext.h
14283template
14285 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
14287 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
14288 const clang::ASTContext &Ctx, Decl *Value);
14289
14291 assert(Ty->isFixedPointType());
14292
14293 const TargetInfo &Target = getTargetInfo();
14294 switch (Ty->castAs<BuiltinType>()->getKind()) {
14295 default:
14296 llvm_unreachable("Not a fixed point type!");
14297 case BuiltinType::ShortAccum:
14298 case BuiltinType::SatShortAccum:
14299 return Target.getShortAccumScale();
14300 case BuiltinType::Accum:
14301 case BuiltinType::SatAccum:
14302 return Target.getAccumScale();
14303 case BuiltinType::LongAccum:
14304 case BuiltinType::SatLongAccum:
14305 return Target.getLongAccumScale();
14306 case BuiltinType::UShortAccum:
14307 case BuiltinType::SatUShortAccum:
14308 return Target.getUnsignedShortAccumScale();
14309 case BuiltinType::UAccum:
14310 case BuiltinType::SatUAccum:
14311 return Target.getUnsignedAccumScale();
14312 case BuiltinType::ULongAccum:
14313 case BuiltinType::SatULongAccum:
14314 return Target.getUnsignedLongAccumScale();
14315 case BuiltinType::ShortFract:
14316 case BuiltinType::SatShortFract:
14317 return Target.getShortFractScale();
14318 case BuiltinType::Fract:
14319 case BuiltinType::SatFract:
14320 return Target.getFractScale();
14321 case BuiltinType::LongFract:
14322 case BuiltinType::SatLongFract:
14323 return Target.getLongFractScale();
14324 case BuiltinType::UShortFract:
14325 case BuiltinType::SatUShortFract:
14326 return Target.getUnsignedShortFractScale();
14327 case BuiltinType::UFract:
14328 case BuiltinType::SatUFract:
14329 return Target.getUnsignedFractScale();
14330 case BuiltinType::ULongFract:
14331 case BuiltinType::SatULongFract:
14332 return Target.getUnsignedLongFractScale();
14333 }
14334}
14335
14337 assert(Ty->isFixedPointType());
14338
14339 const TargetInfo &Target = getTargetInfo();
14340 switch (Ty->castAs<BuiltinType>()->getKind()) {
14341 default:
14342 llvm_unreachable("Not a fixed point type!");
14343 case BuiltinType::ShortAccum:
14344 case BuiltinType::SatShortAccum:
14345 return Target.getShortAccumIBits();
14346 case BuiltinType::Accum:
14347 case BuiltinType::SatAccum:
14348 return Target.getAccumIBits();
14349 case BuiltinType::LongAccum:
14350 case BuiltinType::SatLongAccum:
14351 return Target.getLongAccumIBits();
14352 case BuiltinType::UShortAccum:
14353 case BuiltinType::SatUShortAccum:
14354 return Target.getUnsignedShortAccumIBits();
14355 case BuiltinType::UAccum:
14356 case BuiltinType::SatUAccum:
14357 return Target.getUnsignedAccumIBits();
14358 case BuiltinType::ULongAccum:
14359 case BuiltinType::SatULongAccum:
14360 return Target.getUnsignedLongAccumIBits();
14361 case BuiltinType::ShortFract:
14362 case BuiltinType::SatShortFract:
14363 case BuiltinType::Fract:
14364 case BuiltinType::SatFract:
14365 case BuiltinType::LongFract:
14366 case BuiltinType::SatLongFract:
14367 case BuiltinType::UShortFract:
14368 case BuiltinType::SatUShortFract:
14369 case BuiltinType::UFract:
14370 case BuiltinType::SatUFract:
14371 case BuiltinType::ULongFract:
14372 case BuiltinType::SatULongFract:
14373 return 0;
14374 }
14375}
14376
14377llvm::FixedPointSemantics
14379 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
14380 "Can only get the fixed point semantics for a "
14381 "fixed point or integer type.");
14382 if (Ty->isIntegerType())
14383 return llvm::FixedPointSemantics::GetIntegerSemantics(
14384 getIntWidth(Ty), Ty->isSignedIntegerType());
14385
14386 bool isSigned = Ty->isSignedFixedPointType();
14387 return llvm::FixedPointSemantics(
14388 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
14390 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
14391}
14392
14393llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
14394 assert(Ty->isFixedPointType());
14395 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
14396}
14397
14398llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
14399 assert(Ty->isFixedPointType());
14400 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
14401}
14402
14404 assert(Ty->isUnsignedFixedPointType() &&
14405 "Expected unsigned fixed point type");
14406
14407 switch (Ty->castAs<BuiltinType>()->getKind()) {
14408 case BuiltinType::UShortAccum:
14409 return ShortAccumTy;
14410 case BuiltinType::UAccum:
14411 return AccumTy;
14412 case BuiltinType::ULongAccum:
14413 return LongAccumTy;
14414 case BuiltinType::SatUShortAccum:
14415 return SatShortAccumTy;
14416 case BuiltinType::SatUAccum:
14417 return SatAccumTy;
14418 case BuiltinType::SatULongAccum:
14419 return SatLongAccumTy;
14420 case BuiltinType::UShortFract:
14421 return ShortFractTy;
14422 case BuiltinType::UFract:
14423 return FractTy;
14424 case BuiltinType::ULongFract:
14425 return LongFractTy;
14426 case BuiltinType::SatUShortFract:
14427 return SatShortFractTy;
14428 case BuiltinType::SatUFract:
14429 return SatFractTy;
14430 case BuiltinType::SatULongFract:
14431 return SatLongFractTy;
14432 default:
14433 llvm_unreachable("Unexpected unsigned fixed point type");
14434 }
14435}
14436
14437// Given a list of FMV features, return a concatenated list of the
14438// corresponding backend features (which may contain duplicates).
14439static std::vector<std::string> getFMVBackendFeaturesFor(
14440 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
14441 std::vector<std::string> BackendFeats;
14442 llvm::AArch64::ExtensionSet FeatureBits;
14443 for (StringRef F : FMVFeatStrings)
14444 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
14445 if (FMVExt->ID)
14446 FeatureBits.enable(*FMVExt->ID);
14447 FeatureBits.toLLVMFeatureList(BackendFeats);
14448 return BackendFeats;
14449}
14450
14452ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
14453 assert(TD != nullptr);
14454 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
14455
14456 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
14457 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
14458 });
14459 return ParsedAttr;
14460}
14461
14462void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14463 const FunctionDecl *FD) const {
14464 if (FD)
14465 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
14466 else
14467 Target->initFeatureMap(FeatureMap, getDiagnostics(),
14468 Target->getTargetOpts().CPU,
14469 Target->getTargetOpts().Features);
14470}
14471
14472// Fills in the supplied string map with the set of target features for the
14473// passed in function.
14474void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14475 GlobalDecl GD) const {
14476 StringRef TargetCPU = Target->getTargetOpts().CPU;
14477 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
14478 if (const auto *TD = FD->getAttr<TargetAttr>()) {
14480
14481 // Make a copy of the features as passed on the command line into the
14482 // beginning of the additional features from the function to override.
14483 // AArch64 handles command line option features in parseTargetAttr().
14484 if (!Target->getTriple().isAArch64())
14485 ParsedAttr.Features.insert(
14486 ParsedAttr.Features.begin(),
14487 Target->getTargetOpts().FeaturesAsWritten.begin(),
14488 Target->getTargetOpts().FeaturesAsWritten.end());
14489
14490 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
14491 TargetCPU = ParsedAttr.CPU;
14492
14493 // Now populate the feature map, first with the TargetCPU which is either
14494 // the default or a new one from the target attribute string. Then we'll use
14495 // the passed in features (FeaturesAsWritten) along with the new ones from
14496 // the attribute.
14497 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
14498 ParsedAttr.Features);
14499 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
14501 Target->getCPUSpecificCPUDispatchFeatures(
14502 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
14503 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
14504 Features.insert(Features.begin(),
14505 Target->getTargetOpts().FeaturesAsWritten.begin(),
14506 Target->getTargetOpts().FeaturesAsWritten.end());
14507 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14508 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
14509 if (Target->getTriple().isAArch64()) {
14511 TC->getFeatures(Feats, GD.getMultiVersionIndex());
14512 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
14513 Features.insert(Features.begin(),
14514 Target->getTargetOpts().FeaturesAsWritten.begin(),
14515 Target->getTargetOpts().FeaturesAsWritten.end());
14516 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14517 } else if (Target->getTriple().isRISCV()) {
14518 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14519 std::vector<std::string> Features;
14520 if (VersionStr != "default") {
14521 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
14522 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14523 ParsedAttr.Features.end());
14524 }
14525 Features.insert(Features.begin(),
14526 Target->getTargetOpts().FeaturesAsWritten.begin(),
14527 Target->getTargetOpts().FeaturesAsWritten.end());
14528 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14529 } else {
14530 std::vector<std::string> Features;
14531 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14532 if (VersionStr.starts_with("arch="))
14533 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
14534 else if (VersionStr != "default")
14535 Features.push_back((StringRef{"+"} + VersionStr).str());
14536 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14537 }
14538 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
14539 std::vector<std::string> Features;
14540 if (Target->getTriple().isRISCV()) {
14541 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
14542 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14543 ParsedAttr.Features.end());
14544 } else {
14545 assert(Target->getTriple().isAArch64());
14547 TV->getFeatures(Feats);
14548 Features = getFMVBackendFeaturesFor(Feats);
14549 }
14550 Features.insert(Features.begin(),
14551 Target->getTargetOpts().FeaturesAsWritten.begin(),
14552 Target->getTargetOpts().FeaturesAsWritten.end());
14553 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14554 } else {
14555 FeatureMap = Target->getTargetOpts().FeatureMap;
14556 }
14557}
14558
14560 const FunctionDecl *FD) {
14561 return {KernelNameType, FD};
14562}
14563
14565 // If the function declaration to register is invalid or dependent, the
14566 // registration attempt is ignored.
14567 if (FD->isInvalidDecl() || FD->isTemplated())
14568 return;
14569
14570 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
14571 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
14572
14573 // Be tolerant of multiple registration attempts so long as each attempt
14574 // is for the same entity. Callers are obligated to detect and diagnose
14575 // conflicting kernel names prior to calling this function.
14576 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
14577 auto IT = SYCLKernels.find(KernelNameType);
14578 assert((IT == SYCLKernels.end() ||
14579 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
14580 "SYCL kernel name conflict");
14581 (void)IT;
14582 SYCLKernels.insert(
14583 std::make_pair(KernelNameType, BuildSYCLKernelInfo(KernelNameType, FD)));
14584}
14585
14587 CanQualType KernelNameType = getCanonicalType(T);
14588 return SYCLKernels.at(KernelNameType);
14589}
14590
14592 CanQualType KernelNameType = getCanonicalType(T);
14593 auto IT = SYCLKernels.find(KernelNameType);
14594 if (IT != SYCLKernels.end())
14595 return &IT->second;
14596 return nullptr;
14597}
14598
14600 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
14601 return *OMPTraitInfoVector.back();
14602}
14603
14606 const ASTContext::SectionInfo &Section) {
14607 if (Section.Decl)
14608 return DB << Section.Decl;
14609 return DB << "a prior #pragma section";
14610}
14611
14613 bool IsInternalVar =
14614 isa<VarDecl>(D) &&
14615 basicGVALinkageForVariable(*this, cast<VarDecl>(D)) == GVA_Internal;
14616 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
14617 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
14618 (D->hasAttr<CUDAConstantAttr>() &&
14619 !D->getAttr<CUDAConstantAttr>()->isImplicit());
14620 // CUDA/HIP: managed variables need to be externalized since it is
14621 // a declaration in IR, therefore cannot have internal linkage. Kernels in
14622 // anonymous name space needs to be externalized to avoid duplicate symbols.
14623 return (IsInternalVar &&
14624 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
14625 (D->hasAttr<CUDAGlobalAttr>() &&
14626 basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) ==
14627 GVA_Internal);
14628}
14629
14631 return mayExternalize(D) &&
14632 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
14633 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
14634}
14635
14636StringRef ASTContext::getCUIDHash() const {
14637 if (!CUIDHash.empty())
14638 return CUIDHash;
14639 if (LangOpts.CUID.empty())
14640 return StringRef();
14641 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
14642 return CUIDHash;
14643}
14644
14645const CXXRecordDecl *
14647 assert(ThisClass);
14648 assert(ThisClass->isPolymorphic());
14649 const CXXRecordDecl *PrimaryBase = ThisClass;
14650 while (1) {
14651 assert(PrimaryBase);
14652 assert(PrimaryBase->isPolymorphic());
14653 auto &Layout = getASTRecordLayout(PrimaryBase);
14654 auto Base = Layout.getPrimaryBase();
14655 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
14656 break;
14657 PrimaryBase = Base;
14658 }
14659 return PrimaryBase;
14660}
14661
14663 StringRef MangledName) {
14664 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
14665 assert(Method->isVirtual());
14666 bool DefaultIncludesPointerAuth =
14667 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
14668
14669 if (!DefaultIncludesPointerAuth)
14670 return true;
14671
14672 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
14673 if (Existing != ThunksToBeAbbreviated.end())
14674 return Existing->second.contains(MangledName.str());
14675
14676 std::unique_ptr<MangleContext> Mangler(createMangleContext());
14677 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
14678 auto VtableContext = getVTableContext();
14679 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
14680 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
14681 for (const auto &Thunk : *ThunkInfos) {
14682 SmallString<256> ElidedName;
14683 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
14684 if (Destructor)
14685 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
14686 Thunk, /* elideOverrideInfo */ true,
14687 ElidedNameStream);
14688 else
14689 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
14690 ElidedNameStream);
14691 SmallString<256> MangledName;
14692 llvm::raw_svector_ostream mangledNameStream(MangledName);
14693 if (Destructor)
14694 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
14695 Thunk, /* elideOverrideInfo */ false,
14696 mangledNameStream);
14697 else
14698 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
14699 mangledNameStream);
14700
14701 Thunks[ElidedName].push_back(std::string(MangledName));
14702 }
14703 }
14704 llvm::StringSet<> SimplifiedThunkNames;
14705 for (auto &ThunkList : Thunks) {
14706 llvm::sort(ThunkList.second);
14707 SimplifiedThunkNames.insert(ThunkList.second[0]);
14708 }
14709 bool Result = SimplifiedThunkNames.contains(MangledName);
14710 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
14711 return Result;
14712}
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 getCommonTypes(ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=false)
static auto getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool NeedsInjectedClassNameType(const RecordDecl *D)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static NamespaceDecl * getNamespace(const NestedNameSpecifier *X)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static NestedNameSpecifier * getCommonNNS(ASTContext &Ctx, const T *X, const T *Y)
static Decl * getCommonDecl(Decl *X, Decl *Y)
static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L)
static bool isTypeTypedefedAsBOOL(QualType T)
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
static const TemplateArgument * getDefaultTemplateArgumentOrNone(const NamedDecl *P)
static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty)
getSVETypeSize - Return SVE vector or predicate register size.
#define SUGAR_FREE_TYPE(Class)
static bool getCommonTemplateArguments(ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
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 const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
Definition: ASTContext.cpp:355
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *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 TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static TypedefDecl * CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context)
static TemplateName getCommonTemplateNameChecked(ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced)
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)
Definition: ASTContext.cpp:900
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
Definition: ASTContext.cpp:104
@ FloatRank
Definition: ASTContext.cpp:108
@ LongDoubleRank
Definition: ASTContext.cpp:110
@ Float16Rank
Definition: ASTContext.cpp:106
@ Ibm128Rank
Definition: ASTContext.cpp:112
@ Float128Rank
Definition: ASTContext.cpp:111
@ BFloat16Rank
Definition: ASTContext.cpp:105
@ HalfRank
Definition: ASTContext.cpp:107
@ DoubleRank
Definition: ASTContext.cpp:109
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
static void mergeTypeLists(ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > Y)
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 TypedefDecl * CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context)
static TemplateArgument getCommonTemplateArgument(ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &Y)
static auto * getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y)
static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx, raw_ostream &OS, QualType QT)
Encode a function type for use in the discriminator of a function pointer type.
static std::optional< int64_t > structSubobjectsHaveUniqueObjectRepresentations(const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext &Context, const clang::ASTRecordLayout &Layout, bool CheckIfTriviallyCopyable)
static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET)
static QualType getCommonArrayElementType(ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y)
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static SYCLKernelInfo BuildSYCLKernelInfo(CanQualType KernelNameType, const FunctionDecl *FD)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static QualType getCommonNonSugarTypeNode(ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
static QualType getCommonSugarTypeNode(ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static bool isSameQualifier(const NestedNameSpecifier *X, const NestedNameSpecifier *Y)
static std::string charUnitsToString(const CharUnits &CU)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
Definition: ASTContext.cpp:513
static SmallVector< SourceLocation, 2 > getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr)
Definition: ASTContext.cpp:139
static TemplateName getCommonTemplateName(ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced=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)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static std::vector< std::string > getFMVBackendFeaturesFor(const llvm::SmallVectorImpl< StringRef > &FMVFeatStrings)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y)
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3460
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
Provides definitions for the various language-specific address spaces.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
#define SM(sm)
Definition: Cuda.cpp:84
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
Defines enum values for all the target-independent builtin functions.
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition: CFG.cpp:2686
const Decl * D
IndirectLocalPath & Path
Expr * E
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1180
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.
StringRef Text
Definition: Format.cpp:3054
unsigned Iter
Definition: HTMLLogger.cpp:153
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition: Value.h:144
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
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.
Defines types useful for describing an Objective-C runtime.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
uint32_t Id
Definition: SemaARM.cpp:1134
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
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.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
SourceLocation Begin
__device__ __2f16 float c
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isMemberPointerToDerivedMember() const
Definition: APValue.cpp:1063
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1056
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition: APValue.cpp:1070
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
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.
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
CanQualType AccumTy
Definition: ASTContext.h:1173
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
Definition: ASTContext.h:1192
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2922
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.
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition: ASTContext.h:508
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
Definition: ASTContext.cpp:894
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
MemberSpecializationInfo * getInstantiatedFromStaticDataMember(const VarDecl *Var)
If this variable is an instantiated static data member of a class template specialization,...
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1191
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped) const
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
Definition: ASTContext.h:896
BuiltinTemplateDecl * getBuiltinCommonTypeDecl() const
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
Definition: ASTContext.h:1169
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
Definition: ASTContext.h:1165
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
Definition: ASTContext.h:1169
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1182
BuiltinTemplateDecl * getMakeIntegerSeqDecl() const
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
ExternCContextDecl * getExternCContextDecl() const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const
Parses the target attributes passed in, and returns only the ones that are valid feature names.
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, ConceptDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
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
Definition: ASTContext.h:1175
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef< TemplateArgumentLoc > Args) const
QualType adjustFunctionResultType(QualType FunctionType, QualType NewResultType)
Change the result type of a function type, preserving sugar such as attributed types.
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
bool 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 getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, ObjCTypeParamDecl *New) const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:2258
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:684
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
Definition: ASTContext.cpp:592
QualType getUnresolvedUsingType(const UnresolvedUsingTypenameDecl *Decl) const
CharUnits getObjCEncodingTypeSize(QualType T) const
Return the size of type T for Objective-C encoding purpose, in characters.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
void setCurrentNamedModule(Module *M)
Set the (C++20) module we are building.
QualType getProcessIDType() const
Return the unique type for "pid_t" defined in <sys/types.h>.
CharUnits getMemberPointerPathAdjustment(const APValue &MP) const
Find the 'this' offset for the member path in a pointer-to-member APValue.
bool mayExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel may be externalized.
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
Definition: ASTContext.h:1178
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
QualType getucontext_tType() const
Retrieve the C ucontext_t type.
Definition: ASTContext.h:2132
QualType getRecordType(const RecordDecl *Decl) const
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
bool hasSameExpr(const Expr *X, const Expr *Y) const
Determine whether the given expressions X and Y are equivalent.
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
QualType getRealTypeForBitwidth(unsigned DestWidth, FloatModeKind ExplicitType) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
Definition: ASTContext.h:1173
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1289
IdentifierInfo * getBuiltinCommonTypeName() const
Definition: ASTContext.h:2076
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3410
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,...
Definition: ASTContext.h:2528
unsigned char getFixedPointIBits(QualType Ty) const
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
Definition: ASTContext.h:1172
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
QualType getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, bool OrNull, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2723
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3424
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS)
ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and Class<pr1, ...>.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2739
bool propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
Definition: ASTContext.h:1172
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
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
Definition: ASTContext.h:1178
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.
QualType getFILEType() const
Retrieve the C FILE type.
Definition: ASTContext.h:2096
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.
Definition: ASTContext.h:2580
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
Definition: ASTContext.h:1172
CanQualType OMPArrayShapingTy
Definition: ASTContext.h:1201
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
Definition: ASTContext.cpp:913
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
Definition: ASTContext.h:1167
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)
Definition: ASTContext.cpp:346
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...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex, SubstTemplateTypeParmTypeFlag Flag=SubstTemplateTypeParmTypeFlag::None) const
Retrieve a substitution-result type.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
Definition: ASTContext.h:2280
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...
const ASTRecordLayout & getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const
Get or compute information about the layout of the specified Objective-C implementation.
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1177
QualType getEnumType(const EnumDecl *Decl) const
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
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
Definition: ASTContext.h:1187
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
Definition: ASTContext.h:1188
IdentifierInfo * getMakeIntegerSeqName() const
Definition: ASTContext.h:2064
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
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...
IdentifierInfo * getTypePackElementName() const
Definition: ASTContext.h:2070
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
Definition: ASTContext.h:1187
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
CanQualType WideCharTy
Definition: ASTContext.h:1164
CanQualType OMPIteratorTy
Definition: ASTContext.h:1201
IdentifierTable & Idents
Definition: ASTContext.h:680
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex) const
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:682
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
Definition: ASTContext.h:1063
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...
Definition: ASTContext.cpp:854
unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const
Return the minimum alignement as specified by the target.
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:867
bool isSameDefaultTemplateArgument(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two default template arguments are similar enough that they may be used in declarat...
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl * > protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CanQualType SatShortFractTy
Definition: ASTContext.h:1181
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
bool canBindObjCObjectType(QualType To, QualType From)
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...
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
Definition: ASTContext.h:1172
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
Definition: ASTContext.h:1179
bool useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl, StringRef MangledName)
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
QualType getSignatureParameterType(QualType T) const
Retrieve the parameter type as adjusted for use in the signature of a function, decaying array and fu...
CanQualType ArraySectionTy
Definition: ASTContext.h:1200
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args) const
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1192
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
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
QualType AutoDeductTy
Definition: ASTContext.h:1223
CanQualType BoolTy
Definition: ASTContext.h:1161
void cacheRawCommentForDecl(const Decl &OriginalD, const RawComment &Comment) const
Attaches Comment to OriginalD and to its redeclaration chain and removes the redeclaration chain from...
Definition: ASTContext.cpp:504
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
Definition: ASTContext.cpp:530
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
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2213
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
CanQualType UnsignedFractTy
Definition: ASTContext.h:1177
QualType getjmp_bufType() const
Retrieve the C jmp_buf type.
Definition: ASTContext.h:2108
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
QualType getsigjmp_bufType() const
Retrieve the C sigjmp_buf type.
Definition: ASTContext.h:2120
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
CanQualType Float128Ty
Definition: ASTContext.h:1172
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1192
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3389
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1188
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
CanQualType UnsignedLongTy
Definition: ASTContext.h:1170
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...
CanQualType UnsignedLongAccumTy
Definition: ASTContext.h:1175
QualType AutoRRefDeductTy
Definition: ASTContext.h:1224
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
Definition: ASTContext.h:1176
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
TypeSourceInfo * getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &Args, QualType Canon=QualType()) const
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
Retrieve a.
CanQualType BoundMemberTy
Definition: ASTContext.h:1188
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1182
CanQualType CharTy
Definition: ASTContext.h:1162
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
Definition: ASTContext.h:870
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:3403
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3396
CanQualType IntTy
Definition: ASTContext.h:1169
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
Definition: ASTContext.h:1237
CanQualType PseudoObjectTy
Definition: ASTContext.h:1191
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
Definition: ASTContext.cpp:980
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.
void PrintStats() const
Definition: ASTContext.cpp:994
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:607
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:3420
CanQualType Float16Ty
Definition: ASTContext.h:1186
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2296
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
Definition: ASTContext.h:1231
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
Definition: ASTContext.h:1169
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition: ASTContext.h:686
QualType getPackExpansionType(QualType Pattern, std::optional< unsigned > NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1193
TypeInfoChars getTypeInfoInChars(const Type *T) const
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
TemplateParamObjectDecl * getTemplateParamObjectDecl(QualType T, const APValue &V) const
Return the template parameter object of the given type with the given value.
CanQualType OverloadTy
Definition: ASTContext.h:1188
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.
CanQualType OCLClkEventTy
Definition: ASTContext.h:1197
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:733
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCImplementationDecl *ID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
CanQualType SatUnsignedShortAccumTy
Definition: ASTContext.h:1179
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
const RawComment * getRawCommentForAnyRedecl(const Decl *D, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration.
Definition: ASTContext.cpp:422
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.
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2469
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2203
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
QualType getFunctionTypeWithoutParamABIs(QualType T) const
Get or construct a function type that is equivalent to the input type except that the parameter ABI a...
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2770
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:612
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent)
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.
Definition: ASTContext.h:1250
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.
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass)
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2489
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1171
CanQualType BuiltinFnTy
Definition: ASTContext.h:1190
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:3385
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
Definition: ASTContext.h:3417
void setManglingNumber(const NamedDecl *ND, unsigned Number)
llvm::DenseMap< const Decl *, const RawComment * > DeclRawComments
Mapping from declaration to directly attached comment.
Definition: ASTContext.h:876
CanQualType OCLSamplerTy
Definition: ASTContext.h:1197
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1160
CanQualType UnsignedCharTy
Definition: ASTContext.h:1170
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1177
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:754
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template apply.
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:3399
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl * > protocols) const
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1381
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string &S, bool Extended) const
getObjCEncodingForMethodParameter - Return the encoded type for a single method parameter or return t...
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
unsigned overridden_methods_size(const CXXMethodDecl *Method) const
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const
Return the encoded type for this block declaration.
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
Definition: ASTContext.h:1189
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
Definition: ASTContext.h:1171
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false)
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1198
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
Definition: ASTContext.h:1170
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 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.
Definition: ASTContext.h:1681
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
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
Definition: ASTContext.h:1183
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, int Index=-1) const
RawComment * getRawCommentForDeclNoCache(const Decl *D) const
Return the documentation comment attached to a given declaration, without looking into cache.
Definition: ASTContext.cpp:313
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2925
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.
Definition: ASTContext.cpp:990
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
Definition: ASTContext.h:1169
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
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 areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Definition: ASTContext.h:1176
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)
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
void ResetObjCLayout(const ObjCContainerDecl *CD)
CanQualType LongAccumTy
Definition: ASTContext.h:1174
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
Definition: ASTContext.cpp:887
CanQualType Char32Ty
Definition: ASTContext.h:1168
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
Definition: ASTContext.h:1181
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
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
Definition: ASTContext.h:1181
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
Definition: ASTContext.h:1198
CanQualType LongFractTy
Definition: ASTContext.h:1176
CanQualType SatShortAccumTy
Definition: ASTContext.h:1178
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
Definition: ASTContext.h:1185
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:3392
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1199
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
QualType getCorrespondingUnsignedType(QualType T) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, bool Final) const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
Definition: ASTContext.cpp:861
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 ...
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1274
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
BuiltinTemplateDecl * getTypePackElementDecl() const
CanQualType SatUnsignedLongAccumTy
Definition: ASTContext.h:1180
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
Definition: ASTContext.h:1169
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
QualType getCorrespondingSignedType(QualType T) const
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
llvm::DenseMap< const Decl *, const Decl * > CommentlessRedeclChains
Keeps track of redeclaration chains that don't have any comment attached.
Definition: ASTContext.h:892
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
void deduplicateMergedDefinitonsFor(NamedDecl *ND)
Clean up the merged definition list.
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1927
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...
void addTranslationUnitDecl()
Definition: ASTContext.h:1144
CanQualType WCharTy
Definition: ASTContext.h:1163
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.
Definition: ASTContext.h:3406
void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet< ObjCProtocolDecl *, 8 > &Protocols)
CollectInheritedProtocols - Collect all protocols in current class and those inherited by it.
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
llvm::DenseMap< const Decl *, const Decl * > RedeclChainComments
Mapping from canonical declaration to the first redeclaration in chain that has a comment attached.
Definition: ASTContext.h:883
CanQualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
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.
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
uint16_t getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD)
Return the "other" discriminator used for the pointer auth schema used for vtable pointers in instanc...
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const
Loading virtual member pointers using the virtual inheritance model always results in an adjustment u...
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
unsigned char getFixedPointScale(QualType Ty) const
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
Definition: ASTContext.h:2391
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2397
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2394
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2403
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2400
QualType adjustStringLiteralBaseType(QualType StrLTy) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
CanQualType Char8Ty
Definition: ASTContext.h:1166
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
Definition: ASTContext.h:1184
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1175
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
bool isInSameModule(const Module *M1, const Module *M2)
If the two module M1 and M2 are in the same module.
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...
CanQualType OCLEventTy
Definition: ASTContext.h:1197
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
Definition: ASTContext.cpp:985
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
Definition: ASTContext.h:1053
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
Definition: ASTContext.cpp:235
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2520
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
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2493
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.
Definition: ASTContext.h:3413
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
virtual void AddedStaticLocalNumbers(const Decl *D, unsigned Number)
An static local number was added to a Decl.
virtual void RedefinedHiddenDefinition(const NamedDecl *D, Module *M)
A definition has been made visible by being redefined locally.
virtual void AddedManglingNumber(const Decl *D, unsigned Number)
An mangling number was added to a Decl.
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/...
Definition: RecordLayout.h:38
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
Definition: RecordLayout.h:182
const CXXRecordDecl * getBaseSharingVBPtr() const
Definition: RecordLayout.h:329
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:193
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
Definition: RecordLayout.h:206
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:259
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
Definition: RecordLayout.h:210
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustement.
Definition: RecordLayout.h:190
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:3357
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3376
Represents a loop initializing the elements of an array.
Definition: Expr.h:5752
llvm::APInt getArraySize() const
Definition: Expr.h:5774
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition: Expr.h:5772
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition: Type.h:3747
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3591
Qualifiers getIndexTypeQualifiers() const
Definition: Type.h:3595
QualType getElementType() const
Definition: Type.h:3589
unsigned getIndexTypeCVRQualifiers() const
Definition: Type.h:3599
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:6678
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7766
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7771
Attr - This represents one attribute.
Definition: Attr.h:43
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:6132
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6204
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6561
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.cpp:5204
bool isConstrained() const
Definition: Type.h:6580
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6241
A fixed int type of a specified bitwidth.
Definition: Type.h:7819
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:7836
unsigned getNumBits() const
Definition: Type.h:7831
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4496
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6414
Pointer to a block type.
Definition: Type.h:3408
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3425
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: Type.h:3034
Kind getKind() const
Definition: Type.h:3082
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:3328
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:85
const char * getTypeString(unsigned ID) const
Get the type descriptor string for the specified builtin.
Definition: Builtins.h:109
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:197
bool canBeRedeclared(unsigned ID) const
Returns true if this is a builtin that can be redeclared.
Definition: Builtins.cpp:246
bool isNoReturn(unsigned ID) const
Return true if we know this builtin never returns.
Definition: Builtins.h:133
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:128
Implements C++ ABI-specific semantic analysis functions.
Definition: CXXABI.h:29
virtual ~CXXABI()
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2174
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1226
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:132
bool isDynamicClass() const
Definition: DeclCXX.h:586
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1198
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
bool isNull() const
Definition: CanonicalType.h:98
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:84
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition: CharUnits.h:128
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Declaration of a class template.
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3145
QualType getElementType() const
Definition: Type.h:3155
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3160
Declaration of a C++20 concept.
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
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: Type.h:3615
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition: Type.h:3711
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3671
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.h:3730
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3691
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4232
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4253
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4270
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4250
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: Type.h:4261
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition: Type.h:3306
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3342
Represents a pointer type decayed from an array or function type.
Definition: Type.h:3391
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1439
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2104
bool isFileContext() const
Definition: DeclBase.h:2175
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1342
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2120
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1862
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:2006
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1776
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1054
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:322
T * getAttr() const
Definition: DeclBase.h:576
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:528
void addAttr(Attr *A)
Definition: DeclBase.cpp:1018
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:542
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:1046
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:289
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition: DeclBase.h:977
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:254
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition: DeclBase.h:198
@ OBJC_TQ_Byref
Definition: DeclBase.h:204
@ OBJC_TQ_Oneway
Definition: DeclBase.h:205
@ OBJC_TQ_Bycopy
Definition: DeclBase.h:203
@ OBJC_TQ_None
Definition: DeclBase.h:199
@ OBJC_TQ_Inout
Definition: DeclBase.h:201
bool isInvalidDecl() const
Definition: DeclBase.h:591
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:562
SourceLocation getLocation() const
Definition: DeclBase.h:442
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:237
void setImplicit(bool I=true)
Definition: DeclBase.h:597
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1042
DeclContext * getDeclContext()
Definition: DeclBase.h:451
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:434
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:363
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:911
bool hasAttr() const
Definition: DeclBase.h:580
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:971
Kind getKind() const
Definition: DeclBase.h:445
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.
DeclarationName getIdentifier(const IdentifierInfo *ID)
Create a declaration name that is a simple identifier.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:735
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
Represents the type decltype(expr) (C++11).
Definition: Type.h:5879
Represents a C++17 deduced template specialization type.
Definition: Type.h:6609
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:6630
TemplateName getUnderlying() const
Definition: TemplateName.h:458
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
DefaultArguments getDefaultArguments() const
Definition: TemplateName.h:460
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6527
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3920
Expr * getAddrSpaceExpr() const
Definition: Type.h:3931
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3942
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:7864
Internal representation of canonical, dependent decltype(expr) types.
Definition: Type.h:5907
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5911
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:7029
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7061
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3862
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3899
Expr * getSizeExpr() const
Definition: Type.h:3882
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3960
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3985
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4291
Expr * getRowExpr() const
Definition: Type.h:4303
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4311
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:548
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
Definition: TemplateName.h:620
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:607
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:610
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:626
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:7081
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:7108
Internal representation of canonical, dependent typeof(expr) types.
Definition: Type.h:5836
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5841
Internal representation of canonical, dependent __underlying_type(type) types.
Definition: Type.h:6037
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6042
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4086
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4111
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1493
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:896
Wrap a function effect's condition expression in another struct so that FunctionProtoType's TrailingO...
Definition: Type.h:4828
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6948
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7001
Represents an enum.
Definition: Decl.h:3861
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4066
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4080
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4021
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4963
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6103
EnumDecl * getDecl() const
Definition: Type.h:6110
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3102
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4131
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3077
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:3970
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
We can encode up to four bits in the low bits of a type pointer, but there are many more type qualifi...
Definition: Type.h:1703
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:1750
ExtVectorType - Extended vector type.
Definition: Type.h:4126
Declaration context for names declared as extern "C" in C++.
Definition: Decl.h:226
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition: Decl.cpp:5359
Abstract interface for external sources of AST nodes.
virtual ExtKind hasExternalDefinitions(const Decl *D)
virtual void ReadComments()
Loads comment ranges.
virtual void CompleteRedeclChain(const Decl *D)
Gives the external AST source an opportunity to complete the redeclaration chain for a declaration.
virtual void PrintStats()
Print any statistics that have been gathered regarding the external AST source.
Represents a member of a struct/union/class.
Definition: Decl.h:3033
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3136
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4602
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.h:3118
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3264
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:4555
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:1935
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2565
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3638
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2796
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition: Decl.cpp:3767
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4276
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2338
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4024
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:3937
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition: Type.cpp:5335
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition: Type.cpp:5373
Represents an abstract function effect, using just an enumeration describing its kind.
Definition: Type.h:4721
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4908
size_t size() const
Definition: Type.h:4939
ArrayRef< EffectConditionExpr > conditions() const
Definition: Type.h:4942
bool empty() const
Definition: Type.h:4938
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4686
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4702
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5107
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5573
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5387
unsigned getNumParams() const
Definition: Type.h:5360
QualType getParamType(unsigned i) const
Definition: Type.h:5362
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3867
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5393
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5484
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5371
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5367
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: Type.h:5549
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5545
Declaration of a template function.
Definition: DeclTemplate.h:958
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4432
CallingConv getCC() const
Definition: Type.h:4494
bool getNoCfCheck() const
Definition: Type.h:4484
unsigned getRegParm() const
Definition: Type.h:4487
bool getNoCallerSavedRegs() const
Definition: Type.h:4483
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4506
bool getHasRegParm() const
Definition: Type.h:4485
bool getNoReturn() const
Definition: Type.h:4480
bool getProducesResult() const
Definition: Type.h:4481
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:4347
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition: Type.h:4387
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
ExtInfo getExtInfo() const
Definition: Type.h:4660
QualType getReturnType() const
Definition: Type.h:4648
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
unsigned getMultiVersionIndex() const
Definition: GlobalDecl.h:122
CXXDtorType getDtorType() const
Definition: GlobalDecl.h:110
const Decl * getDecl() const
Definition: GlobalDecl.h:103
QualType getWrappedType() const
Definition: Type.h:6298
const Attributes & getAttrs() const
Definition: Type.h:6301
QualType getContainedType() const
Definition: Type.h:6299
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6306
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.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4808
Represents a C array with an unspecified size.
Definition: Type.h:3764
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3781
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6798
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
@ Relative
Components in the vtable are relative offsets between the vtable and the other structs/functions.
@ Pointer
Components in the vtable are pointers to other structs/functions.
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3483
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:499
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
Definition: LangOptions.h:587
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:534
CoreFoundationABI CFRuntime
Definition: LangOptions.h:536
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:563
std::string CUID
The user provided compilation unit ID, if non-empty.
Definition: LangOptions.h:583
A global _GUID constant.
Definition: DeclCXX.h:4312
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition: DeclCXX.h:4349
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition: Type.h:5770
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:45
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4210
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition: Type.h:4217
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3555
QualType getPointeeType() const
Definition: Type.h:3535
const Type * getClass() const
Definition: Type.h:3549
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:619
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Describes a module or submodule.
Definition: Module.h:115
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:195
This represents a decl that may have a name.
Definition: Decl.h:253
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1089
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
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:296
bool isExternallyVisible() const
Definition: Decl.h:412
NamespaceDecl * getNamespace()
Retrieve the namespace declaration aliased by this directive.
Definition: DeclCXX.h:3215
Represent a C++ namespace.
Definition: Decl.h:551
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition: DeclCXX.cpp:3128
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
NamespaceAliasDecl * getAsNamespaceAlias() const
Retrieve the namespace alias stored in this nested name specifier.
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
NamespaceDecl * getAsNamespace() const
Retrieve the namespace stored in this nested name specifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2328
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition: DeclObjC.h:2544
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2596
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition: DeclObjC.cpp:320
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, const IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
Definition: DeclObjC.cpp:1540
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1527
ivar_range ivars() const
Definition: DeclObjC.h:1450
bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID=false)
ClassImplementsProtocol - Checks that 'lProto' protocol has been implemented in IDecl class,...
Definition: DeclObjC.cpp:1786
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
Definition: DeclObjC.cpp:1611
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1627
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1914
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:350
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:1809
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1761
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7529
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.cpp:936
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1986
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: DeclObjC.h:246
unsigned param_size() const
Definition: DeclObjC.h:347
param_const_iterator param_end() const
Definition: DeclObjC.h:358
param_const_iterator param_begin() const
Definition: DeclObjC.h:354
bool isVariadic() const
Definition: DeclObjC.h:431
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:349
Selector getSelector() const
Definition: DeclObjC.h:327
bool isInstanceMethod() const
Definition: DeclObjC.h:426
QualType getReturnType() const
Definition: DeclObjC.h:329
Represents a pointer to an Objective C object.
Definition: Type.h:7585
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition: Type.h:7666
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition: Type.cpp:943
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition: Type.h:7660
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7742
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7622
bool qual_empty() const
Definition: Type.h:7714
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7643
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7597
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7637
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1833
qual_range quals() const
Definition: Type.h:7704
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:7649
A class providing a concrete implementation of ObjCObjectType, so as to not increase the footprint of...
Definition: Type.h:7482
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4450
Represents a class type in Objective C.
Definition: Type.h:7331
bool isKindOfTypeAsWritten() const
Whether this is a "__kindof" type as written.
Definition: Type.h:7446
bool isSpecialized() const
Determine whether this object type is "specialized", meaning that it has type arguments.
Definition: Type.cpp:865
ArrayRef< QualType > getTypeArgsAsWritten() const
Retrieve the type arguments of this object type as they were written.
Definition: Type.h:7441
bool isObjCQualifiedClass() const
Definition: Type.h:7413
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:7393
bool isObjCClass() const
Definition: Type.h:7399
bool isKindOfType() const
Whether this ia a "__kindof" type (semantically).
Definition: Type.cpp:901
bool isObjCQualifiedId() const
Definition: Type.h:7412
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments of this object type (semantically).
Definition: Type.cpp:883
bool isObjCUnqualifiedId() const
Definition: Type.h:7403
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:7564
QualType getSuperClassType() const
Retrieve the type of the superclass of this object type.
Definition: Type.h:7457
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition: DeclObjC.h:837
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:177
bool isOptional() const
Definition: DeclObjC.h:915
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition: DeclObjC.h:872
Selector getSetterName() const
Definition: DeclObjC.h:892
QualType getType() const
Definition: DeclObjC.h:803
Selector getGetterName() const
Definition: DeclObjC.h:884
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition: DeclObjC.h:814
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2804
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2878
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2083
protocol_range protocols() const
Definition: DeclObjC.h:2160
unsigned getNumProtocols() const
Return the number of qualifying protocols in this type, or 0 if there are none.
Definition: Type.h:7237
qual_iterator qual_end() const
Definition: Type.h:7231
qual_iterator qual_begin() const
Definition: Type.h:7230
qual_range quals() const
Definition: Type.h:7229
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
Definition: ObjCRuntime.h:127
Represents the declaration of an Objective-C type parameter.
Definition: DeclObjC.h:578
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition: DeclObjC.h:623
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition: DeclObjC.h:659
Represents a type parameter type in Objective C.
Definition: Type.h:7257
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4467
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:116
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4180
Represents a pack expansion of types.
Definition: Type.h:7146
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7180
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5973
Sugar for parentheses used when specifying types.
Definition: Type.h:3172
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3186
void clear()
Clear parent maps.
Represents a parameter to a function.
Definition: Decl.h:1725
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1789
QualType getOriginalType() const
Definition: Decl.cpp:2931
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
PipeType - OpenCL20.
Definition: Type.h:7785
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7802
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3213
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:138
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8020
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2796
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition: Type.h:8067
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8025
QualType withConst() const
Definition: Type.h:1154
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition: Type.h:1056
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7936
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8062
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7976
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
QualType getCanonicalType() const
Definition: Type.h:7988
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8030
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: Type.h:7957
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8009
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1531
bool isCanonical() const
Definition: Type.h:7993
const Type * getTypePtrOrNull() const
Definition: Type.h:7940
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
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:2933
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7968
Represents a template name as written in source code.
Definition: TemplateName.h:491
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:528
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7876
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7883
The collection of all-type qualifiers we support.
Definition: Type.h:324
unsigned getCVRQualifiers() const
Definition: Type.h:481
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:488
GC getObjCGCAttr() const
Definition: Type.h:512
void addAddressSpace(LangAS space)
Definition: Type.h:590
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition: Type.h:377
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:347
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:343
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:357
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:360
void removeObjCLifetime()
Definition: Type.h:544
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated.
Definition: Type.h:631
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don't conflict.
Definition: Type.h:682
void removeFastQualifiers(unsigned mask)
Definition: Type.h:617
bool hasUnaligned() const
Definition: Type.h:504
bool hasAddressSpace() const
Definition: Type.h:563
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: Type.h:701
unsigned getFastQualifiers() const
Definition: Type.h:612
void removeAddressSpace()
Definition: Type.h:589
void setAddressSpace(LangAS space)
Definition: Type.h:584
bool hasObjCGCAttr() const
Definition: Type.h:511
uint64_t getAsOpaqueValue() const
Definition: Type.h:448
bool hasObjCLifetime() const
Definition: Type.h:537
ObjCLifetime getObjCLifetime() const
Definition: Type.h:538
bool empty() const
Definition: Type.h:640
void addObjCGCAttr(GC type)
Definition: Type.h:517
LangAS getAddressSpace() const
Definition: Type.h:564
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3501
unsigned getCommentBeginLine(RawComment *C, FileID File, unsigned Offset) const
const std::map< unsigned, RawComment * > * getCommentsInFile(FileID File) const
unsigned getCommentEndOffset(RawComment *C) const
void addComment(const RawComment &RC, const CommentOptions &CommentOpts, llvm::BumpPtrAllocator &Allocator)
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:4162
bool hasFlexibleArrayMember() const
Definition: Decl.h:4195
field_range fields() const
Definition: Decl.h:4376
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5041
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5107
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4361
bool field_empty() const
Definition: Decl.h:4384
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6077
RecordDecl * getDecl() const
Definition: Type.h:6087
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:203
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:225
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:295
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
QualType getPointeeType() const
Definition: Type.h:3457
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3465
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.
DiagnosticsEngine & getDiagnostics() const
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Given a SourceLocation, return the spelling line number for the position indicated.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
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.
Definition: Diagnostic.h:1102
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1194
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:149
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.
Definition: TemplateName.h:164
A structure for storing the information associated with a substituted template template parameter.
Definition: TemplateName.h:408
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:6469
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4311
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:6388
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6433
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3578
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3806
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4762
bool isUnion() const
Definition: Decl.h:3784
TagDecl * getDecl() const
Definition: Type.cpp:4122
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
Kind
The basic C++ ABI kind.
Definition: TargetCXXABI.h:31
static Kind getKind(StringRef Name)
Definition: TargetCXXABI.h:59
Exposes information about the current target.
Definition: TargetInfo.h:220
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:311
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
IntType getInt64Type() const
Definition: TargetInfo.h:411
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition: TargetInfo.h:844
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
Definition: TargetInfo.h:1646
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
Definition: TargetInfo.h:1640
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition: TargetInfo.h:737
unsigned getBFloat16Width() const
getBFloat16Width/Align/Format - Return the size/align/format of '__bf16'.
Definition: TargetInfo.h:782
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition: TargetInfo.h:318
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition: TargetInfo.h:327
@ PNaClABIBuiltinVaList
__builtin_va_list as defined by the PNaCl ABI: http://www.chromium.org/nativeclient/pnacl/bitcode-abi...
Definition: TargetInfo.h:331
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition: TargetInfo.h:336
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition: TargetInfo.h:345
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:320
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition: TargetInfo.h:323
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition: TargetInfo.h:340
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition: TargetInfo.h:494
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:478
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
Definition: TargetInfo.cpp:386
unsigned getHalfAlign() const
Definition: TargetInfo.h:773
unsigned getBFloat16Align() const
Definition: TargetInfo.h:783
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
Definition: TargetInfo.cpp:332
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
Definition: TargetInfo.cpp:302
unsigned getHalfWidth() const
getHalfWidth/Align/Format - Return the size/align/format of 'half'.
Definition: TargetInfo.h:772
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition: TargetInfo.h:957
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:745
unsigned getTargetAddressSpace(LangAS AS) const
Definition: TargetInfo.h:1627
unsigned getFloat128Width() const
getFloat128Width/Align/Format - Return the size/align/format of '__float128'.
Definition: TargetInfo.h:801
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:795
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
bool hasAArch64SVETypes() const
Returns whether or not the AArch64 SVE built-in types are available on this target.
Definition: TargetInfo.h:1046
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
Definition: TargetInfo.h:1008
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:524
unsigned getFloat128Align() const
Definition: TargetInfo.h:802
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition: TargetInfo.h:709
const llvm::fltSemantics & getFloat128Format() const
Definition: TargetInfo.h:803
unsigned getLongDoubleWidth() const
getLongDoubleWidth/Align/Format - Return the size/align/format of 'long double'.
Definition: TargetInfo.h:793
unsigned getLongDoubleAlign() const
Definition: TargetInfo.h:794
virtual std::optional< std::pair< unsigned, unsigned > > getVScaleRange(const LangOptions &LangOpts) const
Returns target-specific min and max values VScale_Range.
Definition: TargetInfo.h:1026
llvm::StringMap< bool > FeatureMap
The map of which features have been enabled disabled based on the command line.
Definition: TargetOptions.h:62
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:648
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
SourceLocation getLAngleLoc() const
Definition: TemplateBase.h:647
A template argument list.
Definition: DeclTemplate.h:250
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:399
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:331
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
std::optional< unsigned > 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.
Definition: TemplateBase.h:319
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:337
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.
Definition: TemplateBase.h:343
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.
Definition: TemplateBase.h:377
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
Definition: TemplateBase.h:393
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:432
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
Definition: TemplateBase.h:350
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:396
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:398
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:417
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
Definition: TemplateName.h:388
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
Definition: TemplateName.h:265
@ OverloadedTemplate
A set of overloaded template declarations.
Definition: TemplateName.h:240
@ Template
A single template declaration.
Definition: TemplateName.h:237
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
Definition: TemplateName.h:252
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
Definition: TemplateName.h:256
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
Definition: TemplateName.h:261
@ DeducedTemplate
A template name that refers to another TemplateName with deduced default arguments.
Definition: TemplateName.h:269
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
Definition: TemplateName.h:248
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
Definition: TemplateName.h:244
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.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:147
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.
Definition: DeclTemplate.h:132
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:183
ArrayRef< NamedDecl * > asArray()
Definition: DeclTemplate.h:142
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1719
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1695
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1736
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1703
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1711
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6666
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:4402
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
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.
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, bool Typename, TemplateParameterList *Params)
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6360
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:227
ConceptDecl * getNamedConcept() const
Definition: ASTConcept.h:250
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:242
ConceptReference * getConceptReference() const
Definition: ASTConcept.h:246
Represents a declaration of a type.
Definition: Decl.h:3384
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3410
const Type * getTypeForDecl() const
Definition: Decl.h:3409
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:94
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition: TypeLoc.h:200
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:5802
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:5852
A container of type source information.
Definition: Type.h:7907
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
The base class of the type hierarchy.
Definition: Type.h:1828
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isBlockPointerType() const
Definition: Type.h:8205
bool isVoidType() const
Definition: Type.h:8515
bool isBooleanType() const
Definition: Type.h:8643
bool isFunctionReferenceType() const
Definition: Type.h:8238
bool isObjCBuiltinType() const
Definition: Type.h:8384
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition: Type.cpp:2624
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:773
bool isIncompleteArrayType() const
Definition: Type.h:8271
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:8491
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2180
bool isConstantArrayType() const
Definition: Type.h:8267
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:2055
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2386
bool isArrayType() const
Definition: Type.h:8263
bool isCharType() const
Definition: Type.cpp:2123
QualType getLocallyUnqualifiedSingleStepDesugaredType() const
Pull a single level of sugar off of this locally-unqualified type.
Definition: Type.cpp:509
bool isFunctionPointerType() const
Definition: Type.h:8231
bool isPointerType() const
Definition: Type.h:8191
bool isArrayParameterType() const
Definition: Type.h:8279
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8555
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8805
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:8504
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8596
bool isEnumeralType() const
Definition: Type.h:8295
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2554
bool isObjCQualifiedIdType() const
Definition: Type.h:8354
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8630
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2270
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2593
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2811
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isBitIntType() const
Definition: Type.h:8429
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8484
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8287
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8568
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8584
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2361
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2220
QualType getCanonicalTypeInternal() const
Definition: Type.h:2989
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8686
bool isMemberPointerType() const
Definition: Type.h:8245
bool isObjCIdType() const
Definition: Type.h:8366
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8592
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8791
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool isFunctionType() const
Definition: Type.h:8187
bool isObjCObjectPointerType() const
Definition: Type.h:8333
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8610
bool isVectorType() const
Definition: Type.h:8303
bool isObjCClassType() const
Definition: Type.h:8372
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition: Type.cpp:2606
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2541
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:2230
bool isAnyPointerType() const
Definition: Type.h:8199
TypeClass getTypeClass() const
Definition: Type.h:2341
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2367
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8736
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:638
bool isNullPtrType() const
Definition: Type.h:8548
bool isRecordType() const
Definition: Type.h:8291
bool isObjCRetainableType() const
Definition: Type.cpp:5028
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4763
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3528
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5529
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3427
QualType getUnderlyingType() const
Definition: Decl.h:3482
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3488
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5755
A unary type transform, which is a type constructed from another.
Definition: Type.h:5994
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4369
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition: DeclCXX.h:4397
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: Type.h:5672
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3982
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3736
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3343
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5723
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
void setType(QualType newType)
Definition: Decl.h:683
QualType getType() const
Definition: Decl.h:682
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5392
void clear()
Definition: Value.cpp:218
Represents a variable declaration or definition.
Definition: Decl.h:882
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2786
bool hasInit() const
Definition: Decl.cpp:2387
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:2433
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1159
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2748
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1495
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1246
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2364
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:2755
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3808
Expr * getSizeExpr() const
Definition: Type.h:3827
Represents a GCC generic vector type.
Definition: Type.h:4034
unsigned getNumElements() const
Definition: Type.h:4049
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4058
VectorKind getVectorKind() const
Definition: Type.h:4054
QualType getElementType() const
Definition: Type.h:4048
A full comment attached to a declaration, contains block content.
Definition: Comment.h:1083
ArrayRef< BlockContentComment * > getBlocks() const
Definition: Comment.h:1121
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition: Comment.h:1115
const Decl * getDecl() const LLVM_READONLY
Definition: Comment.h:1111
Holds all information required to evaluate constexpr code in a module.
Definition: Context.h:40
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
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
Matches all kinds of arrays.
const AstTypeMatcher< TagType > tagType
Matches tag types (record and enum types).
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OpenCL
Definition: LangStandard.h:65
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
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: Type.h:1778
OpenCLTypeKind
OpenCL type kinds.
Definition: TargetInfo.h:206
@ OCLTK_ReserveID
Definition: TargetInfo.h:213
@ OCLTK_Sampler
Definition: TargetInfo.h:214
@ OCLTK_Pipe
Definition: TargetInfo.h:211
@ OCLTK_ClkEvent
Definition: TargetInfo.h:208
@ OCLTK_Event
Definition: TargetInfo.h:209
@ OCLTK_Default
Definition: TargetInfo.h:207
@ OCLTK_Queue
Definition: TargetInfo.h:212
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition: Type.h:8089
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:336
@ Nullable
Values of this type can be null.
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
@ NonNull
Values of this type can never be null.
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
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: Type.h:910
@ SC_Register
Definition: Specifiers.h:257
@ SC_Static
Definition: Specifiers.h:252
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Result
The result type of a method or function.
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition: Type.h:3574
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
SubstTemplateTypeParmTypeFlag
Definition: Type.h:1789
TagTypeKind
The kind of a tag type.
Definition: Type.h:6876
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:80
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition: Builtins.h:308
@ BTK__type_pack_element
This names the __type_pack_element BuiltinTemplateDecl.
Definition: Builtins.h:313
@ BTK__builtin_common_type
This names the __builtin_common_type BuiltinTemplateDecl.
Definition: Builtins.h:316
@ BTK__make_integer_seq
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:310
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:1096
@ TypeAlignment
Definition: Type.h:76
FloatModeKind
Definition: TargetInfo.h:73
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:91
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1278
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_C
Definition: Specifiers.h:279
@ CC_M68kRTD
Definition: Specifiers.h:300
@ CC_X86RegCall
Definition: Specifiers.h:287
@ CC_X86VectorCall
Definition: Specifiers.h:283
@ CC_X86StdCall
Definition: Specifiers.h:280
@ CC_X86FastCall
Definition: Specifiers.h:281
@ Invariant
The parameter is invariant: must match exactly.
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
VectorKind
Definition: Type.h:3993
@ AltiVecBool
is AltiVec 'vector bool ...'
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
@ AltiVecPixel
is AltiVec 'vector Pixel'
@ Generic
not a target-specific vector type
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
LangAS getLangASFromTargetAS(unsigned TargetAS)
Definition: AddressSpaces.h:86
AlignRequirementKind
Definition: ASTContext.h:144
@ None
The alignment was not explicit in code.
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6851
@ None
No keyword precedes the qualified type name.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_DynamicNone
throw()
@ 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)
@ AS_public
Definition: Specifiers.h:124
unsigned long uint64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: TemplateBase.h:694
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition: Expr.h:6460
Expr * getCopyExpr() const
Definition: Expr.h:6467
bool ParseAllComments
Treat ordinary comments as documentation comments.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
ArrayRef< TemplateArgument > Args
Definition: TemplateName.h:187
Holds information about the various types of exception specification.
Definition: Type.h:5164
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5166
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:5169
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:5172
Extra information about a function prototype.
Definition: Type.h:5192
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5199
bool requiresFunctionProtoTypeArmAttributes() const
Definition: Type.h:5224
FunctionEffectsRef FunctionEffects
Definition: Type.h:5202
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5200
bool requiresFunctionProtoTypeExtraBitfields() const
Definition: Type.h:5218
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5193
A simple holder for a QualType representing a type in an exception specification.
Definition: Type.h:4559
A holder for Arm type attributes as described in the Arm C/C++ Language extensions which are not part...
Definition: Type.h:4625
A simple holder for various uncommon bits which do not fit in FunctionTypeBitfields.
Definition: Type.h:4564
A lazy value (of type T) that is within an AST node of type Owner, where the value might change in la...
Parts of a decomposed MSGuidDecl.
Definition: DeclCXX.h:4287
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:58
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: Type.h:862
const Type * Ty
The locally-unqualified type.
Definition: Type.h:864
Qualifiers Quals
The local qualifiers.
Definition: Type.h:867
A this pointer adjustment.
Definition: Thunk.h:92
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition: TargetInfo.h:144
AlignRequirementKind AlignRequirement
Definition: ASTContext.h:175
bool isAlignRequired()
Definition: ASTContext.h:167
AlignRequirementKind AlignRequirement
Definition: ASTContext.h:161
uint64_t Width
Definition: ASTContext.h:159
unsigned Align
Definition: ASTContext.h:160
Information about the declaration, useful to clients of FullComment.
Definition: Comment.h:962
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition: Comment.h:988
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition: Comment.h:965
static bool isEqual(const FoldingSetNodeID &LHS, const FoldingSetNodeID &RHS)
Definition: ASTContext.cpp:130
static FoldingSetNodeID getTombstoneKey()
Definition: ASTContext.cpp:118
static unsigned getHashValue(const FoldingSetNodeID &Val)
Definition: ASTContext.cpp:126