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
13#include "clang/AST/ASTContext.h"
14#include "ByteCode/Context.h"
15#include "CXXABI.h"
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/ASTStructuralEquivalence.h"
20#include "clang/AST/ASTTypeTraits.h"
21#include "clang/AST/Attr.h"
22#include "clang/AST/AttrIterator.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/Comment.h"
25#include "clang/AST/Decl.h"
26#include "clang/AST/DeclBase.h"
27#include "clang/AST/DeclCXX.h"
28#include "clang/AST/DeclContextInternals.h"
29#include "clang/AST/DeclObjC.h"
30#include "clang/AST/DeclOpenMP.h"
31#include "clang/AST/DeclTemplate.h"
32#include "clang/AST/DeclarationName.h"
33#include "clang/AST/DependenceFlags.h"
34#include "clang/AST/Expr.h"
35#include "clang/AST/ExprCXX.h"
36#include "clang/AST/ExternalASTSource.h"
37#include "clang/AST/Mangle.h"
38#include "clang/AST/MangleNumberingContext.h"
39#include "clang/AST/NestedNameSpecifier.h"
40#include "clang/AST/ParentMapContext.h"
41#include "clang/AST/RawCommentList.h"
42#include "clang/AST/RecordLayout.h"
43#include "clang/AST/Stmt.h"
44#include "clang/AST/TemplateBase.h"
45#include "clang/AST/TemplateName.h"
46#include "clang/AST/Type.h"
47#include "clang/AST/TypeLoc.h"
48#include "clang/AST/UnresolvedSet.h"
49#include "clang/AST/VTableBuilder.h"
50#include "clang/Basic/AddressSpaces.h"
51#include "clang/Basic/Builtins.h"
52#include "clang/Basic/CommentOptions.h"
53#include "clang/Basic/DiagnosticAST.h"
54#include "clang/Basic/ExceptionSpecificationType.h"
55#include "clang/Basic/IdentifierTable.h"
56#include "clang/Basic/LLVM.h"
57#include "clang/Basic/LangOptions.h"
58#include "clang/Basic/Linkage.h"
59#include "clang/Basic/Module.h"
60#include "clang/Basic/NoSanitizeList.h"
61#include "clang/Basic/ObjCRuntime.h"
62#include "clang/Basic/ProfileList.h"
63#include "clang/Basic/SourceLocation.h"
64#include "clang/Basic/SourceManager.h"
65#include "clang/Basic/Specifiers.h"
66#include "clang/Basic/TargetCXXABI.h"
67#include "clang/Basic/TargetInfo.h"
68#include "clang/Basic/XRayLists.h"
69#include "clang/Lex/MacroInfo.h"
70#include "llvm/ADT/APFixedPoint.h"
71#include "llvm/ADT/APInt.h"
72#include "llvm/ADT/APSInt.h"
73#include "llvm/ADT/ArrayRef.h"
74#include "llvm/ADT/DenseMap.h"
75#include "llvm/ADT/DenseSet.h"
76#include "llvm/ADT/FoldingSet.h"
77#include "llvm/ADT/PointerUnion.h"
78#include "llvm/ADT/STLExtras.h"
79#include "llvm/ADT/SmallPtrSet.h"
80#include "llvm/ADT/SmallVector.h"
81#include "llvm/ADT/StringExtras.h"
82#include "llvm/ADT/StringRef.h"
83#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
84#include "llvm/Support/Capacity.h"
85#include "llvm/Support/Casting.h"
86#include "llvm/Support/Compiler.h"
87#include "llvm/Support/ErrorHandling.h"
88#include "llvm/Support/MD5.h"
89#include "llvm/Support/MathExtras.h"
90#include "llvm/Support/SipHash.h"
91#include "llvm/Support/raw_ostream.h"
92#include "llvm/TargetParser/AArch64TargetParser.h"
93#include "llvm/TargetParser/Triple.h"
94#include <algorithm>
95#include <cassert>
96#include <cstddef>
97#include <cstdint>
98#include <cstdlib>
99#include <map>
100#include <memory>
101#include <optional>
102#include <string>
103#include <tuple>
104#include <utility>
105
106using namespace clang;
107
108enum FloatingRank {
109 BFloat16Rank,
110 Float16Rank,
111 HalfRank,
112 FloatRank,
113 DoubleRank,
114 LongDoubleRank,
115 Float128Rank,
116 Ibm128Rank
117};
118
119/// \returns The locations that are relevant when searching for Doc comments
120/// related to \p Key.
121static SmallVector<SourceLocation, 2>
122getLocsForCommentSearch(ASTContext::RawCommentLookupKey Key,
123 SourceManager &SourceMgr) {
124 if (const auto *MI = dyn_cast<const MacroInfo *>(Val&: Key)) {
125 SourceLocation DefLoc = MI->getDefinitionLoc();
126 if (DefLoc.isInvalid() || !DefLoc.isFileID())
127 return {};
128
129 // The macro's definition location points at its name (e.g. FOO in
130 // `#define FOO 1`). The text between a preceding documentation comment
131 // and the name contains the `#define` directive itself, which would be
132 // rejected by the preprocessor-directive guard in
133 // getRawCommentNoCacheImpl. Walk back to the leading `#` so that
134 // the guard only fires when something *else* sits between the comment
135 // and our directive.
136 FileIDAndOffset Decomposed = SourceMgr.getDecomposedLoc(Loc: DefLoc);
137 bool Invalid = false;
138 StringRef Buffer = SourceMgr.getBufferData(FID: Decomposed.first, Invalid: &Invalid);
139 if (Invalid)
140 return {};
141 unsigned Offset = Decomposed.second;
142 if (size_t Found = Buffer.find_last_of(Chars: "#\n", From: Offset);
143 Found != StringRef::npos)
144 Offset = Found;
145 return {SourceMgr.getLocForStartOfFile(FID: Decomposed.first)
146 .getLocWithOffset(Offset)};
147 }
148
149 const auto *D = cast<const Decl *>(Val&: Key);
150 assert(D);
151
152 // User can not attach documentation to implicit declarations.
153 if (D->isImplicit())
154 return {};
155
156 // User can not attach documentation to implicit instantiations.
157 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
158 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
159 return {};
160 }
161
162 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
163 if (VD->isStaticDataMember() &&
164 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
165 return {};
166 }
167
168 if (const auto *CRD = dyn_cast<CXXRecordDecl>(Val: D)) {
169 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
170 return {};
171 }
172
173 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: D)) {
174 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
175 if (TSK == TSK_ImplicitInstantiation ||
176 TSK == TSK_Undeclared)
177 return {};
178 }
179
180 if (const auto *ED = dyn_cast<EnumDecl>(Val: D)) {
181 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
182 return {};
183 }
184 if (const auto *TD = dyn_cast<TagDecl>(Val: D)) {
185 // When tag declaration (but not definition!) is part of the
186 // decl-specifier-seq of some other declaration, it doesn't get comment
187 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
188 return {};
189 }
190 // TODO: handle comments for function parameters properly.
191 if (isa<ParmVarDecl>(Val: D))
192 return {};
193
194 // TODO: we could look up template parameter documentation in the template
195 // documentation.
196 if (isa<TemplateTypeParmDecl>(Val: D) ||
197 isa<NonTypeTemplateParmDecl>(Val: D) ||
198 isa<TemplateTemplateParmDecl>(Val: D))
199 return {};
200
201 SmallVector<SourceLocation, 2> Locations;
202 // Find declaration location.
203 // For Objective-C declarations we generally don't expect to have multiple
204 // declarators, thus use declaration starting location as the "declaration
205 // location".
206 // For all other declarations multiple declarators are used quite frequently,
207 // so we use the location of the identifier as the "declaration location".
208 SourceLocation BaseLocation;
209 if (isa<ObjCMethodDecl>(Val: D) || isa<ObjCContainerDecl>(Val: D) ||
210 isa<ObjCPropertyDecl>(Val: D) || isa<RedeclarableTemplateDecl>(Val: D) ||
211 isa<ClassTemplateSpecializationDecl>(Val: D) ||
212 // Allow association with Y across {} in `typedef struct X {} Y`.
213 isa<TypedefDecl>(Val: D))
214 BaseLocation = D->getBeginLoc();
215 else
216 BaseLocation = D->getLocation();
217
218 if (!D->getLocation().isMacroID()) {
219 Locations.emplace_back(Args&: BaseLocation);
220 } else {
221 const auto *DeclCtx = D->getDeclContext();
222
223 // When encountering definitions generated from a macro (that are not
224 // contained by another declaration in the macro) we need to try and find
225 // the comment at the location of the expansion but if there is no comment
226 // there we should retry to see if there is a comment inside the macro as
227 // well. To this end we return first BaseLocation to first look at the
228 // expansion site, the second value is the spelling location of the
229 // beginning of the declaration defined inside the macro.
230 if (!(DeclCtx &&
231 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
232 Locations.emplace_back(Args: SourceMgr.getExpansionLoc(Loc: BaseLocation));
233 }
234
235 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
236 // we don't refer to the macro argument location at the expansion site (this
237 // can happen if the name's spelling is provided via macro argument), and
238 // always to the declaration itself.
239 Locations.emplace_back(Args: SourceMgr.getSpellingLoc(Loc: D->getBeginLoc()));
240 }
241
242 return Locations;
243}
244
245RawComment *ASTContext::getRawCommentNoCacheImpl(
246 RawCommentLookupKey Key, const SourceLocation RepresentativeLoc,
247 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
248 // If the declaration doesn't map directly to a location in a file, we
249 // can't find the comment.
250 if (RepresentativeLoc.isInvalid() || !RepresentativeLoc.isFileID())
251 return nullptr;
252
253 // If there are no comments anywhere, we won't find anything.
254 if (CommentsInTheFile.empty())
255 return nullptr;
256
257 const auto *D = dyn_cast<const Decl *>(Val&: Key);
258 const bool IsMacro = isa<const MacroInfo *>(Val: Key);
259
260 // Decompose the location for the declaration and find the beginning of the
261 // file buffer.
262 const FileIDAndOffset LocDecomp =
263 SourceMgr.getDecomposedLoc(Loc: RepresentativeLoc);
264
265 // Slow path.
266 auto OffsetCommentBehindDecl =
267 CommentsInTheFile.lower_bound(x: LocDecomp.second);
268
269 // First check whether we have a trailing comment.
270 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
271 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
272 if ((CommentBehindDecl->isDocumentation() ||
273 LangOpts.CommentOpts.ParseAllComments) &&
274 CommentBehindDecl->isTrailingComment() &&
275 (IsMacro || (D && (isa<FieldDecl>(Val: D) || isa<EnumConstantDecl>(Val: D) ||
276 isa<VarDecl>(Val: D) || isa<ObjCMethodDecl>(Val: D) ||
277 isa<ObjCPropertyDecl>(Val: D))))) {
278
279 // Check that Doxygen trailing comment comes after the declaration, starts
280 // on the same line and in the same file as the declaration.
281 if (SourceMgr.getLineNumber(FID: LocDecomp.first, FilePos: LocDecomp.second) ==
282 Comments.getCommentBeginLine(C: CommentBehindDecl, File: LocDecomp.first,
283 Offset: OffsetCommentBehindDecl->first)) {
284 return CommentBehindDecl;
285 }
286 }
287 }
288
289 // The comment just after the declaration was not a trailing comment.
290 // Let's look at the previous comment.
291 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
292 return nullptr;
293
294 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
295 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
296
297 // Check that we actually have a non-member Doxygen comment.
298 if (!(CommentBeforeDecl->isDocumentation() ||
299 LangOpts.CommentOpts.ParseAllComments) ||
300 CommentBeforeDecl->isTrailingComment())
301 return nullptr;
302
303 // Decompose the end of the comment.
304 const unsigned CommentEndOffset =
305 Comments.getCommentEndOffset(C: CommentBeforeDecl);
306
307 // Get the corresponding buffer.
308 bool Invalid = false;
309 const char *Buffer =
310 SourceMgr.getBufferData(FID: LocDecomp.first, Invalid: &Invalid).data();
311 if (Invalid)
312 return nullptr;
313
314 // Extract text between the comment and declaration.
315 StringRef Text(Buffer + CommentEndOffset,
316 LocDecomp.second - CommentEndOffset);
317
318 // There should be no other declarations or preprocessor directives between
319 // comment and declaration.
320 if (Text.find_last_of(Chars: ";{}#@") != StringRef::npos)
321 return nullptr;
322
323 return CommentBeforeDecl;
324}
325
326RawComment *ASTContext::getRawCommentNoCache(RawCommentLookupKey Key) const {
327 const auto Locs = getLocsForCommentSearch(Key, SourceMgr);
328
329 for (const auto Loc : Locs) {
330 // If the declaration or macro doesn't map directly to a location in a file,
331 // we can't find the comment.
332 if (Loc.isInvalid() || !Loc.isFileID())
333 continue;
334
335 if (ExternalSource && !CommentsLoaded) {
336 ExternalSource->ReadComments();
337 CommentsLoaded = true;
338 }
339
340 if (Comments.empty())
341 continue;
342
343 const FileID File = SourceMgr.getDecomposedLoc(Loc).first;
344 if (!File.isValid())
345 continue;
346
347 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
348 if (!CommentsInThisFile || CommentsInThisFile->empty())
349 continue;
350
351 if (RawComment *Comment =
352 getRawCommentNoCacheImpl(Key, RepresentativeLoc: Loc, CommentsInTheFile: *CommentsInThisFile))
353 return Comment;
354 }
355
356 return nullptr;
357}
358
359void ASTContext::addComment(const RawComment &RC) {
360 assert(LangOpts.RetainCommentsFromSystemHeaders ||
361 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
362 Comments.addComment(RC, CommentOpts: LangOpts.CommentOpts, Allocator&: BumpAlloc);
363}
364
365const RawComment *
366ASTContext::getRawCommentForAnyRedecl(RawCommentLookupKey Key,
367 const Decl **OriginalDecl) const {
368 if (Key.isNull()) {
369 if (OriginalDecl)
370 *OriginalDecl = nullptr;
371 return nullptr;
372 }
373
374 // Macros have no redeclaration chain: look up directly, populate the cache,
375 // and return.
376 if (const auto *MI = dyn_cast<const MacroInfo *>(Val&: Key)) {
377 if (OriginalDecl)
378 *OriginalDecl = nullptr;
379 auto Existing = RawComments.find(Val: Key);
380 if (Existing != RawComments.end())
381 return Existing->second;
382 if (const RawComment *RC = getRawCommentNoCache(Key)) {
383 cacheRawComment(Original: MI, Comment: *RC);
384 return RC;
385 }
386 return nullptr;
387 }
388
389 const Decl *D = cast<const Decl *>(Val&: Key);
390 D = &adjustDeclToTemplate(D: *D);
391
392 // Any comment directly attached to D?
393 {
394 auto DeclComment = RawComments.find(Val: D);
395 if (DeclComment != RawComments.end()) {
396 if (OriginalDecl)
397 *OriginalDecl = D;
398 return DeclComment->second;
399 }
400 }
401
402 // Any comment attached to any redeclaration of D?
403 const Decl *CanonicalD = D->getCanonicalDecl();
404 if (!CanonicalD)
405 return nullptr;
406
407 {
408 auto RedeclComment = RedeclChainComments.find(Val: CanonicalD);
409 if (RedeclComment != RedeclChainComments.end()) {
410 if (OriginalDecl)
411 *OriginalDecl = RedeclComment->second;
412 auto CommentAtRedecl = RawComments.find(Val: RedeclComment->second);
413 assert(CommentAtRedecl != RawComments.end() &&
414 "This decl is supposed to have comment attached.");
415 return CommentAtRedecl->second;
416 }
417 }
418
419 // Any redeclarations of D that we haven't checked for comments yet?
420 const Decl *LastCheckedRedecl = [&]() {
421 const Decl *LastChecked = CommentlessRedeclChains.lookup(Val: CanonicalD);
422 bool CanUseCommentlessCache = false;
423 if (LastChecked) {
424 for (auto *Redecl : CanonicalD->redecls()) {
425 if (Redecl == D) {
426 CanUseCommentlessCache = true;
427 break;
428 }
429 if (Redecl == LastChecked)
430 break;
431 }
432 }
433 // FIXME: This could be improved so that even if CanUseCommentlessCache
434 // is false, once we've traversed past CanonicalD we still skip ahead
435 // LastChecked.
436 return CanUseCommentlessCache ? LastChecked : nullptr;
437 }();
438
439 for (const Decl *Redecl : D->redecls()) {
440 assert(Redecl);
441 // Skip all redeclarations that have been checked previously.
442 if (LastCheckedRedecl) {
443 if (LastCheckedRedecl == Redecl) {
444 LastCheckedRedecl = nullptr;
445 }
446 continue;
447 }
448 const RawComment *RedeclComment = getRawCommentNoCache(Key: Redecl);
449 if (RedeclComment) {
450 cacheRawComment(Original: Redecl, Comment: *RedeclComment);
451 if (OriginalDecl)
452 *OriginalDecl = Redecl;
453 return RedeclComment;
454 }
455 CommentlessRedeclChains[CanonicalD] = Redecl;
456 }
457
458 if (OriginalDecl)
459 *OriginalDecl = nullptr;
460 return nullptr;
461}
462
463void ASTContext::cacheRawComment(RawCommentLookupKey Original,
464 const RawComment &Comment) const {
465 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
466 RawComments.try_emplace(Key: Original, Args: &Comment);
467 if (const auto *D = dyn_cast<const Decl *>(Val&: Original)) {
468 const Decl *const CanonicalDecl = D->getCanonicalDecl();
469 RedeclChainComments.try_emplace(Key: CanonicalDecl, Args&: D);
470 CommentlessRedeclChains.erase(Val: CanonicalDecl);
471 }
472}
473
474static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
475 SmallVectorImpl<const NamedDecl *> &Redeclared) {
476 const DeclContext *DC = ObjCMethod->getDeclContext();
477 if (const auto *IMD = dyn_cast<ObjCImplDecl>(Val: DC)) {
478 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
479 if (!ID)
480 return;
481 // Add redeclared method here.
482 for (const auto *Ext : ID->known_extensions()) {
483 if (ObjCMethodDecl *RedeclaredMethod =
484 Ext->getMethod(Sel: ObjCMethod->getSelector(),
485 isInstance: ObjCMethod->isInstanceMethod()))
486 Redeclared.push_back(Elt: RedeclaredMethod);
487 }
488 }
489}
490
491void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
492 const Preprocessor *PP) {
493 if (Comments.empty() || Decls.empty())
494 return;
495
496 FileID File;
497 for (const Decl *D : Decls) {
498 if (D->isInvalidDecl())
499 continue;
500
501 D = &adjustDeclToTemplate(D: *D);
502 SourceLocation Loc = D->getLocation();
503 if (Loc.isValid()) {
504 // See if there are any new comments that are not attached to a decl.
505 // The location doesn't have to be precise - we care only about the file.
506 File = SourceMgr.getDecomposedLoc(Loc).first;
507 break;
508 }
509 }
510
511 if (File.isInvalid())
512 return;
513
514 auto CommentsInThisFile = Comments.getCommentsInFile(File);
515 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
516 CommentsInThisFile->rbegin()->second->isAttached())
517 return;
518
519 // There is at least one comment not attached to a decl.
520 // Maybe it should be attached to one of Decls?
521 //
522 // Note that this way we pick up not only comments that precede the
523 // declaration, but also comments that *follow* the declaration -- thanks to
524 // the lookahead in the lexer: we've consumed the semicolon and looked
525 // ahead through comments.
526 for (const Decl *D : Decls) {
527 assert(D);
528 if (D->isInvalidDecl())
529 continue;
530
531 D = &adjustDeclToTemplate(D: *D);
532
533 if (RawComments.count(Val: D) > 0)
534 continue;
535
536 const auto DeclLocs = getLocsForCommentSearch(Key: D, SourceMgr);
537
538 for (const auto DeclLoc : DeclLocs) {
539 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
540 continue;
541
542 if (RawComment *const DocComment =
543 getRawCommentNoCacheImpl(Key: D, RepresentativeLoc: DeclLoc, CommentsInTheFile: *CommentsInThisFile)) {
544 cacheRawComment(Original: D, Comment: *DocComment);
545 comments::FullComment *FC = DocComment->parse(Context: *this, PP, D);
546 ParsedComments[D->getCanonicalDecl()] = FC;
547 break;
548 }
549 }
550 }
551}
552
553comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
554 const Decl *D) const {
555 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
556 ThisDeclInfo->CommentDecl = D;
557 ThisDeclInfo->IsFilled = false;
558 ThisDeclInfo->fill();
559 ThisDeclInfo->CommentDecl = FC->getDecl();
560 if (!ThisDeclInfo->TemplateParameters)
561 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
562 comments::FullComment *CFC =
563 new (*this) comments::FullComment(FC->getBlocks(),
564 ThisDeclInfo);
565 return CFC;
566}
567
568comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
569 const RawComment *RC = getRawCommentNoCache(Key: D);
570 return RC ? RC->parse(Context: *this, PP: nullptr, D) : nullptr;
571}
572
573comments::FullComment *ASTContext::getCommentForDecl(
574 const Decl *D,
575 const Preprocessor *PP) const {
576 if (!D || D->isInvalidDecl())
577 return nullptr;
578 D = &adjustDeclToTemplate(D: *D);
579
580 const Decl *Canonical = D->getCanonicalDecl();
581 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
582 ParsedComments.find(Val: Canonical);
583
584 if (Pos != ParsedComments.end()) {
585 if (Canonical != D) {
586 comments::FullComment *FC = Pos->second;
587 comments::FullComment *CFC = cloneFullComment(FC, D);
588 return CFC;
589 }
590 return Pos->second;
591 }
592
593 const Decl *OriginalDecl = nullptr;
594
595 const RawComment *RC = getRawCommentForAnyRedecl(Key: D, OriginalDecl: &OriginalDecl);
596 if (!RC) {
597 if (isa<ObjCMethodDecl>(Val: D) || isa<FunctionDecl>(Val: D)) {
598 SmallVector<const NamedDecl*, 8> Overridden;
599 const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D);
600 if (OMD && OMD->isPropertyAccessor())
601 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
602 if (comments::FullComment *FC = getCommentForDecl(D: PDecl, PP))
603 return cloneFullComment(FC, D);
604 if (OMD)
605 addRedeclaredMethods(ObjCMethod: OMD, Redeclared&: Overridden);
606 getOverriddenMethods(Method: dyn_cast<NamedDecl>(Val: D), Overridden);
607 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
608 if (comments::FullComment *FC = getCommentForDecl(D: Overridden[i], PP))
609 return cloneFullComment(FC, D);
610 }
611 else if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
612 // Attach any tag type's documentation to its typedef if latter
613 // does not have one of its own.
614 QualType QT = TD->getUnderlyingType();
615 if (const auto *TT = QT->getAs<TagType>())
616 if (comments::FullComment *FC = getCommentForDecl(D: TT->getDecl(), PP))
617 return cloneFullComment(FC, D);
618 }
619 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(Val: D)) {
620 while (IC->getSuperClass()) {
621 IC = IC->getSuperClass();
622 if (comments::FullComment *FC = getCommentForDecl(D: IC, PP))
623 return cloneFullComment(FC, D);
624 }
625 }
626 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(Val: D)) {
627 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
628 if (comments::FullComment *FC = getCommentForDecl(D: IC, PP))
629 return cloneFullComment(FC, D);
630 }
631 else if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
632 if (!(RD = RD->getDefinition()))
633 return nullptr;
634 // Check non-virtual bases.
635 for (const auto &I : RD->bases()) {
636 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
637 continue;
638 QualType Ty = I.getType();
639 if (Ty.isNull())
640 continue;
641 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
642 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
643 continue;
644
645 if (comments::FullComment *FC = getCommentForDecl(D: (NonVirtualBase), PP))
646 return cloneFullComment(FC, D);
647 }
648 }
649 // Check virtual bases.
650 for (const auto &I : RD->vbases()) {
651 if (I.getAccessSpecifier() != AS_public)
652 continue;
653 QualType Ty = I.getType();
654 if (Ty.isNull())
655 continue;
656 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
657 if (!(VirtualBase= VirtualBase->getDefinition()))
658 continue;
659 if (comments::FullComment *FC = getCommentForDecl(D: (VirtualBase), PP))
660 return cloneFullComment(FC, D);
661 }
662 }
663 }
664 return nullptr;
665 }
666
667 // If the RawComment was attached to other redeclaration of this Decl, we
668 // should parse the comment in context of that other Decl. This is important
669 // because comments can contain references to parameter names which can be
670 // different across redeclarations.
671 if (D != OriginalDecl && OriginalDecl)
672 return getCommentForDecl(D: OriginalDecl, PP);
673
674 comments::FullComment *FC = RC->parse(Context: *this, PP, D);
675 ParsedComments[Canonical] = FC;
676 return FC;
677}
678
679void ASTContext::CanonicalTemplateTemplateParm::Profile(
680 llvm::FoldingSetNodeID &ID, const ASTContext &C,
681 TemplateTemplateParmDecl *Parm) {
682 ID.AddInteger(I: Parm->getDepth());
683 ID.AddInteger(I: Parm->getPosition());
684 ID.AddBoolean(B: Parm->isParameterPack());
685 ID.AddInteger(I: Parm->templateParameterKind());
686
687 TemplateParameterList *Params = Parm->getTemplateParameters();
688 ID.AddInteger(I: Params->size());
689 for (TemplateParameterList::const_iterator P = Params->begin(),
690 PEnd = Params->end();
691 P != PEnd; ++P) {
692 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *P)) {
693 ID.AddInteger(I: 0);
694 ID.AddBoolean(B: TTP->isParameterPack());
695 ID.AddInteger(
696 I: TTP->getNumExpansionParameters().toInternalRepresentation());
697 continue;
698 }
699
700 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: *P)) {
701 ID.AddInteger(I: 1);
702 ID.AddBoolean(B: NTTP->isParameterPack());
703 ID.AddPointer(Ptr: C.getUnconstrainedType(T: C.getCanonicalType(T: NTTP->getType()))
704 .getAsOpaquePtr());
705 if (NTTP->isExpandedParameterPack()) {
706 ID.AddBoolean(B: true);
707 ID.AddInteger(I: NTTP->getNumExpansionTypes());
708 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
709 QualType T = NTTP->getExpansionType(I);
710 ID.AddPointer(Ptr: T.getCanonicalType().getAsOpaquePtr());
711 }
712 } else
713 ID.AddBoolean(B: false);
714 continue;
715 }
716
717 auto *TTP = cast<TemplateTemplateParmDecl>(Val: *P);
718 ID.AddInteger(I: 2);
719 Profile(ID, C, Parm: TTP);
720 }
721}
722
723TemplateTemplateParmDecl *
724ASTContext::getCanonicalTemplateTemplateParmDecl(
725 TemplateTemplateParmDecl *TTP) const {
726 // Check if we already have a canonical template template parameter.
727 llvm::FoldingSetNodeID ID;
728 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: TTP);
729 void *InsertPos = nullptr;
730 CanonicalTemplateTemplateParm *Canonical
731 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
732 if (Canonical)
733 return Canonical->getParam();
734
735 // Build a canonical template parameter list.
736 TemplateParameterList *Params = TTP->getTemplateParameters();
737 SmallVector<NamedDecl *, 4> CanonParams;
738 CanonParams.reserve(N: Params->size());
739 for (TemplateParameterList::const_iterator P = Params->begin(),
740 PEnd = Params->end();
741 P != PEnd; ++P) {
742 // Note that, per C++20 [temp.over.link]/6, when determining whether
743 // template-parameters are equivalent, constraints are ignored.
744 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *P)) {
745 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(
746 C: *this, DC: getTranslationUnitDecl(), KeyLoc: SourceLocation(), NameLoc: SourceLocation(),
747 D: TTP->getDepth(), P: TTP->getIndex(), Id: nullptr, Typename: false,
748 ParameterPack: TTP->isParameterPack(), /*HasTypeConstraint=*/false,
749 NumExpanded: TTP->getNumExpansionParameters());
750 CanonParams.push_back(Elt: NewTTP);
751 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: *P)) {
752 QualType T = getUnconstrainedType(T: getCanonicalType(T: NTTP->getType()));
753 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
754 NonTypeTemplateParmDecl *Param;
755 if (NTTP->isExpandedParameterPack()) {
756 SmallVector<QualType, 2> ExpandedTypes;
757 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
758 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
759 ExpandedTypes.push_back(Elt: getCanonicalType(T: NTTP->getExpansionType(I)));
760 ExpandedTInfos.push_back(
761 Elt: getTrivialTypeSourceInfo(T: ExpandedTypes.back()));
762 }
763
764 Param = NonTypeTemplateParmDecl::Create(C: *this, DC: getTranslationUnitDecl(),
765 StartLoc: SourceLocation(),
766 IdLoc: SourceLocation(),
767 D: NTTP->getDepth(),
768 P: NTTP->getPosition(), Id: nullptr,
769 T,
770 TInfo,
771 ExpandedTypes,
772 ExpandedTInfos);
773 } else {
774 Param = NonTypeTemplateParmDecl::Create(C: *this, DC: getTranslationUnitDecl(),
775 StartLoc: SourceLocation(),
776 IdLoc: SourceLocation(),
777 D: NTTP->getDepth(),
778 P: NTTP->getPosition(), Id: nullptr,
779 T,
780 ParameterPack: NTTP->isParameterPack(),
781 TInfo);
782 }
783 CanonParams.push_back(Elt: Param);
784 } else
785 CanonParams.push_back(Elt: getCanonicalTemplateTemplateParmDecl(
786 TTP: cast<TemplateTemplateParmDecl>(Val: *P)));
787 }
788
789 TemplateTemplateParmDecl *CanonTTP = TemplateTemplateParmDecl::Create(
790 C: *this, DC: getTranslationUnitDecl(), L: SourceLocation(), D: TTP->getDepth(),
791 P: TTP->getPosition(), ParameterPack: TTP->isParameterPack(), Id: nullptr,
792 ParameterKind: TTP->templateParameterKind(),
793 /*Typename=*/false,
794 Params: TemplateParameterList::Create(C: *this, TemplateLoc: SourceLocation(), LAngleLoc: SourceLocation(),
795 Params: CanonParams, RAngleLoc: SourceLocation(),
796 /*RequiresClause=*/nullptr));
797
798 // Get the new insert position for the node we care about.
799 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
800 assert(!Canonical && "Shouldn't be in the map!");
801 (void)Canonical;
802
803 // Create the canonical template template parameter entry.
804 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
805 CanonTemplateTemplateParms.InsertNode(N: Canonical, InsertPos);
806 return CanonTTP;
807}
808
809TemplateTemplateParmDecl *
810ASTContext::findCanonicalTemplateTemplateParmDeclInternal(
811 TemplateTemplateParmDecl *TTP) const {
812 llvm::FoldingSetNodeID ID;
813 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: TTP);
814 void *InsertPos = nullptr;
815 CanonicalTemplateTemplateParm *Canonical =
816 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
817 return Canonical ? Canonical->getParam() : nullptr;
818}
819
820TemplateTemplateParmDecl *
821ASTContext::insertCanonicalTemplateTemplateParmDeclInternal(
822 TemplateTemplateParmDecl *CanonTTP) const {
823 llvm::FoldingSetNodeID ID;
824 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: CanonTTP);
825 void *InsertPos = nullptr;
826 if (auto *Existing =
827 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos))
828 return Existing->getParam();
829 CanonTemplateTemplateParms.InsertNode(
830 N: new (*this) CanonicalTemplateTemplateParm(CanonTTP), InsertPos);
831 return CanonTTP;
832}
833
834/// For the purposes of overflow pattern exclusion, does this match the
835/// while(i--) pattern?
836static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx) {
837 if (UO->getOpcode() != UO_PostDec)
838 return false;
839
840 if (!UO->getType()->isUnsignedIntegerType())
841 return false;
842
843 // -fsanitize-undefined-ignore-overflow-pattern=unsigned-post-decr-while
844 if (!Ctx.getLangOpts().isOverflowPatternExcluded(
845 Kind: LangOptions::OverflowPatternExclusionKind::PostDecrInWhile))
846 return false;
847
848 // all Parents (usually just one) must be a WhileStmt
849 return llvm::all_of(
850 Range: Ctx.getParentMapContext().getParents(Node: *UO),
851 P: [](const DynTypedNode &P) { return P.get<WhileStmt>() != nullptr; });
852}
853
854bool ASTContext::isUnaryOverflowPatternExcluded(const UnaryOperator *UO) {
855 // -fsanitize-undefined-ignore-overflow-pattern=negated-unsigned-const
856 // ... like -1UL;
857 if (UO->getOpcode() == UO_Minus &&
858 getLangOpts().isOverflowPatternExcluded(
859 Kind: LangOptions::OverflowPatternExclusionKind::NegUnsignedConst) &&
860 UO->isIntegerConstantExpr(Ctx: *this)) {
861 return true;
862 }
863
864 if (matchesPostDecrInWhile(UO, Ctx&: *this))
865 return true;
866
867 return false;
868}
869
870/// Check if a type can have its sanitizer instrumentation elided based on its
871/// presence within an ignorelist.
872bool ASTContext::isTypeIgnoredBySanitizer(const SanitizerMask &Mask,
873 const QualType &Ty) const {
874 std::string TyName = Ty.getUnqualifiedType().getAsString(Policy: getPrintingPolicy());
875 return NoSanitizeL->containsType(Mask, MangledTypeName: TyName);
876}
877
878TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
879 auto Kind = getTargetInfo().getCXXABI().getKind();
880 return getLangOpts().CXXABI.value_or(u&: Kind);
881}
882
883CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
884 if (!LangOpts.CPlusPlus) return nullptr;
885
886 switch (getCXXABIKind()) {
887 case TargetCXXABI::AppleARM64:
888 case TargetCXXABI::Fuchsia:
889 case TargetCXXABI::GenericARM: // Same as Itanium at this level
890 case TargetCXXABI::iOS:
891 case TargetCXXABI::WatchOS:
892 case TargetCXXABI::GenericAArch64:
893 case TargetCXXABI::GenericMIPS:
894 case TargetCXXABI::GenericItanium:
895 case TargetCXXABI::WebAssembly:
896 case TargetCXXABI::XL:
897 return CreateItaniumCXXABI(Ctx&: *this);
898 case TargetCXXABI::Microsoft:
899 return CreateMicrosoftCXXABI(Ctx&: *this);
900 }
901 llvm_unreachable("Invalid CXXABI type!");
902}
903
904interp::Context &ASTContext::getInterpContext() const {
905 if (!InterpContext) {
906 InterpContext.reset(p: new interp::Context(const_cast<ASTContext &>(*this)));
907 }
908 return *InterpContext;
909}
910
911ParentMapContext &ASTContext::getParentMapContext() {
912 if (!ParentMapCtx)
913 ParentMapCtx.reset(p: new ParentMapContext(*this));
914 return *ParentMapCtx;
915}
916
917static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
918 const LangOptions &LangOpts) {
919 switch (LangOpts.getAddressSpaceMapMangling()) {
920 case LangOptions::ASMM_Target:
921 return TI.useAddressSpaceMapMangling();
922 case LangOptions::ASMM_On:
923 return true;
924 case LangOptions::ASMM_Off:
925 return false;
926 }
927 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
928}
929
930ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
931 IdentifierTable &idents, SelectorTable &sels,
932 Builtin::Context &builtins, TranslationUnitKind TUKind)
933 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
934 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
935 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
936 DependentSizedMatrixTypes(this_()),
937 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
938 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
939 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
940 AttributedTypes(this_()), DependentBitIntTypes(this_()),
941 SubstTemplateTemplateParmPacks(this_()), DeducedTemplates(this_()),
942 ArrayParameterTypes(this_()), CanonTemplateTemplateParms(this_()),
943 SourceMgr(SM), LangOpts(LOpts),
944 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
945 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
946 LangOpts.XRayNeverInstrumentFiles,
947 LangOpts.XRayAttrListFiles, SM)),
948 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
949 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
950 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
951 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
952 CompCategories(this_()), LastSDM(nullptr, 0) {
953 addTranslationUnitDecl();
954}
955
956void ASTContext::cleanup() {
957 // Release the DenseMaps associated with DeclContext objects.
958 // FIXME: Is this the ideal solution?
959 ReleaseDeclContextMaps();
960
961 // Call all of the deallocation functions on all of their targets.
962 for (auto &Pair : Deallocations)
963 (Pair.first)(Pair.second);
964 Deallocations.clear();
965
966 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
967 // because they can contain DenseMaps.
968 for (llvm::DenseMap<const ObjCInterfaceDecl *,
969 const ASTRecordLayout *>::iterator
970 I = ObjCLayouts.begin(),
971 E = ObjCLayouts.end();
972 I != E;)
973 // Increment in loop to prevent using deallocated memory.
974 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
975 R->Destroy(Ctx&: *this);
976 ObjCLayouts.clear();
977
978 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
979 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
980 // Increment in loop to prevent using deallocated memory.
981 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
982 R->Destroy(Ctx&: *this);
983 }
984 ASTRecordLayouts.clear();
985
986 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
987 AEnd = DeclAttrs.end();
988 A != AEnd; ++A)
989 A->second->~AttrVec();
990 DeclAttrs.clear();
991
992 CtorClosureDefaultArgs.clear();
993
994 for (const auto &Value : ModuleInitializers)
995 Value.second->~PerModuleInitializers();
996 ModuleInitializers.clear();
997
998 TUDecl = nullptr;
999 XRayFilter.reset();
1000 NoSanitizeL.reset();
1001}
1002
1003ASTContext::~ASTContext() { cleanup(); }
1004
1005void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1006 TraversalScope = TopLevelDecls;
1007 getParentMapContext().clear();
1008}
1009
1010void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1011 Deallocations.push_back(Elt: {Callback, Data});
1012}
1013
1014void
1015ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1016 ExternalSource = std::move(Source);
1017}
1018
1019void ASTContext::PrintStats() const {
1020 llvm::errs() << "\n*** AST Context Stats:\n";
1021 llvm::errs() << " " << Types.size() << " types total.\n";
1022
1023 unsigned counts[] = {
1024#define TYPE(Name, Parent) 0,
1025#define ABSTRACT_TYPE(Name, Parent)
1026#include "clang/AST/TypeNodes.inc"
1027 0 // Extra
1028 };
1029
1030 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1031 Type *T = Types[i];
1032 counts[(unsigned)T->getTypeClass()]++;
1033 }
1034
1035 unsigned Idx = 0;
1036 unsigned TotalBytes = 0;
1037#define TYPE(Name, Parent) \
1038 if (counts[Idx]) \
1039 llvm::errs() << " " << counts[Idx] << " " << #Name \
1040 << " types, " << sizeof(Name##Type) << " each " \
1041 << "(" << counts[Idx] * sizeof(Name##Type) \
1042 << " bytes)\n"; \
1043 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1044 ++Idx;
1045#define ABSTRACT_TYPE(Name, Parent)
1046#include "clang/AST/TypeNodes.inc"
1047
1048 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1049
1050 // Implicit special member functions.
1051 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1052 << NumImplicitDefaultConstructors
1053 << " implicit default constructors created\n";
1054 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1055 << NumImplicitCopyConstructors
1056 << " implicit copy constructors created\n";
1057 if (getLangOpts().CPlusPlus)
1058 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1059 << NumImplicitMoveConstructors
1060 << " implicit move constructors created\n";
1061 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1062 << NumImplicitCopyAssignmentOperators
1063 << " implicit copy assignment operators created\n";
1064 if (getLangOpts().CPlusPlus)
1065 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1066 << NumImplicitMoveAssignmentOperators
1067 << " implicit move assignment operators created\n";
1068 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1069 << NumImplicitDestructors
1070 << " implicit destructors created\n";
1071
1072 if (ExternalSource) {
1073 llvm::errs() << "\n";
1074 ExternalSource->PrintStats();
1075 }
1076
1077 BumpAlloc.PrintStats();
1078}
1079
1080void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1081 bool NotifyListeners) {
1082 if (NotifyListeners)
1083 if (auto *Listener = getASTMutationListener();
1084 Listener && !ND->isUnconditionallyVisible())
1085 Listener->RedefinedHiddenDefinition(D: ND, M);
1086
1087 MergedDefModules[cast<NamedDecl>(Val: ND->getCanonicalDecl())].push_back(NewVal: M);
1088}
1089
1090void ASTContext::deduplicateMergedDefinitionsFor(NamedDecl *ND) {
1091 auto It = MergedDefModules.find(Val: cast<NamedDecl>(Val: ND->getCanonicalDecl()));
1092 if (It == MergedDefModules.end())
1093 return;
1094
1095 auto &Merged = It->second;
1096 llvm::DenseSet<Module*> Found;
1097 for (Module *&M : Merged)
1098 if (!Found.insert(V: M).second)
1099 M = nullptr;
1100 llvm::erase(C&: Merged, V: nullptr);
1101}
1102
1103ArrayRef<Module *>
1104ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1105 auto MergedIt =
1106 MergedDefModules.find(Val: cast<NamedDecl>(Val: Def->getCanonicalDecl()));
1107 if (MergedIt == MergedDefModules.end())
1108 return {};
1109 return MergedIt->second;
1110}
1111
1112void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1113 if (LazyInitializers.empty())
1114 return;
1115
1116 auto *Source = Ctx.getExternalSource();
1117 assert(Source && "lazy initializers but no external source");
1118
1119 auto LazyInits = std::move(LazyInitializers);
1120 LazyInitializers.clear();
1121
1122 for (auto ID : LazyInits)
1123 Initializers.push_back(Elt: Source->GetExternalDecl(ID));
1124
1125 assert(LazyInitializers.empty() &&
1126 "GetExternalDecl for lazy module initializer added more inits");
1127}
1128
1129void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1130 // One special case: if we add a module initializer that imports another
1131 // module, and that module's only initializer is an ImportDecl, simplify.
1132 if (const auto *ID = dyn_cast<ImportDecl>(Val: D)) {
1133 auto It = ModuleInitializers.find(Val: ID->getImportedModule());
1134
1135 // Maybe the ImportDecl does nothing at all. (Common case.)
1136 if (It == ModuleInitializers.end())
1137 return;
1138
1139 // Maybe the ImportDecl only imports another ImportDecl.
1140 auto &Imported = *It->second;
1141 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1142 Imported.resolve(Ctx&: *this);
1143 auto *OnlyDecl = Imported.Initializers.front();
1144 if (isa<ImportDecl>(Val: OnlyDecl))
1145 D = OnlyDecl;
1146 }
1147 }
1148
1149 auto *&Inits = ModuleInitializers[M];
1150 if (!Inits)
1151 Inits = new (*this) PerModuleInitializers;
1152 Inits->Initializers.push_back(Elt: D);
1153}
1154
1155void ASTContext::addLazyModuleInitializers(Module *M,
1156 ArrayRef<GlobalDeclID> IDs) {
1157 auto *&Inits = ModuleInitializers[M];
1158 if (!Inits)
1159 Inits = new (*this) PerModuleInitializers;
1160 Inits->LazyInitializers.insert(I: Inits->LazyInitializers.end(),
1161 From: IDs.begin(), To: IDs.end());
1162}
1163
1164ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1165 auto It = ModuleInitializers.find(Val: M);
1166 if (It == ModuleInitializers.end())
1167 return {};
1168
1169 auto *Inits = It->second;
1170 Inits->resolve(Ctx&: *this);
1171 return Inits->Initializers;
1172}
1173
1174void ASTContext::setCurrentNamedModule(Module *M) {
1175 assert(M->isNamedModule());
1176 assert(!CurrentCXXNamedModule &&
1177 "We should set named module for ASTContext for only once");
1178 CurrentCXXNamedModule = M;
1179}
1180
1181bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1182 if (!M1 != !M2)
1183 return false;
1184
1185 /// Get the representative module for M. The representative module is the
1186 /// first module unit for a specific primary module name. So that the module
1187 /// units have the same representative module belongs to the same module.
1188 ///
1189 /// The process is helpful to reduce the expensive string operations.
1190 auto GetRepresentativeModule = [this](const Module *M) {
1191 auto Iter = SameModuleLookupSet.find(Val: M);
1192 if (Iter != SameModuleLookupSet.end())
1193 return Iter->second;
1194
1195 const Module *RepresentativeModule =
1196 PrimaryModuleNameMap.try_emplace(Key: M->getPrimaryModuleInterfaceName(), Args&: M)
1197 .first->second;
1198 SameModuleLookupSet[M] = RepresentativeModule;
1199 return RepresentativeModule;
1200 };
1201
1202 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1203 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1204}
1205
1206ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1207 if (!ExternCContext)
1208 ExternCContext = ExternCContextDecl::Create(C: *this, TU: getTranslationUnitDecl());
1209
1210 return ExternCContext;
1211}
1212
1213BuiltinTemplateDecl *
1214ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1215 const IdentifierInfo *II) const {
1216 auto *BuiltinTemplate =
1217 BuiltinTemplateDecl::Create(C: *this, DC: getTranslationUnitDecl(), Name: II, BTK);
1218 BuiltinTemplate->setImplicit();
1219 getTranslationUnitDecl()->addDecl(D: BuiltinTemplate);
1220
1221 return BuiltinTemplate;
1222}
1223
1224#define BuiltinTemplate(BTName) \
1225 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1226 if (!Decl##BTName) \
1227 Decl##BTName = \
1228 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1229 return Decl##BTName; \
1230 }
1231#include "clang/Basic/BuiltinTemplates.inc"
1232
1233RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1234 RecordDecl::TagKind TK) const {
1235 SourceLocation Loc;
1236 RecordDecl *NewDecl;
1237 if (getLangOpts().CPlusPlus)
1238 NewDecl = CXXRecordDecl::Create(C: *this, TK, DC: getTranslationUnitDecl(), StartLoc: Loc,
1239 IdLoc: Loc, Id: &Idents.get(Name));
1240 else
1241 NewDecl = RecordDecl::Create(C: *this, TK, DC: getTranslationUnitDecl(), StartLoc: Loc, IdLoc: Loc,
1242 Id: &Idents.get(Name));
1243 NewDecl->setImplicit();
1244 NewDecl->addAttr(A: TypeVisibilityAttr::CreateImplicit(
1245 Ctx&: const_cast<ASTContext &>(*this), Visibility: TypeVisibilityAttr::Default));
1246 return NewDecl;
1247}
1248
1249TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1250 StringRef Name) const {
1251 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1252 TypedefDecl *NewDecl = TypedefDecl::Create(
1253 C&: const_cast<ASTContext &>(*this), DC: getTranslationUnitDecl(),
1254 StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: &Idents.get(Name), TInfo);
1255 NewDecl->setImplicit();
1256 return NewDecl;
1257}
1258
1259TypedefDecl *ASTContext::getInt128Decl() const {
1260 if (!Int128Decl)
1261 Int128Decl = buildImplicitTypedef(T: Int128Ty, Name: "__int128_t");
1262 return Int128Decl;
1263}
1264
1265TypedefDecl *ASTContext::getUInt128Decl() const {
1266 if (!UInt128Decl)
1267 UInt128Decl = buildImplicitTypedef(T: UnsignedInt128Ty, Name: "__uint128_t");
1268 return UInt128Decl;
1269}
1270
1271void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1272 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1273 R = CanQualType::CreateUnsafe(Other: QualType(Ty, 0));
1274 Types.push_back(Elt: Ty);
1275}
1276
1277void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1278 const TargetInfo *AuxTarget) {
1279 assert((!this->Target || this->Target == &Target) &&
1280 "Incorrect target reinitialization");
1281 assert(VoidTy.isNull() && "Context reinitialized?");
1282
1283 this->Target = &Target;
1284 this->AuxTarget = AuxTarget;
1285
1286 ABI.reset(p: createCXXABI(T: Target));
1287 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(TI: Target, LangOpts);
1288
1289 // C99 6.2.5p19.
1290 InitBuiltinType(R&: VoidTy, K: BuiltinType::Void);
1291
1292 // C99 6.2.5p2.
1293 InitBuiltinType(R&: BoolTy, K: BuiltinType::Bool);
1294 // C99 6.2.5p3.
1295 if (LangOpts.CharIsSigned)
1296 InitBuiltinType(R&: CharTy, K: BuiltinType::Char_S);
1297 else
1298 InitBuiltinType(R&: CharTy, K: BuiltinType::Char_U);
1299 // C99 6.2.5p4.
1300 InitBuiltinType(R&: SignedCharTy, K: BuiltinType::SChar);
1301 InitBuiltinType(R&: ShortTy, K: BuiltinType::Short);
1302 InitBuiltinType(R&: IntTy, K: BuiltinType::Int);
1303 InitBuiltinType(R&: LongTy, K: BuiltinType::Long);
1304 InitBuiltinType(R&: LongLongTy, K: BuiltinType::LongLong);
1305
1306 // C99 6.2.5p6.
1307 InitBuiltinType(R&: UnsignedCharTy, K: BuiltinType::UChar);
1308 InitBuiltinType(R&: UnsignedShortTy, K: BuiltinType::UShort);
1309 InitBuiltinType(R&: UnsignedIntTy, K: BuiltinType::UInt);
1310 InitBuiltinType(R&: UnsignedLongTy, K: BuiltinType::ULong);
1311 InitBuiltinType(R&: UnsignedLongLongTy, K: BuiltinType::ULongLong);
1312
1313 // C99 6.2.5p10.
1314 InitBuiltinType(R&: FloatTy, K: BuiltinType::Float);
1315 InitBuiltinType(R&: DoubleTy, K: BuiltinType::Double);
1316 InitBuiltinType(R&: LongDoubleTy, K: BuiltinType::LongDouble);
1317
1318 // GNU extension, __float128 for IEEE quadruple precision
1319 InitBuiltinType(R&: Float128Ty, K: BuiltinType::Float128);
1320
1321 // __ibm128 for IBM extended precision
1322 InitBuiltinType(R&: Ibm128Ty, K: BuiltinType::Ibm128);
1323
1324 // C11 extension ISO/IEC TS 18661-3
1325 InitBuiltinType(R&: Float16Ty, K: BuiltinType::Float16);
1326
1327 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1328 InitBuiltinType(R&: ShortAccumTy, K: BuiltinType::ShortAccum);
1329 InitBuiltinType(R&: AccumTy, K: BuiltinType::Accum);
1330 InitBuiltinType(R&: LongAccumTy, K: BuiltinType::LongAccum);
1331 InitBuiltinType(R&: UnsignedShortAccumTy, K: BuiltinType::UShortAccum);
1332 InitBuiltinType(R&: UnsignedAccumTy, K: BuiltinType::UAccum);
1333 InitBuiltinType(R&: UnsignedLongAccumTy, K: BuiltinType::ULongAccum);
1334 InitBuiltinType(R&: ShortFractTy, K: BuiltinType::ShortFract);
1335 InitBuiltinType(R&: FractTy, K: BuiltinType::Fract);
1336 InitBuiltinType(R&: LongFractTy, K: BuiltinType::LongFract);
1337 InitBuiltinType(R&: UnsignedShortFractTy, K: BuiltinType::UShortFract);
1338 InitBuiltinType(R&: UnsignedFractTy, K: BuiltinType::UFract);
1339 InitBuiltinType(R&: UnsignedLongFractTy, K: BuiltinType::ULongFract);
1340 InitBuiltinType(R&: SatShortAccumTy, K: BuiltinType::SatShortAccum);
1341 InitBuiltinType(R&: SatAccumTy, K: BuiltinType::SatAccum);
1342 InitBuiltinType(R&: SatLongAccumTy, K: BuiltinType::SatLongAccum);
1343 InitBuiltinType(R&: SatUnsignedShortAccumTy, K: BuiltinType::SatUShortAccum);
1344 InitBuiltinType(R&: SatUnsignedAccumTy, K: BuiltinType::SatUAccum);
1345 InitBuiltinType(R&: SatUnsignedLongAccumTy, K: BuiltinType::SatULongAccum);
1346 InitBuiltinType(R&: SatShortFractTy, K: BuiltinType::SatShortFract);
1347 InitBuiltinType(R&: SatFractTy, K: BuiltinType::SatFract);
1348 InitBuiltinType(R&: SatLongFractTy, K: BuiltinType::SatLongFract);
1349 InitBuiltinType(R&: SatUnsignedShortFractTy, K: BuiltinType::SatUShortFract);
1350 InitBuiltinType(R&: SatUnsignedFractTy, K: BuiltinType::SatUFract);
1351 InitBuiltinType(R&: SatUnsignedLongFractTy, K: BuiltinType::SatULongFract);
1352
1353 // GNU extension, 128-bit integers.
1354 InitBuiltinType(R&: Int128Ty, K: BuiltinType::Int128);
1355 InitBuiltinType(R&: UnsignedInt128Ty, K: BuiltinType::UInt128);
1356
1357 // C++ 3.9.1p5
1358 if (TargetInfo::isTypeSigned(T: Target.getWCharType()))
1359 InitBuiltinType(R&: WCharTy, K: BuiltinType::WChar_S);
1360 else // -fshort-wchar makes wchar_t be unsigned.
1361 InitBuiltinType(R&: WCharTy, K: BuiltinType::WChar_U);
1362 if (LangOpts.CPlusPlus && LangOpts.WChar)
1363 WideCharTy = WCharTy;
1364 else {
1365 // C99 (or C++ using -fno-wchar).
1366 WideCharTy = getFromTargetType(Type: Target.getWCharType());
1367 }
1368
1369 WIntTy = getFromTargetType(Type: Target.getWIntType());
1370
1371 // C++20 (proposed)
1372 InitBuiltinType(R&: Char8Ty, K: BuiltinType::Char8);
1373
1374 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1375 InitBuiltinType(R&: Char16Ty, K: BuiltinType::Char16);
1376 else // C99
1377 Char16Ty = getFromTargetType(Type: Target.getChar16Type());
1378
1379 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1380 InitBuiltinType(R&: Char32Ty, K: BuiltinType::Char32);
1381 else // C99
1382 Char32Ty = getFromTargetType(Type: Target.getChar32Type());
1383
1384 // Placeholder type for type-dependent expressions whose type is
1385 // completely unknown. No code should ever check a type against
1386 // DependentTy and users should never see it; however, it is here to
1387 // help diagnose failures to properly check for type-dependent
1388 // expressions.
1389 InitBuiltinType(R&: DependentTy, K: BuiltinType::Dependent);
1390
1391 // Placeholder type for functions.
1392 InitBuiltinType(R&: OverloadTy, K: BuiltinType::Overload);
1393
1394 // Placeholder type for bound members.
1395 InitBuiltinType(R&: BoundMemberTy, K: BuiltinType::BoundMember);
1396
1397 // Placeholder type for unresolved templates.
1398 InitBuiltinType(R&: UnresolvedTemplateTy, K: BuiltinType::UnresolvedTemplate);
1399
1400 // Placeholder type for pseudo-objects.
1401 InitBuiltinType(R&: PseudoObjectTy, K: BuiltinType::PseudoObject);
1402
1403 // "any" type; useful for debugger-like clients.
1404 InitBuiltinType(R&: UnknownAnyTy, K: BuiltinType::UnknownAny);
1405
1406 // Placeholder type for unbridged ARC casts.
1407 InitBuiltinType(R&: ARCUnbridgedCastTy, K: BuiltinType::ARCUnbridgedCast);
1408
1409 // Placeholder type for builtin functions.
1410 InitBuiltinType(R&: BuiltinFnTy, K: BuiltinType::BuiltinFn);
1411
1412 // Placeholder type for OMP array sections.
1413 if (LangOpts.OpenMP) {
1414 InitBuiltinType(R&: ArraySectionTy, K: BuiltinType::ArraySection);
1415 InitBuiltinType(R&: OMPArrayShapingTy, K: BuiltinType::OMPArrayShaping);
1416 InitBuiltinType(R&: OMPIteratorTy, K: BuiltinType::OMPIterator);
1417 }
1418 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1419 // don't bother, as we're just using the same type as OMP.
1420 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1421 InitBuiltinType(R&: ArraySectionTy, K: BuiltinType::ArraySection);
1422 }
1423 if (LangOpts.MatrixTypes)
1424 InitBuiltinType(R&: IncompleteMatrixIdxTy, K: BuiltinType::IncompleteMatrixIdx);
1425
1426 // Builtin types for 'id', 'Class', and 'SEL'.
1427 InitBuiltinType(R&: ObjCBuiltinIdTy, K: BuiltinType::ObjCId);
1428 InitBuiltinType(R&: ObjCBuiltinClassTy, K: BuiltinType::ObjCClass);
1429 InitBuiltinType(R&: ObjCBuiltinSelTy, K: BuiltinType::ObjCSel);
1430
1431 if (LangOpts.OpenCL) {
1432#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1433 InitBuiltinType(SingletonId, BuiltinType::Id);
1434#include "clang/Basic/OpenCLImageTypes.def"
1435
1436 InitBuiltinType(R&: OCLSamplerTy, K: BuiltinType::OCLSampler);
1437 InitBuiltinType(R&: OCLEventTy, K: BuiltinType::OCLEvent);
1438 InitBuiltinType(R&: OCLClkEventTy, K: BuiltinType::OCLClkEvent);
1439 InitBuiltinType(R&: OCLQueueTy, K: BuiltinType::OCLQueue);
1440 InitBuiltinType(R&: OCLReserveIDTy, K: BuiltinType::OCLReserveID);
1441
1442#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1443 InitBuiltinType(Id##Ty, BuiltinType::Id);
1444#include "clang/Basic/OpenCLExtensionTypes.def"
1445 }
1446
1447 if (LangOpts.HLSL) {
1448#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1449 InitBuiltinType(SingletonId, BuiltinType::Id);
1450#include "clang/Basic/HLSLIntangibleTypes.def"
1451 }
1452
1453 if (Target.hasAArch64ACLETypes() ||
1454 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1455#define SVE_TYPE(Name, Id, SingletonId) \
1456 InitBuiltinType(SingletonId, BuiltinType::Id);
1457#include "clang/Basic/AArch64ACLETypes.def"
1458 }
1459
1460 if (Target.getTriple().isPPC64()) {
1461#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1462 InitBuiltinType(Id##Ty, BuiltinType::Id);
1463#include "clang/Basic/PPCTypes.def"
1464#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1465 InitBuiltinType(Id##Ty, BuiltinType::Id);
1466#include "clang/Basic/PPCTypes.def"
1467 }
1468
1469 if (Target.hasRISCVVTypes()) {
1470#define RVV_TYPE(Name, Id, SingletonId) \
1471 InitBuiltinType(SingletonId, BuiltinType::Id);
1472#include "clang/Basic/RISCVVTypes.def"
1473 }
1474
1475 if (Target.getTriple().isWasm() && Target.hasFeature(Feature: "reference-types")) {
1476#define WASM_TYPE(Name, Id, SingletonId) \
1477 InitBuiltinType(SingletonId, BuiltinType::Id);
1478#include "clang/Basic/WebAssemblyReferenceTypes.def"
1479 }
1480
1481 if (Target.getTriple().isAMDGPU() ||
1482 (Target.getTriple().isSPIRV() &&
1483 Target.getTriple().getVendor() == llvm::Triple::AMD) ||
1484 (AuxTarget &&
1485 (AuxTarget->getTriple().isAMDGPU() ||
1486 ((AuxTarget->getTriple().isSPIRV() &&
1487 AuxTarget->getTriple().getVendor() == llvm::Triple::AMD))))) {
1488#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1489 InitBuiltinType(SingletonId, BuiltinType::Id);
1490#include "clang/Basic/AMDGPUTypes.def"
1491 }
1492
1493 // Builtin type for __objc_yes and __objc_no
1494 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1495 SignedCharTy : BoolTy);
1496
1497 ObjCConstantStringType = QualType();
1498
1499 ObjCSuperType = QualType();
1500
1501 // void * type
1502 if (LangOpts.OpenCLGenericAddressSpace) {
1503 auto Q = VoidTy.getQualifiers();
1504 Q.setAddressSpace(LangAS::opencl_generic);
1505 VoidPtrTy = getPointerType(T: getCanonicalType(
1506 T: getQualifiedType(T: VoidTy.getUnqualifiedType(), Qs: Q)));
1507 } else {
1508 VoidPtrTy = getPointerType(T: VoidTy);
1509 }
1510
1511 // nullptr type (C++0x 2.14.7)
1512 InitBuiltinType(R&: NullPtrTy, K: BuiltinType::NullPtr);
1513
1514 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1515 InitBuiltinType(R&: HalfTy, K: BuiltinType::Half);
1516
1517 InitBuiltinType(R&: BFloat16Ty, K: BuiltinType::BFloat16);
1518
1519 // Builtin type used to help define __builtin_va_list.
1520 VaListTagDecl = nullptr;
1521
1522 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1523 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1524 MSGuidTagDecl = buildImplicitRecord(Name: "_GUID");
1525 getTranslationUnitDecl()->addDecl(D: MSGuidTagDecl);
1526 }
1527}
1528
1529DiagnosticsEngine &ASTContext::getDiagnostics() const {
1530 return SourceMgr.getDiagnostics();
1531}
1532
1533AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1534 AttrVec *&Result = DeclAttrs[D];
1535 if (!Result) {
1536 void *Mem = Allocate(Size: sizeof(AttrVec));
1537 Result = new (Mem) AttrVec;
1538 }
1539
1540 return *Result;
1541}
1542
1543/// Erase the attributes corresponding to the given declaration.
1544void ASTContext::eraseDeclAttrs(const Decl *D) {
1545 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(Val: D);
1546 if (Pos != DeclAttrs.end()) {
1547 Pos->second->~AttrVec();
1548 DeclAttrs.erase(I: Pos);
1549 }
1550}
1551
1552ArrayRef<CXXDefaultArgExpr *>
1553ASTContext::getCtorClosureDefaultArgs(const CXXConstructorDecl *CD) {
1554 return CtorClosureDefaultArgs.lookup(Val: CD);
1555}
1556
1557void ASTContext::setCtorClosureDefaultArgs(const CXXConstructorDecl *CD,
1558 ArrayRef<CXXDefaultArgExpr *> Args) {
1559 assert(!CtorClosureDefaultArgs.contains(CD));
1560 CtorClosureDefaultArgs[CD] = Args;
1561}
1562
1563ArrayRef<ExplicitInstantiationDecl *>
1564ASTContext::getExplicitInstantiationDecls(const NamedDecl *Spec) const {
1565 auto It =
1566 ExplicitInstantiations.find(Val: cast<NamedDecl>(Val: Spec->getCanonicalDecl()));
1567 if (It != ExplicitInstantiations.end())
1568 return It->second;
1569 return {};
1570}
1571
1572void ASTContext::addExplicitInstantiationDecl(const NamedDecl *Spec,
1573 ExplicitInstantiationDecl *EID) {
1574 ExplicitInstantiations[cast<NamedDecl>(Val: Spec->getCanonicalDecl())].push_back(
1575 NewVal: EID);
1576}
1577
1578// FIXME: Remove ?
1579MemberSpecializationInfo *
1580ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1581 assert(Var->isStaticDataMember() && "Not a static data member");
1582 return getTemplateOrSpecializationInfo(Var)
1583 .dyn_cast<MemberSpecializationInfo *>();
1584}
1585
1586ASTContext::TemplateOrSpecializationInfo
1587ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1588 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1589 TemplateOrInstantiation.find(Val: Var);
1590 if (Pos == TemplateOrInstantiation.end())
1591 return {};
1592
1593 return Pos->second;
1594}
1595
1596void
1597ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1598 TemplateSpecializationKind TSK,
1599 SourceLocation PointOfInstantiation) {
1600 assert(Inst->isStaticDataMember() && "Not a static data member");
1601 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1602 setTemplateOrSpecializationInfo(Inst, TSI: new (*this) MemberSpecializationInfo(
1603 Tmpl, TSK, PointOfInstantiation));
1604}
1605
1606void
1607ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1608 TemplateOrSpecializationInfo TSI) {
1609 assert(!TemplateOrInstantiation[Inst] &&
1610 "Already noted what the variable was instantiated from");
1611 TemplateOrInstantiation[Inst] = TSI;
1612}
1613
1614NamedDecl *
1615ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1616 return InstantiatedFromUsingDecl.lookup(Val: UUD);
1617}
1618
1619void
1620ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1621 assert((isa<UsingDecl>(Pattern) ||
1622 isa<UnresolvedUsingValueDecl>(Pattern) ||
1623 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1624 "pattern decl is not a using decl");
1625 assert((isa<UsingDecl>(Inst) ||
1626 isa<UnresolvedUsingValueDecl>(Inst) ||
1627 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1628 "instantiation did not produce a using decl");
1629 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1630 InstantiatedFromUsingDecl[Inst] = Pattern;
1631}
1632
1633UsingEnumDecl *
1634ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) {
1635 return InstantiatedFromUsingEnumDecl.lookup(Val: UUD);
1636}
1637
1638void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
1639 UsingEnumDecl *Pattern) {
1640 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1641 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1642}
1643
1644UsingShadowDecl *
1645ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1646 return InstantiatedFromUsingShadowDecl.lookup(Val: Inst);
1647}
1648
1649void
1650ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1651 UsingShadowDecl *Pattern) {
1652 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1653 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1654}
1655
1656FieldDecl *
1657ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const {
1658 return InstantiatedFromUnnamedFieldDecl.lookup(Val: Field);
1659}
1660
1661void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1662 FieldDecl *Tmpl) {
1663 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1664 "Instantiated field decl is not unnamed");
1665 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1666 "Template field decl is not unnamed");
1667 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1668 "Already noted what unnamed field was instantiated from");
1669
1670 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1671}
1672
1673ASTContext::overridden_cxx_method_iterator
1674ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1675 return overridden_methods(Method).begin();
1676}
1677
1678ASTContext::overridden_cxx_method_iterator
1679ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1680 return overridden_methods(Method).end();
1681}
1682
1683unsigned
1684ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1685 auto Range = overridden_methods(Method);
1686 return Range.end() - Range.begin();
1687}
1688
1689ASTContext::overridden_method_range
1690ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1691 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1692 OverriddenMethods.find(Val: Method->getCanonicalDecl());
1693 if (Pos == OverriddenMethods.end())
1694 return overridden_method_range(nullptr, nullptr);
1695 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1696}
1697
1698void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1699 const CXXMethodDecl *Overridden) {
1700 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1701 OverriddenMethods[Method].push_back(NewVal: Overridden);
1702}
1703
1704void ASTContext::getOverriddenMethods(
1705 const NamedDecl *D,
1706 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1707 assert(D);
1708
1709 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(Val: D)) {
1710 Overridden.append(in_start: overridden_methods_begin(Method: CXXMethod),
1711 in_end: overridden_methods_end(Method: CXXMethod));
1712 return;
1713 }
1714
1715 const auto *Method = dyn_cast<ObjCMethodDecl>(Val: D);
1716 if (!Method)
1717 return;
1718
1719 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1720 Method->getOverriddenMethods(Overridden&: OverDecls);
1721 Overridden.append(in_start: OverDecls.begin(), in_end: OverDecls.end());
1722}
1723
1724std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1725ASTContext::getRelocationInfoForCXXRecord(const CXXRecordDecl *RD) const {
1726 assert(RD);
1727 CXXRecordDecl *D = RD->getDefinition();
1728 auto it = RelocatableClasses.find(Val: D);
1729 if (it != RelocatableClasses.end())
1730 return it->getSecond();
1731 return std::nullopt;
1732}
1733
1734void ASTContext::setRelocationInfoForCXXRecord(
1735 const CXXRecordDecl *RD, CXXRecordDeclRelocationInfo Info) {
1736 assert(RD);
1737 CXXRecordDecl *D = RD->getDefinition();
1738 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1739 RelocatableClasses.insert(KV: {D, Info});
1740}
1741
1742static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(
1743 const ASTContext &Context, const CXXRecordDecl *Class) {
1744 if (!Class->isPolymorphic())
1745 return false;
1746 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(ThisClass: Class);
1747 using AuthAttr = VTablePointerAuthenticationAttr;
1748 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1749 if (!ExplicitAuth)
1750 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1751 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1752 ExplicitAuth->getAddressDiscrimination();
1753 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1754 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1755 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1756}
1757
1758ASTContext::PointerAuthContent
1759ASTContext::findPointerAuthContent(QualType T) const {
1760 assert(isPointerAuthenticationAvailable());
1761
1762 T = T.getCanonicalType();
1763 if (T->isDependentType())
1764 return PointerAuthContent::None;
1765
1766 if (T.hasAddressDiscriminatedPointerAuth())
1767 return PointerAuthContent::AddressDiscriminatedData;
1768 const RecordDecl *RD = T->getAsRecordDecl();
1769 if (!RD)
1770 return PointerAuthContent::None;
1771
1772 if (RD->isInvalidDecl())
1773 return PointerAuthContent::None;
1774
1775 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(Val: RD);
1776 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1777 return Existing->second;
1778
1779 PointerAuthContent Result = PointerAuthContent::None;
1780
1781 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1782 auto [ResultIter, DidAdd] =
1783 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(Key: RD, Args&: Result);
1784 (void)ResultIter;
1785 (void)DidAdd;
1786 assert(DidAdd);
1787 return Result;
1788 };
1789 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1790 static_assert(PointerAuthContent::None <
1791 PointerAuthContent::AddressDiscriminatedVTable);
1792 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1793 PointerAuthContent::AddressDiscriminatedData);
1794 if (NewResult > Result)
1795 Result = NewResult;
1796 return Result != PointerAuthContent::AddressDiscriminatedData;
1797 };
1798 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
1799 if (primaryBaseHaseAddressDiscriminatedVTableAuthentication(Context: *this, Class: CXXRD) &&
1800 !ShouldContinueAfterUpdate(
1801 PointerAuthContent::AddressDiscriminatedVTable))
1802 return SaveResultAndReturn();
1803 for (auto Base : CXXRD->bases()) {
1804 if (!ShouldContinueAfterUpdate(findPointerAuthContent(T: Base.getType())))
1805 return SaveResultAndReturn();
1806 }
1807 }
1808 for (auto *FieldDecl : RD->fields()) {
1809 if (!ShouldContinueAfterUpdate(
1810 findPointerAuthContent(T: FieldDecl->getType())))
1811 return SaveResultAndReturn();
1812 }
1813 return SaveResultAndReturn();
1814}
1815
1816void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1817 assert(!Import->getNextLocalImport() &&
1818 "Import declaration already in the chain");
1819 assert(!Import->isFromASTFile() && "Non-local import declaration");
1820 if (!FirstLocalImport) {
1821 FirstLocalImport = Import;
1822 LastLocalImport = Import;
1823 return;
1824 }
1825
1826 LastLocalImport->setNextLocalImport(Import);
1827 LastLocalImport = Import;
1828}
1829
1830//===----------------------------------------------------------------------===//
1831// Type Sizing and Analysis
1832//===----------------------------------------------------------------------===//
1833
1834/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1835/// scalar floating point type.
1836const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1837 switch (T->castAs<BuiltinType>()->getKind()) {
1838 default:
1839 llvm_unreachable("Not a floating point type!");
1840 case BuiltinType::BFloat16:
1841 return Target->getBFloat16Format();
1842 case BuiltinType::Float16:
1843 return Target->getHalfFormat();
1844 case BuiltinType::Half:
1845 return Target->getHalfFormat();
1846 case BuiltinType::Float: return Target->getFloatFormat();
1847 case BuiltinType::Double: return Target->getDoubleFormat();
1848 case BuiltinType::Ibm128:
1849 return Target->getIbm128Format();
1850 case BuiltinType::LongDouble:
1851 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1852 return AuxTarget->getLongDoubleFormat();
1853 return Target->getLongDoubleFormat();
1854 case BuiltinType::Float128:
1855 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1856 return AuxTarget->getFloat128Format();
1857 return Target->getFloat128Format();
1858 }
1859}
1860
1861CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1862 unsigned Align = Target->getCharWidth();
1863
1864 const unsigned AlignFromAttr = D->getMaxAlignment();
1865 if (AlignFromAttr)
1866 Align = AlignFromAttr;
1867
1868 // __attribute__((aligned)) can increase or decrease alignment
1869 // *except* on a struct or struct member, where it only increases
1870 // alignment unless 'packed' is also specified.
1871 //
1872 // It is an error for alignas to decrease alignment, so we can
1873 // ignore that possibility; Sema should diagnose it.
1874 bool UseAlignAttrOnly;
1875 if (const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D))
1876 UseAlignAttrOnly =
1877 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1878 else
1879 UseAlignAttrOnly = AlignFromAttr != 0;
1880 // If we're using the align attribute only, just ignore everything
1881 // else about the declaration and its type.
1882 if (UseAlignAttrOnly) {
1883 // do nothing
1884 } else if (const auto *VD = dyn_cast<ValueDecl>(Val: D)) {
1885 QualType T = VD->getType();
1886 if (const auto *RT = T->getAs<ReferenceType>()) {
1887 if (ForAlignof)
1888 T = RT->getPointeeType();
1889 else
1890 T = getPointerType(T: RT->getPointeeType());
1891 }
1892 QualType BaseT = getBaseElementType(QT: T);
1893 if (T->isFunctionType())
1894 Align = getTypeInfoImpl(T: T.getTypePtr()).Align;
1895 else if (!BaseT->isIncompleteType()) {
1896 // Adjust alignments of declarations with array type by the
1897 // large-array alignment on the target.
1898 if (const ArrayType *arrayType = getAsArrayType(T)) {
1899 unsigned MinWidth = Target->getLargeArrayMinWidth();
1900 if (!ForAlignof && MinWidth) {
1901 if (isa<VariableArrayType>(Val: arrayType))
1902 Align = std::max(a: Align, b: Target->getLargeArrayAlign());
1903 else if (isa<ConstantArrayType>(Val: arrayType) &&
1904 MinWidth <= getTypeSize(T: cast<ConstantArrayType>(Val: arrayType)))
1905 Align = std::max(a: Align, b: Target->getLargeArrayAlign());
1906 }
1907 }
1908 Align = std::max(a: Align, b: getPreferredTypeAlign(T: T.getTypePtr()));
1909 if (BaseT.getQualifiers().hasUnaligned())
1910 Align = Target->getCharWidth();
1911 }
1912
1913 // Ensure minimum alignment for global variables.
1914 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
1915 if (VD->hasGlobalStorage() && !ForAlignof) {
1916 uint64_t TypeSize =
1917 !BaseT->isIncompleteType() ? getTypeSize(T: T.getTypePtr()) : 0;
1918 Align = std::max(a: Align, b: getMinGlobalAlignOfVar(Size: TypeSize, VD));
1919 }
1920
1921 // Fields can be subject to extra alignment constraints, like if
1922 // the field is packed, the struct is packed, or the struct has a
1923 // a max-field-alignment constraint (#pragma pack). So calculate
1924 // the actual alignment of the field within the struct, and then
1925 // (as we're expected to) constrain that by the alignment of the type.
1926 if (const auto *Field = dyn_cast<FieldDecl>(Val: VD)) {
1927 const RecordDecl *Parent = Field->getParent();
1928 // We can only produce a sensible answer if the record is valid.
1929 if (!Parent->isInvalidDecl()) {
1930 const ASTRecordLayout &Layout = getASTRecordLayout(D: Parent);
1931
1932 // Start with the record's overall alignment.
1933 unsigned FieldAlign = toBits(CharSize: Layout.getAlignment());
1934
1935 // Use the GCD of that and the offset within the record.
1936 uint64_t Offset = Layout.getFieldOffset(FieldNo: Field->getFieldIndex());
1937 if (Offset > 0) {
1938 // Alignment is always a power of 2, so the GCD will be a power of 2,
1939 // which means we get to do this crazy thing instead of Euclid's.
1940 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1941 if (LowBitOfOffset < FieldAlign)
1942 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1943 }
1944
1945 Align = std::min(a: Align, b: FieldAlign);
1946 }
1947 }
1948 }
1949
1950 // Some targets have hard limitation on the maximum requestable alignment in
1951 // aligned attribute for static variables.
1952 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1953 const auto *VD = dyn_cast<VarDecl>(Val: D);
1954 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1955 Align = std::min(a: Align, b: MaxAlignedAttr);
1956
1957 return toCharUnitsFromBits(BitSize: Align);
1958}
1959
1960CharUnits ASTContext::getExnObjectAlignment() const {
1961 return toCharUnitsFromBits(BitSize: Target->getExnObjectAlignment());
1962}
1963
1964// getTypeInfoDataSizeInChars - Return the size of a type, in
1965// chars. If the type is a record, its data size is returned. This is
1966// the size of the memcpy that's performed when assigning this type
1967// using a trivial copy/move assignment operator.
1968TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1969 TypeInfoChars Info = getTypeInfoInChars(T);
1970
1971 // In C++, objects can sometimes be allocated into the tail padding
1972 // of a base-class subobject. We decide whether that's possible
1973 // during class layout, so here we can just trust the layout results.
1974 if (getLangOpts().CPlusPlus) {
1975 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1976 const ASTRecordLayout &layout = getASTRecordLayout(D: RD);
1977 Info.Width = layout.getDataSize();
1978 }
1979 }
1980
1981 return Info;
1982}
1983
1984/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1985/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1986TypeInfoChars
1987static getConstantArrayInfoInChars(const ASTContext &Context,
1988 const ConstantArrayType *CAT) {
1989 TypeInfoChars EltInfo = Context.getTypeInfoInChars(T: CAT->getElementType());
1990 uint64_t Size = CAT->getZExtSize();
1991 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1992 (uint64_t)(-1)/Size) &&
1993 "Overflow in array type char size evaluation");
1994 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1995 unsigned Align = EltInfo.Align.getQuantity();
1996 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1997 Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default) == 64)
1998 Width = llvm::alignTo(Value: Width, Align);
1999 return TypeInfoChars(CharUnits::fromQuantity(Quantity: Width),
2000 CharUnits::fromQuantity(Quantity: Align),
2001 EltInfo.AlignRequirement);
2002}
2003
2004TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
2005 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: T))
2006 return getConstantArrayInfoInChars(Context: *this, CAT);
2007 TypeInfo Info = getTypeInfo(T);
2008 return TypeInfoChars(toCharUnitsFromBits(BitSize: Info.Width),
2009 toCharUnitsFromBits(BitSize: Info.Align), Info.AlignRequirement);
2010}
2011
2012TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
2013 return getTypeInfoInChars(T: T.getTypePtr());
2014}
2015
2016bool ASTContext::isPromotableIntegerType(QualType T) const {
2017 // HLSL doesn't promote all small integer types to int, it
2018 // just uses the rank-based promotion rules for all types.
2019 if (getLangOpts().HLSL)
2020 return false;
2021
2022 if (const auto *BT = T->getAs<BuiltinType>())
2023 switch (BT->getKind()) {
2024 case BuiltinType::Bool:
2025 case BuiltinType::Char_S:
2026 case BuiltinType::Char_U:
2027 case BuiltinType::SChar:
2028 case BuiltinType::UChar:
2029 case BuiltinType::Short:
2030 case BuiltinType::UShort:
2031 case BuiltinType::WChar_S:
2032 case BuiltinType::WChar_U:
2033 case BuiltinType::Char8:
2034 case BuiltinType::Char16:
2035 case BuiltinType::Char32:
2036 return true;
2037 default:
2038 return false;
2039 }
2040
2041 // Enumerated types are promotable to their compatible integer types
2042 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2043 if (const auto *ED = T->getAsEnumDecl()) {
2044 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2045 ED->isScoped())
2046 return false;
2047
2048 return true;
2049 }
2050
2051 // OverflowBehaviorTypes are promotable if their underlying type is promotable
2052 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
2053 return isPromotableIntegerType(T: OBT->getUnderlyingType());
2054 }
2055
2056 return false;
2057}
2058
2059bool ASTContext::isAlignmentRequired(const Type *T) const {
2060 return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None;
2061}
2062
2063bool ASTContext::isAlignmentRequired(QualType T) const {
2064 return isAlignmentRequired(T: T.getTypePtr());
2065}
2066
2067unsigned ASTContext::getTypeAlignIfKnown(QualType T,
2068 bool NeedsPreferredAlignment) const {
2069 // An alignment on a typedef overrides anything else.
2070 if (const auto *TT = T->getAs<TypedefType>())
2071 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2072 return Align;
2073
2074 // If we have an (array of) complete type, we're done.
2075 T = getBaseElementType(QT: T);
2076 if (!T->isIncompleteType())
2077 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2078
2079 // If we had an array type, its element type might be a typedef
2080 // type with an alignment attribute.
2081 if (const auto *TT = T->getAs<TypedefType>())
2082 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2083 return Align;
2084
2085 // Otherwise, see if the declaration of the type had an attribute.
2086 if (const auto *TD = T->getAsTagDecl())
2087 return TD->getMaxAlignment();
2088
2089 return 0;
2090}
2091
2092TypeInfo ASTContext::getTypeInfo(const Type *T) const {
2093 TypeInfoMap::iterator I = MemoizedTypeInfo.find(Val: T);
2094 if (I != MemoizedTypeInfo.end())
2095 return I->second;
2096
2097 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2098 TypeInfo TI = getTypeInfoImpl(T);
2099 MemoizedTypeInfo[T] = TI;
2100 return TI;
2101}
2102
2103/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2104/// method does not work on incomplete types.
2105///
2106/// FIXME: Pointers into different addr spaces could have different sizes and
2107/// alignment requirements: getPointerInfo should take an AddrSpace, this
2108/// should take a QualType, &c.
2109TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2110 uint64_t Width = 0;
2111 unsigned Align = 8;
2112 AlignRequirementKind AlignRequirement = AlignRequirementKind::None;
2113 LangAS AS = LangAS::Default;
2114 switch (T->getTypeClass()) {
2115#define TYPE(Class, Base)
2116#define ABSTRACT_TYPE(Class, Base)
2117#define NON_CANONICAL_TYPE(Class, Base)
2118#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2119#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2120 case Type::Class: \
2121 assert(!T->isDependentType() && "should not see dependent types here"); \
2122 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2123#include "clang/AST/TypeNodes.inc"
2124 llvm_unreachable("Should not see dependent types");
2125
2126 case Type::FunctionNoProto:
2127 case Type::FunctionProto:
2128 // GCC extension: alignof(function) = 32 bits
2129 Width = 0;
2130 Align = 32;
2131 break;
2132
2133 case Type::IncompleteArray:
2134 case Type::VariableArray:
2135 case Type::ConstantArray:
2136 case Type::ArrayParameter: {
2137 // Model non-constant sized arrays as size zero, but track the alignment.
2138 uint64_t Size = 0;
2139 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: T))
2140 Size = CAT->getZExtSize();
2141
2142 TypeInfo EltInfo = getTypeInfo(T: cast<ArrayType>(Val: T)->getElementType());
2143 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2144 "Overflow in array type bit size evaluation");
2145 Width = EltInfo.Width * Size;
2146 Align = EltInfo.Align;
2147 AlignRequirement = EltInfo.AlignRequirement;
2148 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2149 getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default) == 64)
2150 Width = llvm::alignTo(Value: Width, Align);
2151 break;
2152 }
2153
2154 case Type::ExtVector:
2155 case Type::Vector: {
2156 const auto *VT = cast<VectorType>(Val: T);
2157 TypeInfo EltInfo = getTypeInfo(T: VT->getElementType());
2158 Width = VT->isPackedVectorBoolType(ctx: *this)
2159 ? VT->getNumElements()
2160 : EltInfo.Width * VT->getNumElements();
2161 // Enforce at least byte size and alignment.
2162 Width = std::max<unsigned>(a: 8, b: Width);
2163 Align = std::max<unsigned>(
2164 a: 8, b: Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2165
2166 // If the alignment is not a power of 2, round up to the next power of 2.
2167 // This happens for non-power-of-2 length vectors.
2168 if (Align & (Align-1)) {
2169 Align = llvm::bit_ceil(Value: Align);
2170 Width = llvm::alignTo(Value: Width, Align);
2171 }
2172 // Adjust the alignment based on the target max.
2173 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2174 if (TargetVectorAlign && TargetVectorAlign < Align)
2175 Align = TargetVectorAlign;
2176 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2177 // Adjust the alignment for fixed-length SVE vectors. This is important
2178 // for non-power-of-2 vector lengths.
2179 Align = 128;
2180 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2181 // Adjust the alignment for fixed-length SVE predicates.
2182 Align = 16;
2183 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2184 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2185 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2186 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2187 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2188 // Adjust the alignment for fixed-length RVV vectors.
2189 Align = std::min<unsigned>(a: 64, b: Width);
2190 break;
2191 }
2192
2193 case Type::ConstantMatrix: {
2194 const auto *MT = cast<ConstantMatrixType>(Val: T);
2195 TypeInfo ElementInfo = getTypeInfo(T: MT->getElementType());
2196 // The internal layout of a matrix value is implementation defined.
2197 // Initially be ABI compatible with arrays with respect to alignment and
2198 // size.
2199 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2200 Align = ElementInfo.Align;
2201 break;
2202 }
2203
2204 case Type::Builtin:
2205 switch (cast<BuiltinType>(Val: T)->getKind()) {
2206 default: llvm_unreachable("Unknown builtin type!");
2207 case BuiltinType::Void:
2208 // GCC extension: alignof(void) = 8 bits.
2209 Width = 0;
2210 Align = 8;
2211 break;
2212 case BuiltinType::Bool:
2213 Width = Target->getBoolWidth();
2214 Align = Target->getBoolAlign();
2215 break;
2216 case BuiltinType::Char_S:
2217 case BuiltinType::Char_U:
2218 case BuiltinType::UChar:
2219 case BuiltinType::SChar:
2220 case BuiltinType::Char8:
2221 Width = Target->getCharWidth();
2222 Align = Target->getCharAlign();
2223 break;
2224 case BuiltinType::WChar_S:
2225 case BuiltinType::WChar_U:
2226 Width = Target->getWCharWidth();
2227 Align = Target->getWCharAlign();
2228 break;
2229 case BuiltinType::Char16:
2230 Width = Target->getChar16Width();
2231 Align = Target->getChar16Align();
2232 break;
2233 case BuiltinType::Char32:
2234 Width = Target->getChar32Width();
2235 Align = Target->getChar32Align();
2236 break;
2237 case BuiltinType::UShort:
2238 case BuiltinType::Short:
2239 Width = Target->getShortWidth();
2240 Align = Target->getShortAlign();
2241 break;
2242 case BuiltinType::UInt:
2243 case BuiltinType::Int:
2244 Width = Target->getIntWidth();
2245 Align = Target->getIntAlign();
2246 break;
2247 case BuiltinType::ULong:
2248 case BuiltinType::Long:
2249 Width = Target->getLongWidth();
2250 Align = Target->getLongAlign();
2251 break;
2252 case BuiltinType::ULongLong:
2253 case BuiltinType::LongLong:
2254 Width = Target->getLongLongWidth();
2255 Align = Target->getLongLongAlign();
2256 break;
2257 case BuiltinType::Int128:
2258 case BuiltinType::UInt128:
2259 Width = 128;
2260 Align = Target->getInt128Align();
2261 break;
2262 case BuiltinType::ShortAccum:
2263 case BuiltinType::UShortAccum:
2264 case BuiltinType::SatShortAccum:
2265 case BuiltinType::SatUShortAccum:
2266 Width = Target->getShortAccumWidth();
2267 Align = Target->getShortAccumAlign();
2268 break;
2269 case BuiltinType::Accum:
2270 case BuiltinType::UAccum:
2271 case BuiltinType::SatAccum:
2272 case BuiltinType::SatUAccum:
2273 Width = Target->getAccumWidth();
2274 Align = Target->getAccumAlign();
2275 break;
2276 case BuiltinType::LongAccum:
2277 case BuiltinType::ULongAccum:
2278 case BuiltinType::SatLongAccum:
2279 case BuiltinType::SatULongAccum:
2280 Width = Target->getLongAccumWidth();
2281 Align = Target->getLongAccumAlign();
2282 break;
2283 case BuiltinType::ShortFract:
2284 case BuiltinType::UShortFract:
2285 case BuiltinType::SatShortFract:
2286 case BuiltinType::SatUShortFract:
2287 Width = Target->getShortFractWidth();
2288 Align = Target->getShortFractAlign();
2289 break;
2290 case BuiltinType::Fract:
2291 case BuiltinType::UFract:
2292 case BuiltinType::SatFract:
2293 case BuiltinType::SatUFract:
2294 Width = Target->getFractWidth();
2295 Align = Target->getFractAlign();
2296 break;
2297 case BuiltinType::LongFract:
2298 case BuiltinType::ULongFract:
2299 case BuiltinType::SatLongFract:
2300 case BuiltinType::SatULongFract:
2301 Width = Target->getLongFractWidth();
2302 Align = Target->getLongFractAlign();
2303 break;
2304 case BuiltinType::BFloat16:
2305 if (Target->hasBFloat16Type()) {
2306 Width = Target->getBFloat16Width();
2307 Align = Target->getBFloat16Align();
2308 } else if ((getLangOpts().SYCLIsDevice ||
2309 (getLangOpts().OpenMP &&
2310 getLangOpts().OpenMPIsTargetDevice)) &&
2311 AuxTarget->hasBFloat16Type()) {
2312 Width = AuxTarget->getBFloat16Width();
2313 Align = AuxTarget->getBFloat16Align();
2314 }
2315 break;
2316 case BuiltinType::Float16:
2317 case BuiltinType::Half:
2318 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2319 !getLangOpts().OpenMPIsTargetDevice) {
2320 Width = Target->getHalfWidth();
2321 Align = Target->getHalfAlign();
2322 } else {
2323 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2324 "Expected OpenMP device compilation.");
2325 Width = AuxTarget->getHalfWidth();
2326 Align = AuxTarget->getHalfAlign();
2327 }
2328 break;
2329 case BuiltinType::Float:
2330 Width = Target->getFloatWidth();
2331 Align = Target->getFloatAlign();
2332 break;
2333 case BuiltinType::Double:
2334 Width = Target->getDoubleWidth();
2335 Align = Target->getDoubleAlign();
2336 break;
2337 case BuiltinType::Ibm128:
2338 Width = Target->getIbm128Width();
2339 Align = Target->getIbm128Align();
2340 break;
2341 case BuiltinType::LongDouble:
2342 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2343 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2344 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2345 Width = AuxTarget->getLongDoubleWidth();
2346 Align = AuxTarget->getLongDoubleAlign();
2347 } else {
2348 Width = Target->getLongDoubleWidth();
2349 Align = Target->getLongDoubleAlign();
2350 }
2351 break;
2352 case BuiltinType::Float128:
2353 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2354 !getLangOpts().OpenMPIsTargetDevice) {
2355 Width = Target->getFloat128Width();
2356 Align = Target->getFloat128Align();
2357 } else {
2358 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2359 "Expected OpenMP device compilation.");
2360 Width = AuxTarget->getFloat128Width();
2361 Align = AuxTarget->getFloat128Align();
2362 }
2363 break;
2364 case BuiltinType::NullPtr:
2365 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2366 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2367 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2368 break;
2369 case BuiltinType::ObjCId:
2370 case BuiltinType::ObjCClass:
2371 case BuiltinType::ObjCSel:
2372 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2373 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2374 break;
2375 case BuiltinType::OCLSampler:
2376 case BuiltinType::OCLEvent:
2377 case BuiltinType::OCLClkEvent:
2378 case BuiltinType::OCLQueue:
2379 case BuiltinType::OCLReserveID:
2380#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2381 case BuiltinType::Id:
2382#include "clang/Basic/OpenCLImageTypes.def"
2383#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2384 case BuiltinType::Id:
2385#include "clang/Basic/OpenCLExtensionTypes.def"
2386 AS = Target->getOpenCLTypeAddrSpace(TK: getOpenCLTypeKind(T));
2387 Width = Target->getPointerWidth(AddrSpace: AS);
2388 Align = Target->getPointerAlign(AddrSpace: AS);
2389 break;
2390 // The SVE types are effectively target-specific. The length of an
2391 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2392 // of 128 bits. There is one predicate bit for each vector byte, so the
2393 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2394 //
2395 // Because the length is only known at runtime, we use a dummy value
2396 // of 0 for the static length. The alignment values are those defined
2397 // by the Procedure Call Standard for the Arm Architecture.
2398#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2399 case BuiltinType::Id: \
2400 Width = 0; \
2401 Align = 128; \
2402 break;
2403#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2404 case BuiltinType::Id: \
2405 Width = 0; \
2406 Align = 16; \
2407 break;
2408#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2409 case BuiltinType::Id: \
2410 Width = 0; \
2411 Align = 16; \
2412 break;
2413#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2414 case BuiltinType::Id: \
2415 Width = Bits; \
2416 Align = Bits; \
2417 break;
2418#include "clang/Basic/AArch64ACLETypes.def"
2419#define PPC_VECTOR_TYPE(Name, Id, Size) \
2420 case BuiltinType::Id: \
2421 Width = Size; \
2422 Align = Size; \
2423 break;
2424#include "clang/Basic/PPCTypes.def"
2425#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2426 IsFP, IsBF) \
2427 case BuiltinType::Id: \
2428 Width = 0; \
2429 Align = ElBits; \
2430 break;
2431#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2432 case BuiltinType::Id: \
2433 Width = 0; \
2434 Align = 8; \
2435 break;
2436#include "clang/Basic/RISCVVTypes.def"
2437#define WASM_TYPE(Name, Id, SingletonId) \
2438 case BuiltinType::Id: \
2439 Width = 0; \
2440 Align = 8; \
2441 break;
2442#include "clang/Basic/WebAssemblyReferenceTypes.def"
2443#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2444 case BuiltinType::ID: \
2445 Width = WIDTH; \
2446 Align = ALIGN; \
2447 break;
2448#include "clang/Basic/AMDGPUTypes.def"
2449#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2450#include "clang/Basic/HLSLIntangibleTypes.def"
2451 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2452 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2453 break;
2454 }
2455 break;
2456 case Type::ObjCObjectPointer:
2457 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2458 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2459 break;
2460 case Type::BlockPointer:
2461 AS = cast<BlockPointerType>(Val: T)->getPointeeType().getAddressSpace();
2462 Width = Target->getPointerWidth(AddrSpace: AS);
2463 Align = Target->getPointerAlign(AddrSpace: AS);
2464 break;
2465 case Type::LValueReference:
2466 case Type::RValueReference:
2467 // alignof and sizeof should never enter this code path here, so we go
2468 // the pointer route.
2469 AS = cast<ReferenceType>(Val: T)->getPointeeType().getAddressSpace();
2470 Width = Target->getPointerWidth(AddrSpace: AS);
2471 Align = Target->getPointerAlign(AddrSpace: AS);
2472 break;
2473 case Type::Pointer:
2474 AS = cast<PointerType>(Val: T)->getPointeeType().getAddressSpace();
2475 Width = Target->getPointerWidth(AddrSpace: AS);
2476 Align = Target->getPointerAlign(AddrSpace: AS);
2477 break;
2478 case Type::MemberPointer: {
2479 const auto *MPT = cast<MemberPointerType>(Val: T);
2480 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2481 Width = MPI.Width;
2482 Align = MPI.Align;
2483 break;
2484 }
2485 case Type::Complex: {
2486 // Complex types have the same alignment as their elements, but twice the
2487 // size.
2488 TypeInfo EltInfo = getTypeInfo(T: cast<ComplexType>(Val: T)->getElementType());
2489 Width = EltInfo.Width * 2;
2490 Align = EltInfo.Align;
2491 break;
2492 }
2493 case Type::ObjCObject:
2494 return getTypeInfo(T: cast<ObjCObjectType>(Val: T)->getBaseType().getTypePtr());
2495 case Type::Adjusted:
2496 case Type::Decayed:
2497 return getTypeInfo(T: cast<AdjustedType>(Val: T)->getAdjustedType().getTypePtr());
2498 case Type::ObjCInterface: {
2499 const auto *ObjCI = cast<ObjCInterfaceType>(Val: T);
2500 if (ObjCI->getDecl()->isInvalidDecl()) {
2501 Width = 8;
2502 Align = 8;
2503 break;
2504 }
2505 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(D: ObjCI->getDecl());
2506 Width = toBits(CharSize: Layout.getSize());
2507 Align = toBits(CharSize: Layout.getAlignment());
2508 break;
2509 }
2510 case Type::BitInt: {
2511 const auto *EIT = cast<BitIntType>(Val: T);
2512 Align = Target->getBitIntAlign(NumBits: EIT->getNumBits());
2513 Width = Target->getBitIntWidth(NumBits: EIT->getNumBits());
2514 break;
2515 }
2516 case Type::Record:
2517 case Type::Enum: {
2518 const auto *TT = cast<TagType>(Val: T);
2519 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2520
2521 if (TD->isInvalidDecl()) {
2522 Width = 8;
2523 Align = 8;
2524 break;
2525 }
2526
2527 if (isa<EnumType>(Val: TT)) {
2528 const EnumDecl *ED = cast<EnumDecl>(Val: TD);
2529 TypeInfo Info =
2530 getTypeInfo(T: ED->getIntegerType()->getUnqualifiedDesugaredType());
2531 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2532 Info.Align = AttrAlign;
2533 Info.AlignRequirement = AlignRequirementKind::RequiredByEnum;
2534 }
2535 return Info;
2536 }
2537
2538 const auto *RD = cast<RecordDecl>(Val: TD);
2539 const ASTRecordLayout &Layout = getASTRecordLayout(D: RD);
2540 Width = toBits(CharSize: Layout.getSize());
2541 Align = toBits(CharSize: Layout.getAlignment());
2542 AlignRequirement = RD->hasAttr<AlignedAttr>()
2543 ? AlignRequirementKind::RequiredByRecord
2544 : AlignRequirementKind::None;
2545 break;
2546 }
2547
2548 case Type::SubstTemplateTypeParm:
2549 return getTypeInfo(T: cast<SubstTemplateTypeParmType>(Val: T)->
2550 getReplacementType().getTypePtr());
2551
2552 case Type::Auto:
2553 case Type::DeducedTemplateSpecialization: {
2554 const auto *A = cast<DeducedType>(Val: T);
2555 assert(!A->getDeducedType().isNull() &&
2556 "cannot request the size of an undeduced or dependent auto type");
2557 return getTypeInfo(T: A->getDeducedType().getTypePtr());
2558 }
2559
2560 case Type::Paren:
2561 return getTypeInfo(T: cast<ParenType>(Val: T)->getInnerType().getTypePtr());
2562
2563 case Type::MacroQualified:
2564 return getTypeInfo(
2565 T: cast<MacroQualifiedType>(Val: T)->getUnderlyingType().getTypePtr());
2566
2567 case Type::ObjCTypeParam:
2568 return getTypeInfo(T: cast<ObjCTypeParamType>(Val: T)->desugar().getTypePtr());
2569
2570 case Type::Using:
2571 return getTypeInfo(T: cast<UsingType>(Val: T)->desugar().getTypePtr());
2572
2573 case Type::Typedef: {
2574 const auto *TT = cast<TypedefType>(Val: T);
2575 TypeInfo Info = getTypeInfo(T: TT->desugar().getTypePtr());
2576 // If the typedef has an aligned attribute on it, it overrides any computed
2577 // alignment we have. This violates the GCC documentation (which says that
2578 // attribute(aligned) can only round up) but matches its implementation.
2579 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2580 Align = AttrAlign;
2581 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2582 } else {
2583 Align = Info.Align;
2584 AlignRequirement = Info.AlignRequirement;
2585 }
2586 Width = Info.Width;
2587 break;
2588 }
2589
2590 case Type::Attributed:
2591 return getTypeInfo(
2592 T: cast<AttributedType>(Val: T)->getEquivalentType().getTypePtr());
2593
2594 case Type::CountAttributed:
2595 return getTypeInfo(T: cast<CountAttributedType>(Val: T)->desugar().getTypePtr());
2596
2597 case Type::BTFTagAttributed:
2598 return getTypeInfo(
2599 T: cast<BTFTagAttributedType>(Val: T)->getWrappedType().getTypePtr());
2600
2601 case Type::OverflowBehavior:
2602 return getTypeInfo(
2603 T: cast<OverflowBehaviorType>(Val: T)->getUnderlyingType().getTypePtr());
2604
2605 case Type::HLSLAttributedResource:
2606 return getTypeInfo(
2607 T: cast<HLSLAttributedResourceType>(Val: T)->getWrappedType().getTypePtr());
2608
2609 case Type::HLSLInlineSpirv: {
2610 const auto *ST = cast<HLSLInlineSpirvType>(Val: T);
2611 // Size is specified in bytes, convert to bits
2612 Width = ST->getSize() * 8;
2613 Align = ST->getAlignment();
2614 if (Width == 0 && Align == 0) {
2615 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2616 Width = 32;
2617 Align = 32;
2618 }
2619 break;
2620 }
2621
2622 case Type::Atomic: {
2623 // Start with the base type information.
2624 TypeInfo Info = getTypeInfo(T: cast<AtomicType>(Val: T)->getValueType());
2625 Width = Info.Width;
2626 Align = Info.Align;
2627
2628 if (!Width) {
2629 // An otherwise zero-sized type should still generate an
2630 // atomic operation.
2631 Width = Target->getCharWidth();
2632 assert(Align);
2633 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2634 // If the size of the type doesn't exceed the platform's max
2635 // atomic promotion width, make the size and alignment more
2636 // favorable to atomic operations:
2637
2638 // Round the size up to a power of 2.
2639 Width = llvm::bit_ceil(Value: Width);
2640
2641 // Set the alignment equal to the size.
2642 Align = static_cast<unsigned>(Width);
2643 }
2644 }
2645 break;
2646
2647 case Type::PredefinedSugar:
2648 return getTypeInfo(T: cast<PredefinedSugarType>(Val: T)->desugar().getTypePtr());
2649
2650 case Type::Pipe:
2651 Width = Target->getPointerWidth(AddrSpace: LangAS::opencl_global);
2652 Align = Target->getPointerAlign(AddrSpace: LangAS::opencl_global);
2653 break;
2654 }
2655
2656 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2657 return TypeInfo(Width, Align, AlignRequirement);
2658}
2659
2660unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2661 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(Val: T);
2662 if (I != MemoizedUnadjustedAlign.end())
2663 return I->second;
2664
2665 unsigned UnadjustedAlign;
2666 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2667 const ASTRecordLayout &Layout = getASTRecordLayout(D: RT->getDecl());
2668 UnadjustedAlign = toBits(CharSize: Layout.getUnadjustedAlignment());
2669 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2670 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(D: ObjCI->getDecl());
2671 UnadjustedAlign = toBits(CharSize: Layout.getUnadjustedAlignment());
2672 } else {
2673 UnadjustedAlign = getTypeAlign(T: T->getUnqualifiedDesugaredType());
2674 }
2675
2676 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2677 return UnadjustedAlign;
2678}
2679
2680unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2681 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2682 TargetTriple: getTargetInfo().getTriple(), Features: Target->getTargetOpts().FeatureMap);
2683 return SimdAlign;
2684}
2685
2686/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2687CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2688 return CharUnits::fromQuantity(Quantity: BitSize / getCharWidth());
2689}
2690
2691/// toBits - Convert a size in characters to a size in characters.
2692int64_t ASTContext::toBits(CharUnits CharSize) const {
2693 return CharSize.getQuantity() * getCharWidth();
2694}
2695
2696/// getTypeSizeInChars - Return the size of the specified type, in characters.
2697/// This method does not work on incomplete types.
2698CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2699 return getTypeInfoInChars(T).Width;
2700}
2701CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2702 return getTypeInfoInChars(T).Width;
2703}
2704
2705/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2706/// characters. This method does not work on incomplete types.
2707CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2708 return toCharUnitsFromBits(BitSize: getTypeAlign(T));
2709}
2710CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2711 return toCharUnitsFromBits(BitSize: getTypeAlign(T));
2712}
2713
2714/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2715/// type, in characters, before alignment adjustments. This method does
2716/// not work on incomplete types.
2717CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2718 return toCharUnitsFromBits(BitSize: getTypeUnadjustedAlign(T));
2719}
2720CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2721 return toCharUnitsFromBits(BitSize: getTypeUnadjustedAlign(T));
2722}
2723
2724/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2725/// type for the current target in bits. This can be different than the ABI
2726/// alignment in cases where it is beneficial for performance or backwards
2727/// compatibility preserving to overalign a data type. (Note: despite the name,
2728/// the preferred alignment is ABI-impacting, and not an optimization.)
2729unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2730 TypeInfo TI = getTypeInfo(T);
2731 unsigned ABIAlign = TI.Align;
2732
2733 T = T->getBaseElementTypeUnsafe();
2734
2735 // The preferred alignment of member pointers is that of a pointer.
2736 if (T->isMemberPointerType())
2737 return getPreferredTypeAlign(T: getPointerDiffType().getTypePtr());
2738
2739 if (!Target->allowsLargerPreferedTypeAlignment())
2740 return ABIAlign;
2741
2742 if (const auto *RD = T->getAsRecordDecl()) {
2743 // When used as part of a typedef, or together with a 'packed' attribute,
2744 // the 'aligned' attribute can be used to decrease alignment. Note that the
2745 // 'packed' case is already taken into consideration when computing the
2746 // alignment, we only need to handle the typedef case here.
2747 if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
2748 RD->isInvalidDecl())
2749 return ABIAlign;
2750
2751 unsigned PreferredAlign = static_cast<unsigned>(
2752 toBits(CharSize: getASTRecordLayout(D: RD).PreferredAlignment));
2753 assert(PreferredAlign >= ABIAlign &&
2754 "PreferredAlign should be at least as large as ABIAlign.");
2755 return PreferredAlign;
2756 }
2757
2758 // Double (and, for targets supporting AIX `power` alignment, long double) and
2759 // long long should be naturally aligned (despite requiring less alignment) if
2760 // possible.
2761 if (const auto *CT = T->getAs<ComplexType>())
2762 T = CT->getElementType().getTypePtr();
2763 if (const auto *ED = T->getAsEnumDecl())
2764 T = ED->getIntegerType().getTypePtr();
2765 if (T->isSpecificBuiltinType(K: BuiltinType::Double) ||
2766 T->isSpecificBuiltinType(K: BuiltinType::LongLong) ||
2767 T->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
2768 (T->isSpecificBuiltinType(K: BuiltinType::LongDouble) &&
2769 Target->defaultsToAIXPowerAlignment()))
2770 // Don't increase the alignment if an alignment attribute was specified on a
2771 // typedef declaration.
2772 if (!TI.isAlignRequired())
2773 return std::max(a: ABIAlign, b: (unsigned)getTypeSize(T));
2774
2775 return ABIAlign;
2776}
2777
2778/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2779/// for __attribute__((aligned)) on this target, to be used if no alignment
2780/// value is specified.
2781unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2782 return getTargetInfo().getDefaultAlignForAttributeAligned();
2783}
2784
2785/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2786/// to a global variable of the specified type.
2787unsigned ASTContext::getAlignOfGlobalVar(QualType T, const VarDecl *VD) const {
2788 uint64_t TypeSize = getTypeSize(T: T.getTypePtr());
2789 return std::max(a: getPreferredTypeAlign(T),
2790 b: getMinGlobalAlignOfVar(Size: TypeSize, VD));
2791}
2792
2793/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2794/// should be given to a global variable of the specified type.
2795CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T,
2796 const VarDecl *VD) const {
2797 return toCharUnitsFromBits(BitSize: getAlignOfGlobalVar(T, VD));
2798}
2799
2800unsigned ASTContext::getMinGlobalAlignOfVar(uint64_t Size,
2801 const VarDecl *VD) const {
2802 // Make the default handling as that of a non-weak definition in the
2803 // current translation unit.
2804 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2805 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2806}
2807
2808CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2809 CharUnits Offset = CharUnits::Zero();
2810 const ASTRecordLayout *Layout = &getASTRecordLayout(D: RD);
2811 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2812 Offset += Layout->getBaseClassOffset(Base);
2813 Layout = &getASTRecordLayout(D: Base);
2814 }
2815 return Offset;
2816}
2817
2818CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2819 const ValueDecl *MPD = MP.getMemberPointerDecl();
2820 CharUnits ThisAdjustment = CharUnits::Zero();
2821 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2822 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2823 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: MPD->getDeclContext());
2824 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2825 const CXXRecordDecl *Base = RD;
2826 const CXXRecordDecl *Derived = Path[I];
2827 if (DerivedMember)
2828 std::swap(a&: Base, b&: Derived);
2829 ThisAdjustment += getASTRecordLayout(D: Derived).getBaseClassOffset(Base);
2830 RD = Path[I];
2831 }
2832 if (DerivedMember)
2833 ThisAdjustment = -ThisAdjustment;
2834 return ThisAdjustment;
2835}
2836
2837/// DeepCollectObjCIvars -
2838/// This routine first collects all declared, but not synthesized, ivars in
2839/// super class and then collects all ivars, including those synthesized for
2840/// current class. This routine is used for implementation of current class
2841/// when all ivars, declared and synthesized are known.
2842void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2843 bool leafClass,
2844 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2845 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2846 DeepCollectObjCIvars(OI: SuperClass, leafClass: false, Ivars);
2847 if (!leafClass) {
2848 llvm::append_range(C&: Ivars, R: OI->ivars());
2849 } else {
2850 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2851 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2852 Iv= Iv->getNextIvar())
2853 Ivars.push_back(Elt: Iv);
2854 }
2855}
2856
2857/// CollectInheritedProtocols - Collect all protocols in current class and
2858/// those inherited by it.
2859void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2860 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2861 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(Val: CDecl)) {
2862 // We can use protocol_iterator here instead of
2863 // all_referenced_protocol_iterator since we are walking all categories.
2864 for (auto *Proto : OI->all_referenced_protocols()) {
2865 CollectInheritedProtocols(CDecl: Proto, Protocols);
2866 }
2867
2868 // Categories of this Interface.
2869 for (const auto *Cat : OI->visible_categories())
2870 CollectInheritedProtocols(CDecl: Cat, Protocols);
2871
2872 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2873 while (SD) {
2874 CollectInheritedProtocols(CDecl: SD, Protocols);
2875 SD = SD->getSuperClass();
2876 }
2877 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(Val: CDecl)) {
2878 for (auto *Proto : OC->protocols()) {
2879 CollectInheritedProtocols(CDecl: Proto, Protocols);
2880 }
2881 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(Val: CDecl)) {
2882 // Insert the protocol.
2883 if (!Protocols.insert(
2884 Ptr: const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2885 return;
2886
2887 for (auto *Proto : OP->protocols())
2888 CollectInheritedProtocols(CDecl: Proto, Protocols);
2889 }
2890}
2891
2892static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2893 const RecordDecl *RD,
2894 bool CheckIfTriviallyCopyable) {
2895 assert(RD->isUnion() && "Must be union type");
2896 CharUnits UnionSize =
2897 Context.getTypeSizeInChars(T: Context.getCanonicalTagType(TD: RD));
2898
2899 for (const auto *Field : RD->fields()) {
2900 if (!Context.hasUniqueObjectRepresentations(Ty: Field->getType(),
2901 CheckIfTriviallyCopyable))
2902 return false;
2903 CharUnits FieldSize = Context.getTypeSizeInChars(T: Field->getType());
2904 if (FieldSize != UnionSize)
2905 return false;
2906 }
2907 return !RD->field_empty();
2908}
2909
2910static int64_t getSubobjectOffset(const FieldDecl *Field,
2911 const ASTContext &Context,
2912 const clang::ASTRecordLayout & /*Layout*/) {
2913 return Context.getFieldOffset(FD: Field);
2914}
2915
2916static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2917 const ASTContext &Context,
2918 const clang::ASTRecordLayout &Layout) {
2919 return Context.toBits(CharSize: Layout.getBaseClassOffset(Base: RD));
2920}
2921
2922static std::optional<int64_t>
2923structHasUniqueObjectRepresentations(const ASTContext &Context,
2924 const RecordDecl *RD,
2925 bool CheckIfTriviallyCopyable);
2926
2927static std::optional<int64_t>
2928getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2929 bool CheckIfTriviallyCopyable) {
2930 if (const auto *RD = Field->getType()->getAsRecordDecl();
2931 RD && !RD->isUnion())
2932 return structHasUniqueObjectRepresentations(Context, RD,
2933 CheckIfTriviallyCopyable);
2934
2935 // A _BitInt type may not be unique if it has padding bits
2936 // but if it is a bitfield the padding bits are not used.
2937 bool IsBitIntType = Field->getType()->isBitIntType();
2938 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2939 !Context.hasUniqueObjectRepresentations(Ty: Field->getType(),
2940 CheckIfTriviallyCopyable))
2941 return std::nullopt;
2942
2943 int64_t FieldSizeInBits =
2944 Context.toBits(CharSize: Context.getTypeSizeInChars(T: Field->getType()));
2945 if (Field->isBitField()) {
2946 // If we have explicit padding bits, they don't contribute bits
2947 // to the actual object representation, so return 0.
2948 if (Field->isUnnamedBitField())
2949 return 0;
2950
2951 int64_t BitfieldSize = Field->getBitWidthValue();
2952 if (IsBitIntType) {
2953 if ((unsigned)BitfieldSize >
2954 cast<BitIntType>(Val: Field->getType())->getNumBits())
2955 return std::nullopt;
2956 } else if (BitfieldSize > FieldSizeInBits) {
2957 return std::nullopt;
2958 }
2959 FieldSizeInBits = BitfieldSize;
2960 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2961 Ty: Field->getType(), CheckIfTriviallyCopyable)) {
2962 return std::nullopt;
2963 }
2964 return FieldSizeInBits;
2965}
2966
2967static std::optional<int64_t>
2968getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context,
2969 bool CheckIfTriviallyCopyable) {
2970 return structHasUniqueObjectRepresentations(Context, RD,
2971 CheckIfTriviallyCopyable);
2972}
2973
2974template <typename RangeT>
2975static std::optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations(
2976 const RangeT &Subobjects, int64_t CurOffsetInBits,
2977 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2978 bool CheckIfTriviallyCopyable) {
2979 for (const auto *Subobject : Subobjects) {
2980 std::optional<int64_t> SizeInBits =
2981 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2982 if (!SizeInBits)
2983 return std::nullopt;
2984 if (*SizeInBits != 0) {
2985 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2986 if (Offset != CurOffsetInBits)
2987 return std::nullopt;
2988 CurOffsetInBits += *SizeInBits;
2989 }
2990 }
2991 return CurOffsetInBits;
2992}
2993
2994static std::optional<int64_t>
2995structHasUniqueObjectRepresentations(const ASTContext &Context,
2996 const RecordDecl *RD,
2997 bool CheckIfTriviallyCopyable) {
2998 assert(!RD->isUnion() && "Must be struct/class type");
2999 const auto &Layout = Context.getASTRecordLayout(D: RD);
3000
3001 int64_t CurOffsetInBits = 0;
3002 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD)) {
3003 if (ClassDecl->isDynamicClass())
3004 return std::nullopt;
3005
3006 SmallVector<CXXRecordDecl *, 4> Bases;
3007 for (const auto &Base : ClassDecl->bases()) {
3008 // Empty types can be inherited from, and non-empty types can potentially
3009 // have tail padding, so just make sure there isn't an error.
3010 Bases.emplace_back(Args: Base.getType()->getAsCXXRecordDecl());
3011 }
3012
3013 llvm::sort(C&: Bases, Comp: [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3014 return Layout.getBaseClassOffset(Base: L) < Layout.getBaseClassOffset(Base: R);
3015 });
3016
3017 std::optional<int64_t> OffsetAfterBases =
3018 structSubobjectsHaveUniqueObjectRepresentations(
3019 Subobjects: Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
3020 if (!OffsetAfterBases)
3021 return std::nullopt;
3022 CurOffsetInBits = *OffsetAfterBases;
3023 }
3024
3025 std::optional<int64_t> OffsetAfterFields =
3026 structSubobjectsHaveUniqueObjectRepresentations(
3027 Subobjects: RD->fields(), CurOffsetInBits, Context, Layout,
3028 CheckIfTriviallyCopyable);
3029 if (!OffsetAfterFields)
3030 return std::nullopt;
3031 CurOffsetInBits = *OffsetAfterFields;
3032
3033 return CurOffsetInBits;
3034}
3035
3036bool ASTContext::hasUniqueObjectRepresentations(
3037 QualType Ty, bool CheckIfTriviallyCopyable) const {
3038 // C++17 [meta.unary.prop]:
3039 // The predicate condition for a template specialization
3040 // has_unique_object_representations<T> shall be satisfied if and only if:
3041 // (9.1) - T is trivially copyable, and
3042 // (9.2) - any two objects of type T with the same value have the same
3043 // object representation, where:
3044 // - two objects of array or non-union class type are considered to have
3045 // the same value if their respective sequences of direct subobjects
3046 // have the same values, and
3047 // - two objects of union type are considered to have the same value if
3048 // they have the same active member and the corresponding members have
3049 // the same value.
3050 // The set of scalar types for which this condition holds is
3051 // implementation-defined. [ Note: If a type has padding bits, the condition
3052 // does not hold; otherwise, the condition holds true for unsigned integral
3053 // types. -- end note ]
3054 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3055
3056 // Arrays are unique only if their element type is unique.
3057 if (Ty->isArrayType())
3058 return hasUniqueObjectRepresentations(Ty: getBaseElementType(QT: Ty),
3059 CheckIfTriviallyCopyable);
3060
3061 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3062 "hasUniqueObjectRepresentations should not be called with an "
3063 "incomplete type");
3064
3065 // (9.1) - T is trivially copyable...
3066 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(Context: *this))
3067 return false;
3068
3069 // All integrals and enums are unique.
3070 if (Ty->isIntegralOrEnumerationType()) {
3071 // Address discriminated integer types are not unique.
3072 if (Ty.hasAddressDiscriminatedPointerAuth())
3073 return false;
3074 // Except _BitInt types that have padding bits.
3075 if (const auto *BIT = Ty->getAs<BitIntType>())
3076 return getTypeSize(T: BIT) == BIT->getNumBits();
3077
3078 return true;
3079 }
3080
3081 // All other pointers are unique.
3082 if (Ty->isPointerType())
3083 return !Ty.hasAddressDiscriminatedPointerAuth();
3084
3085 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3086 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3087
3088 if (const auto *Record = Ty->getAsRecordDecl()) {
3089 if (Record->isInvalidDecl())
3090 return false;
3091
3092 if (Record->isUnion())
3093 return unionHasUniqueObjectRepresentations(Context: *this, RD: Record,
3094 CheckIfTriviallyCopyable);
3095
3096 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3097 Context: *this, RD: Record, CheckIfTriviallyCopyable);
3098
3099 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(T: Ty));
3100 }
3101
3102 // FIXME: More cases to handle here (list by rsmith):
3103 // vectors (careful about, eg, vector of 3 foo)
3104 // _Complex int and friends
3105 // _Atomic T
3106 // Obj-C block pointers
3107 // Obj-C object pointers
3108 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3109 // clk_event_t, queue_t, reserve_id_t)
3110 // There're also Obj-C class types and the Obj-C selector type, but I think it
3111 // makes sense for those to return false here.
3112
3113 return false;
3114}
3115
3116unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
3117 unsigned count = 0;
3118 // Count ivars declared in class extension.
3119 for (const auto *Ext : OI->known_extensions())
3120 count += Ext->ivar_size();
3121
3122 // Count ivar defined in this class's implementation. This
3123 // includes synthesized ivars.
3124 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3125 count += ImplDecl->ivar_size();
3126
3127 return count;
3128}
3129
3130bool ASTContext::isSentinelNullExpr(const Expr *E) {
3131 if (!E)
3132 return false;
3133
3134 // nullptr_t is always treated as null.
3135 if (E->getType()->isNullPtrType()) return true;
3136
3137 if (E->getType()->isAnyPointerType() &&
3138 E->IgnoreParenCasts()->isNullPointerConstant(Ctx&: *this,
3139 NPC: Expr::NPC_ValueDependentIsNull))
3140 return true;
3141
3142 // Unfortunately, __null has type 'int'.
3143 if (isa<GNUNullExpr>(Val: E)) return true;
3144
3145 return false;
3146}
3147
3148/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3149/// exists.
3150ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
3151 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3152 I = ObjCImpls.find(Val: D);
3153 if (I != ObjCImpls.end())
3154 return cast<ObjCImplementationDecl>(Val: I->second);
3155 return nullptr;
3156}
3157
3158/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3159/// exists.
3160ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
3161 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3162 I = ObjCImpls.find(Val: D);
3163 if (I != ObjCImpls.end())
3164 return cast<ObjCCategoryImplDecl>(Val: I->second);
3165 return nullptr;
3166}
3167
3168/// Set the implementation of ObjCInterfaceDecl.
3169void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
3170 ObjCImplementationDecl *ImplD) {
3171 assert(IFaceD && ImplD && "Passed null params");
3172 ObjCImpls[IFaceD] = ImplD;
3173}
3174
3175/// Set the implementation of ObjCCategoryDecl.
3176void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
3177 ObjCCategoryImplDecl *ImplD) {
3178 assert(CatD && ImplD && "Passed null params");
3179 ObjCImpls[CatD] = ImplD;
3180}
3181
3182const ObjCMethodDecl *
3183ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
3184 return ObjCMethodRedecls.lookup(Val: MD);
3185}
3186
3187void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
3188 const ObjCMethodDecl *Redecl) {
3189 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3190 ObjCMethodRedecls[MD] = Redecl;
3191}
3192
3193const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
3194 const NamedDecl *ND) const {
3195 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(Val: ND->getDeclContext()))
3196 return ID;
3197 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(Val: ND->getDeclContext()))
3198 return CD->getClassInterface();
3199 if (const auto *IMD = dyn_cast<ObjCImplDecl>(Val: ND->getDeclContext()))
3200 return IMD->getClassInterface();
3201
3202 return nullptr;
3203}
3204
3205/// Get the copy initialization expression of VarDecl, or nullptr if
3206/// none exists.
3207BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
3208 assert(VD && "Passed null params");
3209 assert(VD->hasAttr<BlocksAttr>() &&
3210 "getBlockVarCopyInits - not __block var");
3211 auto I = BlockVarCopyInits.find(Val: VD);
3212 if (I != BlockVarCopyInits.end())
3213 return I->second;
3214 return {nullptr, false};
3215}
3216
3217/// Set the copy initialization expression of a block var decl.
3218void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
3219 bool CanThrow) {
3220 assert(VD && CopyExpr && "Passed null params");
3221 assert(VD->hasAttr<BlocksAttr>() &&
3222 "setBlockVarCopyInits - not __block var");
3223 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3224}
3225
3226TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
3227 unsigned DataSize) const {
3228 if (!DataSize)
3229 DataSize = TypeLoc::getFullDataSizeForType(Ty: T);
3230 else
3231 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3232 "incorrect data size provided to CreateTypeSourceInfo!");
3233
3234 auto *TInfo =
3235 (TypeSourceInfo*)BumpAlloc.Allocate(Size: sizeof(TypeSourceInfo) + DataSize, Alignment: 8);
3236 new (TInfo) TypeSourceInfo(T, DataSize);
3237 return TInfo;
3238}
3239
3240TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
3241 SourceLocation L) const {
3242 TypeSourceInfo *TSI = CreateTypeSourceInfo(T);
3243 TSI->getTypeLoc().initialize(Context&: const_cast<ASTContext &>(*this), Loc: L);
3244 return TSI;
3245}
3246
3247const ASTRecordLayout &
3248ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
3249 return getObjCLayout(D);
3250}
3251
3252static auto getCanonicalTemplateArguments(const ASTContext &C,
3253 ArrayRef<TemplateArgument> Args,
3254 bool &AnyNonCanonArgs) {
3255 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3256 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(Args: CanonArgs);
3257 return CanonArgs;
3258}
3259
3260bool ASTContext::canonicalizeTemplateArguments(
3261 MutableArrayRef<TemplateArgument> Args) const {
3262 bool AnyNonCanonArgs = false;
3263 for (auto &Arg : Args) {
3264 TemplateArgument OrigArg = Arg;
3265 Arg = getCanonicalTemplateArgument(Arg);
3266 AnyNonCanonArgs |= !Arg.structurallyEquals(Other: OrigArg);
3267 }
3268 return AnyNonCanonArgs;
3269}
3270
3271//===----------------------------------------------------------------------===//
3272// Type creation/memoization methods
3273//===----------------------------------------------------------------------===//
3274
3275QualType
3276ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3277 unsigned fastQuals = quals.getFastQualifiers();
3278 quals.removeFastQualifiers();
3279
3280 // Check if we've already instantiated this type.
3281 llvm::FoldingSetNodeID ID;
3282 ExtQuals::Profile(ID, BaseType: baseType, Quals: quals);
3283 void *insertPos = nullptr;
3284 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos&: insertPos)) {
3285 assert(eq->getQualifiers() == quals);
3286 return QualType(eq, fastQuals);
3287 }
3288
3289 // If the base type is not canonical, make the appropriate canonical type.
3290 QualType canon;
3291 if (!baseType->isCanonicalUnqualified()) {
3292 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3293 canonSplit.Quals.addConsistentQualifiers(qs: quals);
3294 canon = getExtQualType(baseType: canonSplit.Ty, quals: canonSplit.Quals);
3295
3296 // Re-find the insert position.
3297 (void) ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos&: insertPos);
3298 }
3299
3300 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3301 ExtQualNodes.InsertNode(N: eq, InsertPos: insertPos);
3302 return QualType(eq, fastQuals);
3303}
3304
3305QualType ASTContext::getAddrSpaceQualType(QualType T,
3306 LangAS AddressSpace) const {
3307 QualType CanT = getCanonicalType(T);
3308 if (CanT.getAddressSpace() == AddressSpace)
3309 return T;
3310
3311 // If we are composing extended qualifiers together, merge together
3312 // into one ExtQuals node.
3313 QualifierCollector Quals;
3314 const Type *TypeNode = Quals.strip(type: T);
3315
3316 // If this type already has an address space specified, it cannot get
3317 // another one.
3318 assert(!Quals.hasAddressSpace() &&
3319 "Type cannot be in multiple addr spaces!");
3320 Quals.addAddressSpace(space: AddressSpace);
3321
3322 return getExtQualType(baseType: TypeNode, quals: Quals);
3323}
3324
3325QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
3326 // If the type is not qualified with an address space, just return it
3327 // immediately.
3328 if (!T.hasAddressSpace())
3329 return T;
3330
3331 QualifierCollector Quals;
3332 const Type *TypeNode;
3333 // For arrays, strip the qualifier off the element type, then reconstruct the
3334 // array type
3335 if (T.getTypePtr()->isArrayType()) {
3336 T = getUnqualifiedArrayType(T, Quals);
3337 TypeNode = T.getTypePtr();
3338 } else {
3339 // If we are composing extended qualifiers together, merge together
3340 // into one ExtQuals node.
3341 while (T.hasAddressSpace()) {
3342 TypeNode = Quals.strip(type: T);
3343
3344 // If the type no longer has an address space after stripping qualifiers,
3345 // jump out.
3346 if (!QualType(TypeNode, 0).hasAddressSpace())
3347 break;
3348
3349 // There might be sugar in the way. Strip it and try again.
3350 T = T.getSingleStepDesugaredType(Context: *this);
3351 }
3352 }
3353
3354 Quals.removeAddressSpace();
3355
3356 // Removal of the address space can mean there are no longer any
3357 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3358 // or required.
3359 if (Quals.hasNonFastQualifiers())
3360 return getExtQualType(baseType: TypeNode, quals: Quals);
3361 else
3362 return QualType(TypeNode, Quals.getFastQualifiers());
3363}
3364
3365uint16_t
3366ASTContext::getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD) {
3367 assert(RD->isPolymorphic() &&
3368 "Attempted to get vtable pointer discriminator on a monomorphic type");
3369 std::unique_ptr<MangleContext> MC(createMangleContext());
3370 SmallString<256> Str;
3371 llvm::raw_svector_ostream Out(Str);
3372 MC->mangleCXXVTable(RD, Out);
3373 return llvm::getPointerAuthStableSipHash(S: Str);
3374}
3375
3376/// Encode a function type for use in the discriminator of a function pointer
3377/// type. We can't use the itanium scheme for this since C has quite permissive
3378/// rules for type compatibility that we need to be compatible with.
3379///
3380/// Formally, this function associates every function pointer type T with an
3381/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3382/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3383/// compatibility requires equivalent treatment under the ABI, so
3384/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3385/// a subset of ~. Crucially, however, it must be a proper subset because
3386/// CCompatible is not an equivalence relation: for example, int[] is compatible
3387/// with both int[1] and int[2], but the latter are not compatible with each
3388/// other. Therefore this encoding function must be careful to only distinguish
3389/// types if there is no third type with which they are both required to be
3390/// compatible.
3391static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx,
3392 raw_ostream &OS, QualType QT) {
3393 // FIXME: Consider address space qualifiers.
3394 const Type *T = QT.getCanonicalType().getTypePtr();
3395
3396 // FIXME: Consider using the C++ type mangling when we encounter a construct
3397 // that is incompatible with C.
3398
3399 switch (T->getTypeClass()) {
3400 case Type::Atomic:
3401 return encodeTypeForFunctionPointerAuth(
3402 Ctx, OS, QT: cast<AtomicType>(Val: T)->getValueType());
3403
3404 case Type::LValueReference:
3405 OS << "R";
3406 encodeTypeForFunctionPointerAuth(Ctx, OS,
3407 QT: cast<ReferenceType>(Val: T)->getPointeeType());
3408 return;
3409 case Type::RValueReference:
3410 OS << "O";
3411 encodeTypeForFunctionPointerAuth(Ctx, OS,
3412 QT: cast<ReferenceType>(Val: T)->getPointeeType());
3413 return;
3414
3415 case Type::Pointer:
3416 // C11 6.7.6.1p2:
3417 // For two pointer types to be compatible, both shall be identically
3418 // qualified and both shall be pointers to compatible types.
3419 // FIXME: we should also consider pointee types.
3420 OS << "P";
3421 return;
3422
3423 case Type::ObjCObjectPointer:
3424 case Type::BlockPointer:
3425 OS << "P";
3426 return;
3427
3428 case Type::Complex:
3429 OS << "C";
3430 return encodeTypeForFunctionPointerAuth(
3431 Ctx, OS, QT: cast<ComplexType>(Val: T)->getElementType());
3432
3433 case Type::VariableArray:
3434 case Type::ConstantArray:
3435 case Type::IncompleteArray:
3436 case Type::ArrayParameter:
3437 // C11 6.7.6.2p6:
3438 // For two array types to be compatible, both shall have compatible
3439 // element types, and if both size specifiers are present, and are integer
3440 // constant expressions, then both size specifiers shall have the same
3441 // constant value [...]
3442 //
3443 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3444 // width of the array.
3445 OS << "A";
3446 return encodeTypeForFunctionPointerAuth(
3447 Ctx, OS, QT: cast<ArrayType>(Val: T)->getElementType());
3448
3449 case Type::ObjCInterface:
3450 case Type::ObjCObject:
3451 OS << "<objc_object>";
3452 return;
3453
3454 case Type::Enum: {
3455 // C11 6.7.2.2p4:
3456 // Each enumerated type shall be compatible with char, a signed integer
3457 // type, or an unsigned integer type.
3458 //
3459 // So we have to treat enum types as integers.
3460 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3461 return encodeTypeForFunctionPointerAuth(
3462 Ctx, OS, QT: UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3463 }
3464
3465 case Type::FunctionNoProto:
3466 case Type::FunctionProto: {
3467 // C11 6.7.6.3p15:
3468 // For two function types to be compatible, both shall specify compatible
3469 // return types. Moreover, the parameter type lists, if both are present,
3470 // shall agree in the number of parameters and in the use of the ellipsis
3471 // terminator; corresponding parameters shall have compatible types.
3472 //
3473 // That paragraph goes on to describe how unprototyped functions are to be
3474 // handled, which we ignore here. Unprototyped function pointers are hashed
3475 // as though they were prototyped nullary functions since thats probably
3476 // what the user meant. This behavior is non-conforming.
3477 // FIXME: If we add a "custom discriminator" function type attribute we
3478 // should encode functions as their discriminators.
3479 OS << "F";
3480 const auto *FuncType = cast<FunctionType>(Val: T);
3481 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: FuncType->getReturnType());
3482 if (const auto *FPT = dyn_cast<FunctionProtoType>(Val: FuncType)) {
3483 for (QualType Param : FPT->param_types()) {
3484 Param = Ctx.getSignatureParameterType(T: Param);
3485 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: Param);
3486 }
3487 if (FPT->isVariadic())
3488 OS << "z";
3489 }
3490 OS << "E";
3491 return;
3492 }
3493
3494 case Type::MemberPointer: {
3495 OS << "M";
3496 const auto *MPT = T->castAs<MemberPointerType>();
3497 encodeTypeForFunctionPointerAuth(
3498 Ctx, OS, QT: QualType(MPT->getQualifier().getAsType(), 0));
3499 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: MPT->getPointeeType());
3500 return;
3501 }
3502 case Type::ExtVector:
3503 case Type::Vector:
3504 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3505 break;
3506
3507 // Don't bother discriminating based on these types.
3508 case Type::Pipe:
3509 case Type::BitInt:
3510 case Type::ConstantMatrix:
3511 OS << "?";
3512 return;
3513
3514 case Type::Builtin: {
3515 const auto *BTy = T->castAs<BuiltinType>();
3516 switch (BTy->getKind()) {
3517#define SIGNED_TYPE(Id, SingletonId) \
3518 case BuiltinType::Id: \
3519 OS << "i"; \
3520 return;
3521#define UNSIGNED_TYPE(Id, SingletonId) \
3522 case BuiltinType::Id: \
3523 OS << "i"; \
3524 return;
3525#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3526#define BUILTIN_TYPE(Id, SingletonId)
3527#include "clang/AST/BuiltinTypes.def"
3528 llvm_unreachable("placeholder types should not appear here.");
3529
3530 case BuiltinType::Half:
3531 OS << "Dh";
3532 return;
3533 case BuiltinType::Float:
3534 OS << "f";
3535 return;
3536 case BuiltinType::Double:
3537 OS << "d";
3538 return;
3539 case BuiltinType::LongDouble:
3540 OS << "e";
3541 return;
3542 case BuiltinType::Float16:
3543 OS << "DF16_";
3544 return;
3545 case BuiltinType::Float128:
3546 OS << "g";
3547 return;
3548
3549 case BuiltinType::Void:
3550 OS << "v";
3551 return;
3552
3553 case BuiltinType::ObjCId:
3554 case BuiltinType::ObjCClass:
3555 case BuiltinType::ObjCSel:
3556 case BuiltinType::NullPtr:
3557 OS << "P";
3558 return;
3559
3560 // Don't bother discriminating based on OpenCL types.
3561 case BuiltinType::OCLSampler:
3562 case BuiltinType::OCLEvent:
3563 case BuiltinType::OCLClkEvent:
3564 case BuiltinType::OCLQueue:
3565 case BuiltinType::OCLReserveID:
3566 case BuiltinType::BFloat16:
3567 case BuiltinType::VectorQuad:
3568 case BuiltinType::VectorPair:
3569 case BuiltinType::DMR1024:
3570 case BuiltinType::DMR2048:
3571 OS << "?";
3572 return;
3573
3574 // Don't bother discriminating based on these seldom-used types.
3575 case BuiltinType::Ibm128:
3576 return;
3577#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3578 case BuiltinType::Id: \
3579 return;
3580#include "clang/Basic/OpenCLImageTypes.def"
3581#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3582 case BuiltinType::Id: \
3583 return;
3584#include "clang/Basic/OpenCLExtensionTypes.def"
3585#define SVE_TYPE(Name, Id, SingletonId) \
3586 case BuiltinType::Id: \
3587 return;
3588#include "clang/Basic/AArch64ACLETypes.def"
3589#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3590 case BuiltinType::Id: \
3591 return;
3592#include "clang/Basic/HLSLIntangibleTypes.def"
3593 case BuiltinType::Dependent:
3594 llvm_unreachable("should never get here");
3595#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3596#include "clang/Basic/AMDGPUTypes.def"
3597 case BuiltinType::WasmExternRef:
3598#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3599#include "clang/Basic/RISCVVTypes.def"
3600 llvm_unreachable("not yet implemented");
3601 }
3602 llvm_unreachable("should never get here");
3603 }
3604 case Type::Record: {
3605 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3606 const IdentifierInfo *II = RD->getIdentifier();
3607
3608 // In C++, an immediate typedef of an anonymous struct or union
3609 // is considered to name it for ODR purposes, but C's specification
3610 // of type compatibility does not have a similar rule. Using the typedef
3611 // name in function type discriminators anyway, as we do here,
3612 // therefore technically violates the C standard: two function pointer
3613 // types defined in terms of two typedef'd anonymous structs with
3614 // different names are formally still compatible, but we are assigning
3615 // them different discriminators and therefore incompatible ABIs.
3616 //
3617 // This is a relatively minor violation that significantly improves
3618 // discrimination in some cases and has not caused problems in
3619 // practice. Regardless, it is now part of the ABI in places where
3620 // function type discrimination is used, and it can no longer be
3621 // changed except on new platforms.
3622
3623 if (!II)
3624 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3625 II = Typedef->getDeclName().getAsIdentifierInfo();
3626
3627 if (!II) {
3628 OS << "<anonymous_record>";
3629 return;
3630 }
3631 OS << II->getLength() << II->getName();
3632 return;
3633 }
3634 case Type::HLSLAttributedResource:
3635 case Type::HLSLInlineSpirv:
3636 llvm_unreachable("should never get here");
3637 break;
3638 case Type::OverflowBehavior:
3639 llvm_unreachable("should never get here");
3640 break;
3641 case Type::DeducedTemplateSpecialization:
3642 case Type::Auto:
3643#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3644#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3645#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3646#define ABSTRACT_TYPE(Class, Base)
3647#define TYPE(Class, Base)
3648#include "clang/AST/TypeNodes.inc"
3649 llvm_unreachable("unexpected non-canonical or dependent type!");
3650 return;
3651 }
3652}
3653
3654uint16_t ASTContext::getPointerAuthTypeDiscriminator(QualType T) {
3655 assert(!T->isDependentType() &&
3656 "cannot compute type discriminator of a dependent type");
3657 SmallString<256> Str;
3658 llvm::raw_svector_ostream Out(Str);
3659
3660 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3661 T = T->getPointeeType();
3662
3663 if (T->isFunctionType()) {
3664 encodeTypeForFunctionPointerAuth(Ctx: *this, OS&: Out, QT: T);
3665 } else {
3666 T = T.getUnqualifiedType();
3667 // Calls to member function pointers don't need to worry about
3668 // language interop or the laxness of the C type compatibility rules.
3669 // We just mangle the member pointer type directly, which is
3670 // implicitly much stricter about type matching. However, we do
3671 // strip any top-level exception specification before this mangling.
3672 // C++23 requires calls to work when the function type is convertible
3673 // to the pointer type by a function pointer conversion, which can
3674 // change the exception specification. This does not technically
3675 // require the exception specification to not affect representation,
3676 // because the function pointer conversion is still always a direct
3677 // value conversion and therefore an opportunity to resign the
3678 // pointer. (This is in contrast to e.g. qualification conversions,
3679 // which can be applied in nested pointer positions, effectively
3680 // requiring qualified and unqualified representations to match.)
3681 // However, it is pragmatic to ignore exception specifications
3682 // because it allows a certain amount of `noexcept` mismatching
3683 // to not become a visible ODR problem. This also leaves some
3684 // room for the committee to add laxness to function pointer
3685 // conversions in future standards.
3686 if (auto *MPT = T->getAs<MemberPointerType>())
3687 if (MPT->isMemberFunctionPointer()) {
3688 QualType PointeeType = MPT->getPointeeType();
3689 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3690 EST_None) {
3691 QualType FT = getFunctionTypeWithExceptionSpec(Orig: PointeeType, ESI: EST_None);
3692 T = getMemberPointerType(T: FT, Qualifier: MPT->getQualifier(),
3693 Cls: MPT->getMostRecentCXXRecordDecl());
3694 }
3695 }
3696 std::unique_ptr<MangleContext> MC(createMangleContext());
3697 MC->mangleCanonicalTypeName(T, Out);
3698 }
3699
3700 return llvm::getPointerAuthStableSipHash(S: Str);
3701}
3702
3703QualType ASTContext::getObjCGCQualType(QualType T,
3704 Qualifiers::GC GCAttr) const {
3705 QualType CanT = getCanonicalType(T);
3706 if (CanT.getObjCGCAttr() == GCAttr)
3707 return T;
3708
3709 if (const auto *ptr = T->getAs<PointerType>()) {
3710 QualType Pointee = ptr->getPointeeType();
3711 if (Pointee->isAnyPointerType()) {
3712 QualType ResultType = getObjCGCQualType(T: Pointee, GCAttr);
3713 return getPointerType(T: ResultType);
3714 }
3715 }
3716
3717 // If we are composing extended qualifiers together, merge together
3718 // into one ExtQuals node.
3719 QualifierCollector Quals;
3720 const Type *TypeNode = Quals.strip(type: T);
3721
3722 // If this type already has an ObjCGC specified, it cannot get
3723 // another one.
3724 assert(!Quals.hasObjCGCAttr() &&
3725 "Type cannot have multiple ObjCGCs!");
3726 Quals.addObjCGCAttr(type: GCAttr);
3727
3728 return getExtQualType(baseType: TypeNode, quals: Quals);
3729}
3730
3731QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3732 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3733 QualType Pointee = Ptr->getPointeeType();
3734 if (isPtrSizeAddressSpace(AS: Pointee.getAddressSpace())) {
3735 return getPointerType(T: removeAddrSpaceQualType(T: Pointee));
3736 }
3737 }
3738 return T;
3739}
3740
3741QualType ASTContext::getCountAttributedType(
3742 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3743 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3744 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3745
3746 llvm::FoldingSetNodeID ID;
3747 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, Nullable: OrNull);
3748
3749 void *InsertPos = nullptr;
3750 CountAttributedType *CATy =
3751 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3752 if (CATy)
3753 return QualType(CATy, 0);
3754
3755 QualType CanonTy = getCanonicalType(T: WrappedTy);
3756 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3757 Counts: DependentDecls.size());
3758 CATy = (CountAttributedType *)Allocate(Size, Align: TypeAlignment);
3759 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3760 OrNull, DependentDecls);
3761 Types.push_back(Elt: CATy);
3762 CountAttributedTypes.InsertNode(N: CATy, InsertPos);
3763
3764 return QualType(CATy, 0);
3765}
3766
3767QualType
3768ASTContext::adjustType(QualType Orig,
3769 llvm::function_ref<QualType(QualType)> Adjust) const {
3770 switch (Orig->getTypeClass()) {
3771 case Type::Attributed: {
3772 const auto *AT = cast<AttributedType>(Val&: Orig);
3773 return getAttributedType(attrKind: AT->getAttrKind(),
3774 modifiedType: adjustType(Orig: AT->getModifiedType(), Adjust),
3775 equivalentType: adjustType(Orig: AT->getEquivalentType(), Adjust),
3776 attr: AT->getAttr());
3777 }
3778
3779 case Type::BTFTagAttributed: {
3780 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Val&: Orig);
3781 return getBTFTagAttributedType(BTFAttr: BTFT->getAttr(),
3782 Wrapped: adjustType(Orig: BTFT->getWrappedType(), Adjust));
3783 }
3784
3785 case Type::OverflowBehavior: {
3786 const auto *OB = dyn_cast<OverflowBehaviorType>(Val&: Orig);
3787 return getOverflowBehaviorType(Kind: OB->getBehaviorKind(),
3788 Wrapped: adjustType(Orig: OB->getUnderlyingType(), Adjust));
3789 }
3790
3791 case Type::Paren:
3792 return getParenType(
3793 NamedType: adjustType(Orig: cast<ParenType>(Val&: Orig)->getInnerType(), Adjust));
3794
3795 case Type::Adjusted: {
3796 const auto *AT = cast<AdjustedType>(Val&: Orig);
3797 return getAdjustedType(Orig: AT->getOriginalType(),
3798 New: adjustType(Orig: AT->getAdjustedType(), Adjust));
3799 }
3800
3801 case Type::MacroQualified: {
3802 const auto *MQT = cast<MacroQualifiedType>(Val&: Orig);
3803 return getMacroQualifiedType(UnderlyingTy: adjustType(Orig: MQT->getUnderlyingType(), Adjust),
3804 MacroII: MQT->getMacroIdentifier());
3805 }
3806
3807 default:
3808 return Adjust(Orig);
3809 }
3810}
3811
3812const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3813 FunctionType::ExtInfo Info) {
3814 if (T->getExtInfo() == Info)
3815 return T;
3816
3817 QualType Result;
3818 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(Val: T)) {
3819 Result = getFunctionNoProtoType(ResultTy: FNPT->getReturnType(), Info);
3820 } else {
3821 const auto *FPT = cast<FunctionProtoType>(Val: T);
3822 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3823 EPI.ExtInfo = Info;
3824 Result = getFunctionType(ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(), EPI);
3825 }
3826
3827 return cast<FunctionType>(Val: Result.getTypePtr());
3828}
3829
3830QualType ASTContext::adjustFunctionResultType(QualType FunctionType,
3831 QualType ResultType) {
3832 return adjustType(Orig: FunctionType, Adjust: [&](QualType Orig) {
3833 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3834 return getFunctionNoProtoType(ResultTy: ResultType, Info: FNPT->getExtInfo());
3835
3836 const auto *FPT = Orig->castAs<FunctionProtoType>();
3837 return getFunctionType(ResultTy: ResultType, Args: FPT->getParamTypes(),
3838 EPI: FPT->getExtProtoInfo());
3839 });
3840}
3841
3842void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3843 QualType ResultType) {
3844 FD = FD->getMostRecentDecl();
3845 while (true) {
3846 FD->setType(adjustFunctionResultType(FunctionType: FD->getType(), ResultType));
3847 if (FunctionDecl *Next = FD->getPreviousDecl())
3848 FD = Next;
3849 else
3850 break;
3851 }
3852 if (ASTMutationListener *L = getASTMutationListener())
3853 L->DeducedReturnType(FD, ReturnType: ResultType);
3854}
3855
3856/// Get a function type and produce the equivalent function type with the
3857/// specified exception specification. Type sugar that can be present on a
3858/// declaration of a function with an exception specification is permitted
3859/// and preserved. Other type sugar (for instance, typedefs) is not.
3860QualType ASTContext::getFunctionTypeWithExceptionSpec(
3861 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3862 return adjustType(Orig, Adjust: [&](QualType Ty) {
3863 const auto *Proto = Ty->castAs<FunctionProtoType>();
3864 return getFunctionType(ResultTy: Proto->getReturnType(), Args: Proto->getParamTypes(),
3865 EPI: Proto->getExtProtoInfo().withExceptionSpec(ESI));
3866 });
3867}
3868
3869bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3870 QualType U) const {
3871 return hasSameType(T1: T, T2: U) ||
3872 (getLangOpts().CPlusPlus17 &&
3873 hasSameType(T1: getFunctionTypeWithExceptionSpec(Orig: T, ESI: EST_None),
3874 T2: getFunctionTypeWithExceptionSpec(Orig: U, ESI: EST_None)));
3875}
3876
3877QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3878 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3879 QualType RetTy = removePtrSizeAddrSpace(T: Proto->getReturnType());
3880 SmallVector<QualType, 16> Args(Proto->param_types().size());
3881 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3882 Args[i] = removePtrSizeAddrSpace(T: Proto->param_types()[i]);
3883 return getFunctionType(ResultTy: RetTy, Args, EPI: Proto->getExtProtoInfo());
3884 }
3885
3886 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3887 QualType RetTy = removePtrSizeAddrSpace(T: Proto->getReturnType());
3888 return getFunctionNoProtoType(ResultTy: RetTy, Info: Proto->getExtInfo());
3889 }
3890
3891 return T;
3892}
3893
3894bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3895 return hasSameType(T1: T, T2: U) ||
3896 hasSameType(T1: getFunctionTypeWithoutPtrSizes(T),
3897 T2: getFunctionTypeWithoutPtrSizes(T: U));
3898}
3899
3900QualType ASTContext::getFunctionTypeWithoutParamABIs(QualType T) const {
3901 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3902 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3903 EPI.ExtParameterInfos = nullptr;
3904 return getFunctionType(ResultTy: Proto->getReturnType(), Args: Proto->param_types(), EPI);
3905 }
3906 return T;
3907}
3908
3909bool ASTContext::hasSameFunctionTypeIgnoringParamABI(QualType T,
3910 QualType U) const {
3911 return hasSameType(T1: T, T2: U) || hasSameType(T1: getFunctionTypeWithoutParamABIs(T),
3912 T2: getFunctionTypeWithoutParamABIs(T: U));
3913}
3914
3915void ASTContext::adjustExceptionSpec(
3916 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3917 bool AsWritten) {
3918 // Update the type.
3919 QualType Updated =
3920 getFunctionTypeWithExceptionSpec(Orig: FD->getType(), ESI);
3921 FD->setType(Updated);
3922
3923 if (!AsWritten)
3924 return;
3925
3926 // Update the type in the type source information too.
3927 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3928 // If the type and the type-as-written differ, we may need to update
3929 // the type-as-written too.
3930 if (TSInfo->getType() != FD->getType())
3931 Updated = getFunctionTypeWithExceptionSpec(Orig: TSInfo->getType(), ESI);
3932
3933 // FIXME: When we get proper type location information for exceptions,
3934 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3935 // up the TypeSourceInfo;
3936 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3937 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3938 "TypeLoc size mismatch from updating exception specification");
3939 TSInfo->overrideType(T: Updated);
3940 }
3941}
3942
3943/// getComplexType - Return the uniqued reference to the type for a complex
3944/// number with the specified element type.
3945QualType ASTContext::getComplexType(QualType T) const {
3946 // Unique pointers, to guarantee there is only one pointer of a particular
3947 // structure.
3948 llvm::FoldingSetNodeID ID;
3949 ComplexType::Profile(ID, Element: T);
3950
3951 void *InsertPos = nullptr;
3952 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3953 return QualType(CT, 0);
3954
3955 // If the pointee type isn't canonical, this won't be a canonical type either,
3956 // so fill in the canonical type field.
3957 QualType Canonical;
3958 if (!T.isCanonical()) {
3959 Canonical = getComplexType(T: getCanonicalType(T));
3960
3961 // Get the new insert position for the node we care about.
3962 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3963 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3964 }
3965 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3966 Types.push_back(Elt: New);
3967 ComplexTypes.InsertNode(N: New, InsertPos);
3968 return QualType(New, 0);
3969}
3970
3971/// getPointerType - Return the uniqued reference to the type for a pointer to
3972/// the specified type.
3973QualType ASTContext::getPointerType(QualType T) const {
3974 // Unique pointers, to guarantee there is only one pointer of a particular
3975 // structure.
3976 llvm::FoldingSetNodeID ID;
3977 PointerType::Profile(ID, Pointee: T);
3978
3979 void *InsertPos = nullptr;
3980 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3981 return QualType(PT, 0);
3982
3983 // If the pointee type isn't canonical, this won't be a canonical type either,
3984 // so fill in the canonical type field.
3985 QualType Canonical;
3986 if (!T.isCanonical()) {
3987 Canonical = getPointerType(T: getCanonicalType(T));
3988
3989 // Get the new insert position for the node we care about.
3990 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3991 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3992 }
3993 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3994 Types.push_back(Elt: New);
3995 PointerTypes.InsertNode(N: New, InsertPos);
3996 return QualType(New, 0);
3997}
3998
3999QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
4000 llvm::FoldingSetNodeID ID;
4001 AdjustedType::Profile(ID, Orig, New);
4002 void *InsertPos = nullptr;
4003 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4004 if (AT)
4005 return QualType(AT, 0);
4006
4007 QualType Canonical = getCanonicalType(T: New);
4008
4009 // Get the new insert position for the node we care about.
4010 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4011 assert(!AT && "Shouldn't be in the map!");
4012
4013 AT = new (*this, alignof(AdjustedType))
4014 AdjustedType(Type::Adjusted, Orig, New, Canonical);
4015 Types.push_back(Elt: AT);
4016 AdjustedTypes.InsertNode(N: AT, InsertPos);
4017 return QualType(AT, 0);
4018}
4019
4020QualType ASTContext::getDecayedType(QualType Orig, QualType Decayed) const {
4021 llvm::FoldingSetNodeID ID;
4022 AdjustedType::Profile(ID, Orig, New: Decayed);
4023 void *InsertPos = nullptr;
4024 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4025 if (AT)
4026 return QualType(AT, 0);
4027
4028 QualType Canonical = getCanonicalType(T: Decayed);
4029
4030 // Get the new insert position for the node we care about.
4031 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4032 assert(!AT && "Shouldn't be in the map!");
4033
4034 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
4035 Types.push_back(Elt: AT);
4036 AdjustedTypes.InsertNode(N: AT, InsertPos);
4037 return QualType(AT, 0);
4038}
4039
4040QualType ASTContext::getDecayedType(QualType T) const {
4041 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
4042
4043 QualType Decayed;
4044
4045 // C99 6.7.5.3p7:
4046 // A declaration of a parameter as "array of type" shall be
4047 // adjusted to "qualified pointer to type", where the type
4048 // qualifiers (if any) are those specified within the [ and ] of
4049 // the array type derivation.
4050 if (T->isArrayType())
4051 Decayed = getArrayDecayedType(T);
4052
4053 // C99 6.7.5.3p8:
4054 // A declaration of a parameter as "function returning type"
4055 // shall be adjusted to "pointer to function returning type", as
4056 // in 6.3.2.1.
4057 if (T->isFunctionType())
4058 Decayed = getPointerType(T);
4059
4060 return getDecayedType(Orig: T, Decayed);
4061}
4062
4063QualType ASTContext::getArrayParameterType(QualType Ty) const {
4064 if (Ty->isArrayParameterType())
4065 return Ty;
4066 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4067 QualType DTy = Ty.getDesugaredType(Context: *this);
4068 const auto *ATy = cast<ConstantArrayType>(Val&: DTy);
4069 llvm::FoldingSetNodeID ID;
4070 ATy->Profile(ID, Ctx: *this, ET: ATy->getElementType(), ArraySize: ATy->getZExtSize(),
4071 SizeExpr: ATy->getSizeExpr(), SizeMod: ATy->getSizeModifier(),
4072 TypeQuals: ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4073 void *InsertPos = nullptr;
4074 ArrayParameterType *AT =
4075 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4076 if (AT)
4077 return QualType(AT, 0);
4078
4079 QualType Canonical;
4080 if (!DTy.isCanonical()) {
4081 Canonical = getArrayParameterType(Ty: getCanonicalType(T: Ty));
4082
4083 // Get the new insert position for the node we care about.
4084 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4085 assert(!AT && "Shouldn't be in the map!");
4086 }
4087
4088 AT = new (*this, alignof(ArrayParameterType))
4089 ArrayParameterType(ATy, Canonical);
4090 Types.push_back(Elt: AT);
4091 ArrayParameterTypes.InsertNode(N: AT, InsertPos);
4092 return QualType(AT, 0);
4093}
4094
4095/// getBlockPointerType - Return the uniqued reference to the type for
4096/// a pointer to the specified block.
4097QualType ASTContext::getBlockPointerType(QualType T) const {
4098 assert(T->isFunctionType() && "block of function types only");
4099 // Unique pointers, to guarantee there is only one block of a particular
4100 // structure.
4101 llvm::FoldingSetNodeID ID;
4102 BlockPointerType::Profile(ID, Pointee: T);
4103
4104 void *InsertPos = nullptr;
4105 if (BlockPointerType *PT =
4106 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4107 return QualType(PT, 0);
4108
4109 // If the block pointee type isn't canonical, this won't be a canonical
4110 // type either so fill in the canonical type field.
4111 QualType Canonical;
4112 if (!T.isCanonical()) {
4113 Canonical = getBlockPointerType(T: getCanonicalType(T));
4114
4115 // Get the new insert position for the node we care about.
4116 BlockPointerType *NewIP =
4117 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4118 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4119 }
4120 auto *New =
4121 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4122 Types.push_back(Elt: New);
4123 BlockPointerTypes.InsertNode(N: New, InsertPos);
4124 return QualType(New, 0);
4125}
4126
4127/// getLValueReferenceType - Return the uniqued reference to the type for an
4128/// lvalue reference to the specified type.
4129QualType
4130ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4131 assert((!T->isPlaceholderType() ||
4132 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4133 "Unresolved placeholder type");
4134
4135 // Unique pointers, to guarantee there is only one pointer of a particular
4136 // structure.
4137 llvm::FoldingSetNodeID ID;
4138 ReferenceType::Profile(ID, Referencee: T, SpelledAsLValue);
4139
4140 void *InsertPos = nullptr;
4141 if (LValueReferenceType *RT =
4142 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4143 return QualType(RT, 0);
4144
4145 const auto *InnerRef = T->getAs<ReferenceType>();
4146
4147 // If the referencee type isn't canonical, this won't be a canonical type
4148 // either, so fill in the canonical type field.
4149 QualType Canonical;
4150 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4151 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4152 Canonical = getLValueReferenceType(T: getCanonicalType(T: PointeeType));
4153
4154 // Get the new insert position for the node we care about.
4155 LValueReferenceType *NewIP =
4156 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4157 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4158 }
4159
4160 auto *New = new (*this, alignof(LValueReferenceType))
4161 LValueReferenceType(T, Canonical, SpelledAsLValue);
4162 Types.push_back(Elt: New);
4163 LValueReferenceTypes.InsertNode(N: New, InsertPos);
4164
4165 return QualType(New, 0);
4166}
4167
4168/// getRValueReferenceType - Return the uniqued reference to the type for an
4169/// rvalue reference to the specified type.
4170QualType ASTContext::getRValueReferenceType(QualType T) const {
4171 assert((!T->isPlaceholderType() ||
4172 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4173 "Unresolved placeholder type");
4174
4175 // Unique pointers, to guarantee there is only one pointer of a particular
4176 // structure.
4177 llvm::FoldingSetNodeID ID;
4178 ReferenceType::Profile(ID, Referencee: T, SpelledAsLValue: false);
4179
4180 void *InsertPos = nullptr;
4181 if (RValueReferenceType *RT =
4182 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4183 return QualType(RT, 0);
4184
4185 const auto *InnerRef = T->getAs<ReferenceType>();
4186
4187 // If the referencee type isn't canonical, this won't be a canonical type
4188 // either, so fill in the canonical type field.
4189 QualType Canonical;
4190 if (InnerRef || !T.isCanonical()) {
4191 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4192 Canonical = getRValueReferenceType(T: getCanonicalType(T: PointeeType));
4193
4194 // Get the new insert position for the node we care about.
4195 RValueReferenceType *NewIP =
4196 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4197 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4198 }
4199
4200 auto *New = new (*this, alignof(RValueReferenceType))
4201 RValueReferenceType(T, Canonical);
4202 Types.push_back(Elt: New);
4203 RValueReferenceTypes.InsertNode(N: New, InsertPos);
4204 return QualType(New, 0);
4205}
4206
4207QualType ASTContext::getMemberPointerType(QualType T,
4208 NestedNameSpecifier Qualifier,
4209 const CXXRecordDecl *Cls) const {
4210 if (!Qualifier) {
4211 assert(Cls && "At least one of Qualifier or Cls must be provided");
4212 Qualifier = NestedNameSpecifier(getCanonicalTagType(TD: Cls).getTypePtr());
4213 } else if (!Cls) {
4214 Cls = Qualifier.getAsRecordDecl();
4215 }
4216 // Unique pointers, to guarantee there is only one pointer of a particular
4217 // structure.
4218 llvm::FoldingSetNodeID ID;
4219 MemberPointerType::Profile(ID, Pointee: T, Qualifier, Cls);
4220
4221 void *InsertPos = nullptr;
4222 if (MemberPointerType *PT =
4223 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4224 return QualType(PT, 0);
4225
4226 NestedNameSpecifier CanonicalQualifier = [&] {
4227 if (!Cls)
4228 return Qualifier.getCanonical();
4229 NestedNameSpecifier R(getCanonicalTagType(TD: Cls).getTypePtr());
4230 assert(R.isCanonical());
4231 return R;
4232 }();
4233 // If the pointee or class type isn't canonical, this won't be a canonical
4234 // type either, so fill in the canonical type field.
4235 QualType Canonical;
4236 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4237 Canonical =
4238 getMemberPointerType(T: getCanonicalType(T), Qualifier: CanonicalQualifier, Cls);
4239 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4240 // Get the new insert position for the node we care about.
4241 [[maybe_unused]] MemberPointerType *NewIP =
4242 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4243 assert(!NewIP && "Shouldn't be in the map!");
4244 }
4245 auto *New = new (*this, alignof(MemberPointerType))
4246 MemberPointerType(T, Qualifier, Canonical);
4247 Types.push_back(Elt: New);
4248 MemberPointerTypes.InsertNode(N: New, InsertPos);
4249 return QualType(New, 0);
4250}
4251
4252/// getConstantArrayType - Return the unique reference to the type for an
4253/// array of the specified element type.
4254QualType ASTContext::getConstantArrayType(QualType EltTy,
4255 const llvm::APInt &ArySizeIn,
4256 const Expr *SizeExpr,
4257 ArraySizeModifier ASM,
4258 unsigned IndexTypeQuals) const {
4259 assert((EltTy->isDependentType() ||
4260 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4261 "Constant array of VLAs is illegal!");
4262
4263 // We only need the size as part of the type if it's instantiation-dependent.
4264 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4265 SizeExpr = nullptr;
4266
4267 // Convert the array size into a canonical width matching the pointer size for
4268 // the target.
4269 llvm::APInt ArySize(ArySizeIn);
4270 ArySize = ArySize.zextOrTrunc(width: Target->getMaxPointerWidth());
4271
4272 llvm::FoldingSetNodeID ID;
4273 ConstantArrayType::Profile(ID, Ctx: *this, ET: EltTy, ArraySize: ArySize.getZExtValue(), SizeExpr,
4274 SizeMod: ASM, TypeQuals: IndexTypeQuals);
4275
4276 void *InsertPos = nullptr;
4277 if (ConstantArrayType *ATP =
4278 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4279 return QualType(ATP, 0);
4280
4281 // If the element type isn't canonical or has qualifiers, or the array bound
4282 // is instantiation-dependent, this won't be a canonical type either, so fill
4283 // in the canonical type field.
4284 QualType Canon;
4285 // FIXME: Check below should look for qualifiers behind sugar.
4286 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4287 SplitQualType canonSplit = getCanonicalType(T: EltTy).split();
4288 Canon = getConstantArrayType(EltTy: QualType(canonSplit.Ty, 0), ArySizeIn: ArySize, SizeExpr: nullptr,
4289 ASM, IndexTypeQuals);
4290 Canon = getQualifiedType(T: Canon, Qs: canonSplit.Quals);
4291
4292 // Get the new insert position for the node we care about.
4293 ConstantArrayType *NewIP =
4294 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4295 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4296 }
4297
4298 auto *New = ConstantArrayType::Create(Ctx: *this, ET: EltTy, Can: Canon, Sz: ArySize, SzExpr: SizeExpr,
4299 SzMod: ASM, Qual: IndexTypeQuals);
4300 ConstantArrayTypes.InsertNode(N: New, InsertPos);
4301 Types.push_back(Elt: New);
4302 return QualType(New, 0);
4303}
4304
4305/// getVariableArrayDecayedType - Turns the given type, which may be
4306/// variably-modified, into the corresponding type with all the known
4307/// sizes replaced with [*].
4308QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
4309 // Vastly most common case.
4310 if (!type->isVariablyModifiedType()) return type;
4311
4312 QualType result;
4313
4314 SplitQualType split = type.getSplitDesugaredType();
4315 const Type *ty = split.Ty;
4316 switch (ty->getTypeClass()) {
4317#define TYPE(Class, Base)
4318#define ABSTRACT_TYPE(Class, Base)
4319#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4320#include "clang/AST/TypeNodes.inc"
4321 llvm_unreachable("didn't desugar past all non-canonical types?");
4322
4323 // These types should never be variably-modified.
4324 case Type::Builtin:
4325 case Type::Complex:
4326 case Type::Vector:
4327 case Type::DependentVector:
4328 case Type::ExtVector:
4329 case Type::DependentSizedExtVector:
4330 case Type::ConstantMatrix:
4331 case Type::DependentSizedMatrix:
4332 case Type::DependentAddressSpace:
4333 case Type::ObjCObject:
4334 case Type::ObjCInterface:
4335 case Type::ObjCObjectPointer:
4336 case Type::Record:
4337 case Type::Enum:
4338 case Type::UnresolvedUsing:
4339 case Type::TypeOfExpr:
4340 case Type::TypeOf:
4341 case Type::Decltype:
4342 case Type::UnaryTransform:
4343 case Type::DependentName:
4344 case Type::InjectedClassName:
4345 case Type::TemplateSpecialization:
4346 case Type::TemplateTypeParm:
4347 case Type::SubstTemplateTypeParmPack:
4348 case Type::SubstBuiltinTemplatePack:
4349 case Type::Auto:
4350 case Type::DeducedTemplateSpecialization:
4351 case Type::PackExpansion:
4352 case Type::PackIndexing:
4353 case Type::BitInt:
4354 case Type::DependentBitInt:
4355 case Type::ArrayParameter:
4356 case Type::HLSLAttributedResource:
4357 case Type::HLSLInlineSpirv:
4358 case Type::OverflowBehavior:
4359 llvm_unreachable("type should never be variably-modified");
4360
4361 // These types can be variably-modified but should never need to
4362 // further decay.
4363 case Type::FunctionNoProto:
4364 case Type::FunctionProto:
4365 case Type::BlockPointer:
4366 case Type::MemberPointer:
4367 case Type::Pipe:
4368 return type;
4369
4370 // These types can be variably-modified. All these modifications
4371 // preserve structure except as noted by comments.
4372 // TODO: if we ever care about optimizing VLAs, there are no-op
4373 // optimizations available here.
4374 case Type::Pointer:
4375 result = getPointerType(T: getVariableArrayDecayedType(
4376 type: cast<PointerType>(Val: ty)->getPointeeType()));
4377 break;
4378
4379 case Type::LValueReference: {
4380 const auto *lv = cast<LValueReferenceType>(Val: ty);
4381 result = getLValueReferenceType(
4382 T: getVariableArrayDecayedType(type: lv->getPointeeType()),
4383 SpelledAsLValue: lv->isSpelledAsLValue());
4384 break;
4385 }
4386
4387 case Type::RValueReference: {
4388 const auto *lv = cast<RValueReferenceType>(Val: ty);
4389 result = getRValueReferenceType(
4390 T: getVariableArrayDecayedType(type: lv->getPointeeType()));
4391 break;
4392 }
4393
4394 case Type::Atomic: {
4395 const auto *at = cast<AtomicType>(Val: ty);
4396 result = getAtomicType(T: getVariableArrayDecayedType(type: at->getValueType()));
4397 break;
4398 }
4399
4400 case Type::ConstantArray: {
4401 const auto *cat = cast<ConstantArrayType>(Val: ty);
4402 result = getConstantArrayType(
4403 EltTy: getVariableArrayDecayedType(type: cat->getElementType()),
4404 ArySizeIn: cat->getSize(),
4405 SizeExpr: cat->getSizeExpr(),
4406 ASM: cat->getSizeModifier(),
4407 IndexTypeQuals: cat->getIndexTypeCVRQualifiers());
4408 break;
4409 }
4410
4411 case Type::DependentSizedArray: {
4412 const auto *dat = cast<DependentSizedArrayType>(Val: ty);
4413 result = getDependentSizedArrayType(
4414 EltTy: getVariableArrayDecayedType(type: dat->getElementType()), NumElts: dat->getSizeExpr(),
4415 ASM: dat->getSizeModifier(), IndexTypeQuals: dat->getIndexTypeCVRQualifiers());
4416 break;
4417 }
4418
4419 // Turn incomplete types into [*] types.
4420 case Type::IncompleteArray: {
4421 const auto *iat = cast<IncompleteArrayType>(Val: ty);
4422 result =
4423 getVariableArrayType(EltTy: getVariableArrayDecayedType(type: iat->getElementType()),
4424 /*size*/ NumElts: nullptr, ASM: ArraySizeModifier::Normal,
4425 IndexTypeQuals: iat->getIndexTypeCVRQualifiers());
4426 break;
4427 }
4428
4429 // Turn VLA types into [*] types.
4430 case Type::VariableArray: {
4431 const auto *vat = cast<VariableArrayType>(Val: ty);
4432 result =
4433 getVariableArrayType(EltTy: getVariableArrayDecayedType(type: vat->getElementType()),
4434 /*size*/ NumElts: nullptr, ASM: ArraySizeModifier::Star,
4435 IndexTypeQuals: vat->getIndexTypeCVRQualifiers());
4436 break;
4437 }
4438 }
4439
4440 // Apply the top-level qualifiers from the original.
4441 return getQualifiedType(T: result, Qs: split.Quals);
4442}
4443
4444/// getVariableArrayType - Returns a non-unique reference to the type for a
4445/// variable array of the specified element type.
4446QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
4447 ArraySizeModifier ASM,
4448 unsigned IndexTypeQuals) const {
4449 // Since we don't unique expressions, it isn't possible to unique VLA's
4450 // that have an expression provided for their size.
4451 QualType Canon;
4452
4453 // Be sure to pull qualifiers off the element type.
4454 // FIXME: Check below should look for qualifiers behind sugar.
4455 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4456 SplitQualType canonSplit = getCanonicalType(T: EltTy).split();
4457 Canon = getVariableArrayType(EltTy: QualType(canonSplit.Ty, 0), NumElts, ASM,
4458 IndexTypeQuals);
4459 Canon = getQualifiedType(T: Canon, Qs: canonSplit.Quals);
4460 }
4461
4462 auto *New = new (*this, alignof(VariableArrayType))
4463 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4464
4465 VariableArrayTypes.push_back(x: New);
4466 Types.push_back(Elt: New);
4467 return QualType(New, 0);
4468}
4469
4470/// getDependentSizedArrayType - Returns a non-unique reference to
4471/// the type for a dependently-sized array of the specified element
4472/// type.
4473QualType
4474ASTContext::getDependentSizedArrayType(QualType elementType, Expr *numElements,
4475 ArraySizeModifier ASM,
4476 unsigned elementTypeQuals) const {
4477 assert((!numElements || numElements->isTypeDependent() ||
4478 numElements->isValueDependent()) &&
4479 "Size must be type- or value-dependent!");
4480
4481 SplitQualType canonElementType = getCanonicalType(T: elementType).split();
4482
4483 void *insertPos = nullptr;
4484 llvm::FoldingSetNodeID ID;
4485 DependentSizedArrayType::Profile(
4486 ID, Context: *this, ET: numElements ? QualType(canonElementType.Ty, 0) : elementType,
4487 SizeMod: ASM, TypeQuals: elementTypeQuals, E: numElements);
4488
4489 // Look for an existing type with these properties.
4490 DependentSizedArrayType *canonTy =
4491 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos&: insertPos);
4492
4493 // Dependently-sized array types that do not have a specified number
4494 // of elements will have their sizes deduced from a dependent
4495 // initializer.
4496 if (!numElements) {
4497 if (canonTy)
4498 return QualType(canonTy, 0);
4499
4500 auto *newType = new (*this, alignof(DependentSizedArrayType))
4501 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4502 elementTypeQuals);
4503 DependentSizedArrayTypes.InsertNode(N: newType, InsertPos: insertPos);
4504 Types.push_back(Elt: newType);
4505 return QualType(newType, 0);
4506 }
4507
4508 // If we don't have one, build one.
4509 if (!canonTy) {
4510 canonTy = new (*this, alignof(DependentSizedArrayType))
4511 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4512 numElements, ASM, elementTypeQuals);
4513 DependentSizedArrayTypes.InsertNode(N: canonTy, InsertPos: insertPos);
4514 Types.push_back(Elt: canonTy);
4515 }
4516
4517 // Apply qualifiers from the element type to the array.
4518 QualType canon = getQualifiedType(T: QualType(canonTy,0),
4519 Qs: canonElementType.Quals);
4520
4521 // If we didn't need extra canonicalization for the element type or the size
4522 // expression, then just use that as our result.
4523 if (QualType(canonElementType.Ty, 0) == elementType &&
4524 canonTy->getSizeExpr() == numElements)
4525 return canon;
4526
4527 // Otherwise, we need to build a type which follows the spelling
4528 // of the element type.
4529 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4530 DependentSizedArrayType(elementType, canon, numElements, ASM,
4531 elementTypeQuals);
4532 Types.push_back(Elt: sugaredType);
4533 return QualType(sugaredType, 0);
4534}
4535
4536QualType ASTContext::getIncompleteArrayType(QualType elementType,
4537 ArraySizeModifier ASM,
4538 unsigned elementTypeQuals) const {
4539 llvm::FoldingSetNodeID ID;
4540 IncompleteArrayType::Profile(ID, ET: elementType, SizeMod: ASM, TypeQuals: elementTypeQuals);
4541
4542 void *insertPos = nullptr;
4543 if (IncompleteArrayType *iat =
4544 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos&: insertPos))
4545 return QualType(iat, 0);
4546
4547 // If the element type isn't canonical, this won't be a canonical type
4548 // either, so fill in the canonical type field. We also have to pull
4549 // qualifiers off the element type.
4550 QualType canon;
4551
4552 // FIXME: Check below should look for qualifiers behind sugar.
4553 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4554 SplitQualType canonSplit = getCanonicalType(T: elementType).split();
4555 canon = getIncompleteArrayType(elementType: QualType(canonSplit.Ty, 0),
4556 ASM, elementTypeQuals);
4557 canon = getQualifiedType(T: canon, Qs: canonSplit.Quals);
4558
4559 // Get the new insert position for the node we care about.
4560 IncompleteArrayType *existing =
4561 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos&: insertPos);
4562 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4563 }
4564
4565 auto *newType = new (*this, alignof(IncompleteArrayType))
4566 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4567
4568 IncompleteArrayTypes.InsertNode(N: newType, InsertPos: insertPos);
4569 Types.push_back(Elt: newType);
4570 return QualType(newType, 0);
4571}
4572
4573ASTContext::BuiltinVectorTypeInfo
4574ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
4575#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4576 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4577 NUMVECTORS};
4578
4579#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4580 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4581
4582 switch (Ty->getKind()) {
4583 default:
4584 llvm_unreachable("Unsupported builtin vector type");
4585
4586#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4587 ElBits, NF, IsSigned) \
4588 case BuiltinType::Id: \
4589 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4590 llvm::ElementCount::getScalable(NumEls), NF};
4591#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4592 ElBits, NF) \
4593 case BuiltinType::Id: \
4594 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4595 llvm::ElementCount::getScalable(NumEls), NF};
4596#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4597 ElBits, NF) \
4598 case BuiltinType::Id: \
4599 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4600#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4601 ElBits, NF) \
4602 case BuiltinType::Id: \
4603 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4604#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4605 case BuiltinType::Id: \
4606 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4607#include "clang/Basic/AArch64ACLETypes.def"
4608
4609#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4610 IsSigned) \
4611 case BuiltinType::Id: \
4612 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4613 llvm::ElementCount::getScalable(NumEls), NF};
4614#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4615 case BuiltinType::Id: \
4616 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4617 llvm::ElementCount::getScalable(NumEls), NF};
4618#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4619 case BuiltinType::Id: \
4620 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4621#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4622 case BuiltinType::Id: \
4623 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4624#include "clang/Basic/RISCVVTypes.def"
4625 }
4626}
4627
4628/// getExternrefType - Return a WebAssembly externref type, which represents an
4629/// opaque reference to a host value.
4630QualType ASTContext::getWebAssemblyExternrefType() const {
4631 if (Target->getTriple().isWasm() && Target->hasFeature(Feature: "reference-types")) {
4632#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4633 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4634 return SingletonId;
4635#include "clang/Basic/WebAssemblyReferenceTypes.def"
4636 }
4637 llvm_unreachable(
4638 "shouldn't try to generate type externref outside WebAssembly target");
4639}
4640
4641/// getScalableVectorType - Return the unique reference to a scalable vector
4642/// type of the specified element type and size. VectorType must be a built-in
4643/// type.
4644QualType ASTContext::getScalableVectorType(QualType EltTy, unsigned NumElts,
4645 unsigned NumFields) const {
4646 auto K = llvm::ScalableVecTyKey{.EltTy: EltTy, .NumElts: NumElts, .NumFields: NumFields};
4647 if (auto It = ScalableVecTyMap.find(Val: K); It != ScalableVecTyMap.end())
4648 return It->second;
4649
4650 if (Target->hasAArch64ACLETypes()) {
4651 uint64_t EltTySize = getTypeSize(T: EltTy);
4652
4653#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4654 ElBits, NF, IsSigned) \
4655 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4656 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4657 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4658 return ScalableVecTyMap[K] = SingletonId; \
4659 }
4660#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4661 ElBits, NF) \
4662 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4663 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4664 return ScalableVecTyMap[K] = SingletonId; \
4665 }
4666#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4667 ElBits, NF) \
4668 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4669 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4670 return ScalableVecTyMap[K] = SingletonId; \
4671 }
4672#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4673 ElBits, NF) \
4674 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4675 NumElts == (NumEls * NF) && NumFields == 1) { \
4676 return ScalableVecTyMap[K] = SingletonId; \
4677 }
4678#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4679 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4680 return ScalableVecTyMap[K] = SingletonId;
4681#include "clang/Basic/AArch64ACLETypes.def"
4682 } else if (Target->hasRISCVVTypes()) {
4683 uint64_t EltTySize = getTypeSize(T: EltTy);
4684#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4685 IsFP, IsBF) \
4686 if (!EltTy->isBooleanType() && \
4687 ((EltTy->hasIntegerRepresentation() && \
4688 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4689 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4690 IsFP && !IsBF) || \
4691 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4692 IsBF && !IsFP)) && \
4693 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4694 return ScalableVecTyMap[K] = SingletonId;
4695#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4696 if (EltTy->isBooleanType() && NumElts == NumEls) \
4697 return ScalableVecTyMap[K] = SingletonId;
4698#include "clang/Basic/RISCVVTypes.def"
4699 }
4700 return QualType();
4701}
4702
4703/// getVectorType - Return the unique reference to a vector type of
4704/// the specified element type and size. VectorType must be a built-in type.
4705QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
4706 VectorKind VecKind) const {
4707 assert(vecType->isBuiltinType() ||
4708 (vecType->isBitIntType() &&
4709 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4710 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4711
4712 // Check if we've already instantiated a vector of this type.
4713 llvm::FoldingSetNodeID ID;
4714 VectorType::Profile(ID, ElementType: vecType, NumElements: NumElts, TypeClass: Type::Vector, VecKind);
4715
4716 void *InsertPos = nullptr;
4717 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4718 return QualType(VTP, 0);
4719
4720 // If the element type isn't canonical, this won't be a canonical type either,
4721 // so fill in the canonical type field.
4722 QualType Canonical;
4723 if (!vecType.isCanonical()) {
4724 Canonical = getVectorType(vecType: getCanonicalType(T: vecType), NumElts, VecKind);
4725
4726 // Get the new insert position for the node we care about.
4727 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4728 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4729 }
4730 auto *New = new (*this, alignof(VectorType))
4731 VectorType(vecType, NumElts, Canonical, VecKind);
4732 VectorTypes.InsertNode(N: New, InsertPos);
4733 Types.push_back(Elt: New);
4734 return QualType(New, 0);
4735}
4736
4737QualType ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
4738 SourceLocation AttrLoc,
4739 VectorKind VecKind) const {
4740 llvm::FoldingSetNodeID ID;
4741 DependentVectorType::Profile(ID, Context: *this, ElementType: getCanonicalType(T: VecType), SizeExpr,
4742 VecKind);
4743 void *InsertPos = nullptr;
4744 DependentVectorType *Canon =
4745 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4746 DependentVectorType *New;
4747
4748 if (Canon) {
4749 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4750 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4751 } else {
4752 QualType CanonVecTy = getCanonicalType(T: VecType);
4753 if (CanonVecTy == VecType) {
4754 New = new (*this, alignof(DependentVectorType))
4755 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4756
4757 DependentVectorType *CanonCheck =
4758 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4759 assert(!CanonCheck &&
4760 "Dependent-sized vector_size canonical type broken");
4761 (void)CanonCheck;
4762 DependentVectorTypes.InsertNode(N: New, InsertPos);
4763 } else {
4764 QualType CanonTy = getDependentVectorType(VecType: CanonVecTy, SizeExpr,
4765 AttrLoc: SourceLocation(), VecKind);
4766 New = new (*this, alignof(DependentVectorType))
4767 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4768 }
4769 }
4770
4771 Types.push_back(Elt: New);
4772 return QualType(New, 0);
4773}
4774
4775/// getExtVectorType - Return the unique reference to an extended vector type of
4776/// the specified element type and size. VectorType must be a built-in type.
4777QualType ASTContext::getExtVectorType(QualType vecType,
4778 unsigned NumElts) const {
4779 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4780 (vecType->isBitIntType() &&
4781 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4782 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4783
4784 // Check if we've already instantiated a vector of this type.
4785 llvm::FoldingSetNodeID ID;
4786 VectorType::Profile(ID, ElementType: vecType, NumElements: NumElts, TypeClass: Type::ExtVector,
4787 VecKind: VectorKind::Generic);
4788 void *InsertPos = nullptr;
4789 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4790 return QualType(VTP, 0);
4791
4792 // If the element type isn't canonical, this won't be a canonical type either,
4793 // so fill in the canonical type field.
4794 QualType Canonical;
4795 if (!vecType.isCanonical()) {
4796 Canonical = getExtVectorType(vecType: getCanonicalType(T: vecType), NumElts);
4797
4798 // Get the new insert position for the node we care about.
4799 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4800 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4801 }
4802 auto *New = new (*this, alignof(ExtVectorType))
4803 ExtVectorType(vecType, NumElts, Canonical);
4804 VectorTypes.InsertNode(N: New, InsertPos);
4805 Types.push_back(Elt: New);
4806 return QualType(New, 0);
4807}
4808
4809QualType
4810ASTContext::getDependentSizedExtVectorType(QualType vecType,
4811 Expr *SizeExpr,
4812 SourceLocation AttrLoc) const {
4813 llvm::FoldingSetNodeID ID;
4814 DependentSizedExtVectorType::Profile(ID, Context: *this, ElementType: getCanonicalType(T: vecType),
4815 SizeExpr);
4816
4817 void *InsertPos = nullptr;
4818 DependentSizedExtVectorType *Canon
4819 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4820 DependentSizedExtVectorType *New;
4821 if (Canon) {
4822 // We already have a canonical version of this array type; use it as
4823 // the canonical type for a newly-built type.
4824 New = new (*this, alignof(DependentSizedExtVectorType))
4825 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4826 AttrLoc);
4827 } else {
4828 QualType CanonVecTy = getCanonicalType(T: vecType);
4829 if (CanonVecTy == vecType) {
4830 New = new (*this, alignof(DependentSizedExtVectorType))
4831 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4832
4833 DependentSizedExtVectorType *CanonCheck
4834 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4835 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4836 (void)CanonCheck;
4837 DependentSizedExtVectorTypes.InsertNode(N: New, InsertPos);
4838 } else {
4839 QualType CanonExtTy = getDependentSizedExtVectorType(vecType: CanonVecTy, SizeExpr,
4840 AttrLoc: SourceLocation());
4841 New = new (*this, alignof(DependentSizedExtVectorType))
4842 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4843 }
4844 }
4845
4846 Types.push_back(Elt: New);
4847 return QualType(New, 0);
4848}
4849
4850QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
4851 unsigned NumColumns) const {
4852 llvm::FoldingSetNodeID ID;
4853 ConstantMatrixType::Profile(ID, ElementType: ElementTy, NumRows, NumColumns,
4854 TypeClass: Type::ConstantMatrix);
4855
4856 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4857 "need a valid element type");
4858 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4859 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4860 "need valid matrix dimensions");
4861 void *InsertPos = nullptr;
4862 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4863 return QualType(MTP, 0);
4864
4865 QualType Canonical;
4866 if (!ElementTy.isCanonical()) {
4867 Canonical =
4868 getConstantMatrixType(ElementTy: getCanonicalType(T: ElementTy), NumRows, NumColumns);
4869
4870 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4871 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4872 (void)NewIP;
4873 }
4874
4875 auto *New = new (*this, alignof(ConstantMatrixType))
4876 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4877 MatrixTypes.InsertNode(N: New, InsertPos);
4878 Types.push_back(Elt: New);
4879 return QualType(New, 0);
4880}
4881
4882QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4883 Expr *RowExpr,
4884 Expr *ColumnExpr,
4885 SourceLocation AttrLoc) const {
4886 QualType CanonElementTy = getCanonicalType(T: ElementTy);
4887 llvm::FoldingSetNodeID ID;
4888 DependentSizedMatrixType::Profile(ID, Context: *this, ElementType: CanonElementTy, RowExpr,
4889 ColumnExpr);
4890
4891 void *InsertPos = nullptr;
4892 DependentSizedMatrixType *Canon =
4893 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4894
4895 if (!Canon) {
4896 Canon = new (*this, alignof(DependentSizedMatrixType))
4897 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4898 ColumnExpr, AttrLoc);
4899#ifndef NDEBUG
4900 DependentSizedMatrixType *CanonCheck =
4901 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4902 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4903#endif
4904 DependentSizedMatrixTypes.InsertNode(N: Canon, InsertPos);
4905 Types.push_back(Elt: Canon);
4906 }
4907
4908 // Already have a canonical version of the matrix type
4909 //
4910 // If it exactly matches the requested type, use it directly.
4911 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4912 Canon->getRowExpr() == ColumnExpr)
4913 return QualType(Canon, 0);
4914
4915 // Use Canon as the canonical type for newly-built type.
4916 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4917 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4918 ColumnExpr, AttrLoc);
4919 Types.push_back(Elt: New);
4920 return QualType(New, 0);
4921}
4922
4923QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4924 Expr *AddrSpaceExpr,
4925 SourceLocation AttrLoc) const {
4926 assert(AddrSpaceExpr->isInstantiationDependent());
4927
4928 QualType canonPointeeType = getCanonicalType(T: PointeeType);
4929
4930 void *insertPos = nullptr;
4931 llvm::FoldingSetNodeID ID;
4932 DependentAddressSpaceType::Profile(ID, Context: *this, PointeeType: canonPointeeType,
4933 AddrSpaceExpr);
4934
4935 DependentAddressSpaceType *canonTy =
4936 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, InsertPos&: insertPos);
4937
4938 if (!canonTy) {
4939 canonTy = new (*this, alignof(DependentAddressSpaceType))
4940 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4941 AttrLoc);
4942 DependentAddressSpaceTypes.InsertNode(N: canonTy, InsertPos: insertPos);
4943 Types.push_back(Elt: canonTy);
4944 }
4945
4946 if (canonPointeeType == PointeeType &&
4947 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4948 return QualType(canonTy, 0);
4949
4950 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4951 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4952 AddrSpaceExpr, AttrLoc);
4953 Types.push_back(Elt: sugaredType);
4954 return QualType(sugaredType, 0);
4955}
4956
4957/// Determine whether \p T is canonical as the result type of a function.
4958static bool isCanonicalResultType(QualType T) {
4959 return T.isCanonical() &&
4960 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4961 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4962}
4963
4964/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4965QualType
4966ASTContext::getFunctionNoProtoType(QualType ResultTy,
4967 const FunctionType::ExtInfo &Info) const {
4968 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4969 // functionality creates a function without a prototype regardless of
4970 // language mode (so it makes them even in C++). Once the rewriter has been
4971 // fixed, this assertion can be enabled again.
4972 //assert(!LangOpts.requiresStrictPrototypes() &&
4973 // "strict prototypes are disabled");
4974
4975 // Unique functions, to guarantee there is only one function of a particular
4976 // structure.
4977 llvm::FoldingSetNodeID ID;
4978 FunctionNoProtoType::Profile(ID, ResultType: ResultTy, Info);
4979
4980 void *InsertPos = nullptr;
4981 if (FunctionNoProtoType *FT =
4982 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4983 return QualType(FT, 0);
4984
4985 QualType Canonical;
4986 if (!isCanonicalResultType(T: ResultTy)) {
4987 Canonical =
4988 getFunctionNoProtoType(ResultTy: getCanonicalFunctionResultType(ResultType: ResultTy), Info);
4989
4990 // Get the new insert position for the node we care about.
4991 FunctionNoProtoType *NewIP =
4992 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4993 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4994 }
4995
4996 auto *New = new (*this, alignof(FunctionNoProtoType))
4997 FunctionNoProtoType(ResultTy, Canonical, Info);
4998 Types.push_back(Elt: New);
4999 FunctionNoProtoTypes.InsertNode(N: New, InsertPos);
5000 return QualType(New, 0);
5001}
5002
5003CanQualType
5004ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
5005 CanQualType CanResultType = getCanonicalType(T: ResultType);
5006
5007 // Canonical result types do not have ARC lifetime qualifiers.
5008 if (CanResultType.getQualifiers().hasObjCLifetime()) {
5009 Qualifiers Qs = CanResultType.getQualifiers();
5010 Qs.removeObjCLifetime();
5011 return CanQualType::CreateUnsafe(
5012 Other: getQualifiedType(T: CanResultType.getUnqualifiedType(), Qs));
5013 }
5014
5015 return CanResultType;
5016}
5017
5018static bool isCanonicalExceptionSpecification(
5019 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
5020 if (ESI.Type == EST_None)
5021 return true;
5022 if (!NoexceptInType)
5023 return false;
5024
5025 // C++17 onwards: exception specification is part of the type, as a simple
5026 // boolean "can this function type throw".
5027 if (ESI.Type == EST_BasicNoexcept)
5028 return true;
5029
5030 // A noexcept(expr) specification is (possibly) canonical if expr is
5031 // value-dependent.
5032 if (ESI.Type == EST_DependentNoexcept)
5033 return true;
5034
5035 // A dynamic exception specification is canonical if it only contains pack
5036 // expansions (so we can't tell whether it's non-throwing) and all its
5037 // contained types are canonical.
5038 if (ESI.Type == EST_Dynamic) {
5039 bool AnyPackExpansions = false;
5040 for (QualType ET : ESI.Exceptions) {
5041 if (!ET.isCanonical())
5042 return false;
5043 if (ET->getAs<PackExpansionType>())
5044 AnyPackExpansions = true;
5045 }
5046 return AnyPackExpansions;
5047 }
5048
5049 return false;
5050}
5051
5052QualType ASTContext::getFunctionTypeInternal(
5053 QualType ResultTy, ArrayRef<QualType> ArgArray,
5054 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
5055 size_t NumArgs = ArgArray.size();
5056
5057 // Unique functions, to guarantee there is only one function of a particular
5058 // structure.
5059 llvm::FoldingSetNodeID ID;
5060 FunctionProtoType::Profile(ID, Result: ResultTy, ArgTys: ArgArray.begin(), NumArgs, EPI,
5061 Context: *this, Canonical: true);
5062
5063 QualType Canonical;
5064 bool Unique = false;
5065
5066 void *InsertPos = nullptr;
5067 if (FunctionProtoType *FPT =
5068 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5069 QualType Existing = QualType(FPT, 0);
5070
5071 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5072 // it so long as our exception specification doesn't contain a dependent
5073 // noexcept expression, or we're just looking for a canonical type.
5074 // Otherwise, we're going to need to create a type
5075 // sugar node to hold the concrete expression.
5076 if (OnlyWantCanonical || !isComputedNoexcept(ESpecType: EPI.ExceptionSpec.Type) ||
5077 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5078 return Existing;
5079
5080 // We need a new type sugar node for this one, to hold the new noexcept
5081 // expression. We do no canonicalization here, but that's OK since we don't
5082 // expect to see the same noexcept expression much more than once.
5083 Canonical = getCanonicalType(T: Existing);
5084 Unique = true;
5085 }
5086
5087 bool NoexceptInType = getLangOpts().CPlusPlus17;
5088 bool IsCanonicalExceptionSpec =
5089 isCanonicalExceptionSpecification(ESI: EPI.ExceptionSpec, NoexceptInType);
5090
5091 // Determine whether the type being created is already canonical or not.
5092 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5093 isCanonicalResultType(T: ResultTy) && !EPI.HasTrailingReturn;
5094 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5095 if (!ArgArray[i].isCanonicalAsParam())
5096 isCanonical = false;
5097
5098 if (OnlyWantCanonical)
5099 assert(isCanonical &&
5100 "given non-canonical parameters constructing canonical type");
5101
5102 // If this type isn't canonical, get the canonical version of it if we don't
5103 // already have it. The exception spec is only partially part of the
5104 // canonical type, and only in C++17 onwards.
5105 if (!isCanonical && Canonical.isNull()) {
5106 SmallVector<QualType, 16> CanonicalArgs;
5107 CanonicalArgs.reserve(N: NumArgs);
5108 for (unsigned i = 0; i != NumArgs; ++i)
5109 CanonicalArgs.push_back(Elt: getCanonicalParamType(T: ArgArray[i]));
5110
5111 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5112 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5113 CanonicalEPI.HasTrailingReturn = false;
5114
5115 if (IsCanonicalExceptionSpec) {
5116 // Exception spec is already OK.
5117 } else if (NoexceptInType) {
5118 switch (EPI.ExceptionSpec.Type) {
5119 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
5120 // We don't know yet. It shouldn't matter what we pick here; no-one
5121 // should ever look at this.
5122 [[fallthrough]];
5123 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5124 CanonicalEPI.ExceptionSpec.Type = EST_None;
5125 break;
5126
5127 // A dynamic exception specification is almost always "not noexcept",
5128 // with the exception that a pack expansion might expand to no types.
5129 case EST_Dynamic: {
5130 bool AnyPacks = false;
5131 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5132 if (ET->getAs<PackExpansionType>())
5133 AnyPacks = true;
5134 ExceptionTypeStorage.push_back(Elt: getCanonicalType(T: ET));
5135 }
5136 if (!AnyPacks)
5137 CanonicalEPI.ExceptionSpec.Type = EST_None;
5138 else {
5139 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5140 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5141 }
5142 break;
5143 }
5144
5145 case EST_DynamicNone:
5146 case EST_BasicNoexcept:
5147 case EST_NoexceptTrue:
5148 case EST_NoThrow:
5149 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5150 break;
5151
5152 case EST_DependentNoexcept:
5153 llvm_unreachable("dependent noexcept is already canonical");
5154 }
5155 } else {
5156 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5157 }
5158
5159 // Adjust the canonical function result type.
5160 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultType: ResultTy);
5161 Canonical =
5162 getFunctionTypeInternal(ResultTy: CanResultTy, ArgArray: CanonicalArgs, EPI: CanonicalEPI, OnlyWantCanonical: true);
5163
5164 // Get the new insert position for the node we care about.
5165 FunctionProtoType *NewIP =
5166 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5167 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5168 }
5169
5170 // Compute the needed size to hold this FunctionProtoType and the
5171 // various trailing objects.
5172 auto ESH = FunctionProtoType::getExceptionSpecSize(
5173 EST: EPI.ExceptionSpec.Type, NumExceptions: EPI.ExceptionSpec.Exceptions.size());
5174 size_t Size = FunctionProtoType::totalSizeToAlloc<
5175 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5176 FunctionType::FunctionTypeExtraAttributeInfo,
5177 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5178 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5179 FunctionEffect, EffectConditionExpr>(
5180 Counts: NumArgs, Counts: EPI.Variadic, Counts: EPI.requiresFunctionProtoTypeExtraBitfields(),
5181 Counts: EPI.requiresFunctionProtoTypeExtraAttributeInfo(),
5182 Counts: EPI.requiresFunctionProtoTypeArmAttributes(), Counts: ESH.NumExceptionType,
5183 Counts: ESH.NumExprPtr, Counts: ESH.NumFunctionDeclPtr,
5184 Counts: EPI.ExtParameterInfos ? NumArgs : 0,
5185 Counts: EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0, Counts: EPI.FunctionEffects.size(),
5186 Counts: EPI.FunctionEffects.conditions().size());
5187
5188 auto *FTP = (FunctionProtoType *)Allocate(Size, Align: alignof(FunctionProtoType));
5189 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5190 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5191 Types.push_back(Elt: FTP);
5192 if (!Unique)
5193 FunctionProtoTypes.InsertNode(N: FTP, InsertPos);
5194 if (!EPI.FunctionEffects.empty())
5195 AnyFunctionEffects = true;
5196 return QualType(FTP, 0);
5197}
5198
5199QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5200 llvm::FoldingSetNodeID ID;
5201 PipeType::Profile(ID, T, isRead: ReadOnly);
5202
5203 void *InsertPos = nullptr;
5204 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5205 return QualType(PT, 0);
5206
5207 // If the pipe element type isn't canonical, this won't be a canonical type
5208 // either, so fill in the canonical type field.
5209 QualType Canonical;
5210 if (!T.isCanonical()) {
5211 Canonical = getPipeType(T: getCanonicalType(T), ReadOnly);
5212
5213 // Get the new insert position for the node we care about.
5214 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5215 assert(!NewIP && "Shouldn't be in the map!");
5216 (void)NewIP;
5217 }
5218 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5219 Types.push_back(Elt: New);
5220 PipeTypes.InsertNode(N: New, InsertPos);
5221 return QualType(New, 0);
5222}
5223
5224QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
5225 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5226 return LangOpts.OpenCL ? getAddrSpaceQualType(T: Ty, AddressSpace: LangAS::opencl_constant)
5227 : Ty;
5228}
5229
5230QualType ASTContext::getReadPipeType(QualType T) const {
5231 return getPipeType(T, ReadOnly: true);
5232}
5233
5234QualType ASTContext::getWritePipeType(QualType T) const {
5235 return getPipeType(T, ReadOnly: false);
5236}
5237
5238QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5239 llvm::FoldingSetNodeID ID;
5240 BitIntType::Profile(ID, IsUnsigned, NumBits);
5241
5242 void *InsertPos = nullptr;
5243 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5244 return QualType(EIT, 0);
5245
5246 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5247 BitIntTypes.InsertNode(N: New, InsertPos);
5248 Types.push_back(Elt: New);
5249 return QualType(New, 0);
5250}
5251
5252QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
5253 Expr *NumBitsExpr) const {
5254 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5255 llvm::FoldingSetNodeID ID;
5256 DependentBitIntType::Profile(ID, Context: *this, IsUnsigned, NumBitsExpr);
5257
5258 void *InsertPos = nullptr;
5259 if (DependentBitIntType *Existing =
5260 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5261 return QualType(Existing, 0);
5262
5263 auto *New = new (*this, alignof(DependentBitIntType))
5264 DependentBitIntType(IsUnsigned, NumBitsExpr);
5265 DependentBitIntTypes.InsertNode(N: New, InsertPos);
5266
5267 Types.push_back(Elt: New);
5268 return QualType(New, 0);
5269}
5270
5271QualType
5272ASTContext::getPredefinedSugarType(PredefinedSugarType::Kind KD) const {
5273 using Kind = PredefinedSugarType::Kind;
5274
5275 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(E: KD)];
5276 Target != nullptr)
5277 return QualType(Target, 0);
5278
5279 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5280 switch (KDI) {
5281 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5282 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5283 // are part of the core language and are widely used. Using
5284 // PredefinedSugarType makes these types as named sugar types rather than
5285 // standard integer types, enabling better hints and diagnostics.
5286 case Kind::SizeT:
5287 return Ctx.getFromTargetType(Type: Ctx.Target->getSizeType());
5288 case Kind::SignedSizeT:
5289 return Ctx.getFromTargetType(Type: Ctx.Target->getSignedSizeType());
5290 case Kind::PtrdiffT:
5291 return Ctx.getFromTargetType(Type: Ctx.Target->getPtrDiffType(AddrSpace: LangAS::Default));
5292 }
5293 llvm_unreachable("unexpected kind");
5294 };
5295 auto *New = new (*this, alignof(PredefinedSugarType))
5296 PredefinedSugarType(KD, &Idents.get(Name: PredefinedSugarType::getName(KD)),
5297 getCanonicalType(*this, static_cast<Kind>(KD)));
5298 Types.push_back(Elt: New);
5299 PredefinedSugarTypes[llvm::to_underlying(E: KD)] = New;
5300 return QualType(New, 0);
5301}
5302
5303QualType ASTContext::getTypeDeclType(ElaboratedTypeKeyword Keyword,
5304 NestedNameSpecifier Qualifier,
5305 const TypeDecl *Decl) const {
5306 if (auto *Tag = dyn_cast<TagDecl>(Val: Decl))
5307 return getTagType(Keyword, Qualifier, TD: Tag,
5308 /*OwnsTag=*/false);
5309 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Val: Decl))
5310 return getTypedefType(Keyword, Qualifier, Decl: Typedef);
5311 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: Decl))
5312 return getUnresolvedUsingType(Keyword, Qualifier, D: UD);
5313
5314 assert(Keyword == ElaboratedTypeKeyword::None);
5315 assert(!Qualifier);
5316 return QualType(Decl->TypeForDecl, 0);
5317}
5318
5319CanQualType ASTContext::getCanonicalTypeDeclType(const TypeDecl *TD) const {
5320 if (auto *Tag = dyn_cast<TagDecl>(Val: TD))
5321 return getCanonicalTagType(TD: Tag);
5322 if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TD))
5323 return getCanonicalType(T: TN->getUnderlyingType());
5324 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TD))
5325 return getCanonicalUnresolvedUsingType(D: UD);
5326 assert(TD->TypeForDecl);
5327 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5328}
5329
5330QualType ASTContext::getTypeDeclType(const TypeDecl *Decl) const {
5331 if (const auto *TD = dyn_cast<TagDecl>(Val: Decl))
5332 return getCanonicalTagType(TD);
5333 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: Decl);
5334 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(Val: TD))
5335 return getTypedefType(Keyword: ElaboratedTypeKeyword::None,
5336 /*Qualifier=*/std::nullopt, Decl: TD);
5337 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Val: Decl))
5338 return getCanonicalUnresolvedUsingType(D: Using);
5339
5340 assert(Decl->TypeForDecl);
5341 return QualType(Decl->TypeForDecl, 0);
5342}
5343
5344/// getTypedefType - Return the unique reference to the type for the
5345/// specified typedef name decl.
5346QualType
5347ASTContext::getTypedefType(ElaboratedTypeKeyword Keyword,
5348 NestedNameSpecifier Qualifier,
5349 const TypedefNameDecl *Decl, QualType UnderlyingType,
5350 std::optional<bool> TypeMatchesDeclOrNone) const {
5351 if (!TypeMatchesDeclOrNone) {
5352 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5353 assert(!DeclUnderlyingType.isNull());
5354 if (UnderlyingType.isNull())
5355 UnderlyingType = DeclUnderlyingType;
5356 else
5357 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5358 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5359 } else {
5360 // FIXME: This is a workaround for a serialization cycle: assume the decl
5361 // underlying type is not available; don't touch it.
5362 assert(!UnderlyingType.isNull());
5363 }
5364
5365 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5366 *TypeMatchesDeclOrNone) {
5367 if (Decl->TypeForDecl)
5368 return QualType(Decl->TypeForDecl, 0);
5369
5370 auto *NewType = new (*this, alignof(TypedefType))
5371 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5372 !*TypeMatchesDeclOrNone);
5373
5374 Types.push_back(Elt: NewType);
5375 Decl->TypeForDecl = NewType;
5376 return QualType(NewType, 0);
5377 }
5378
5379 llvm::FoldingSetNodeID ID;
5380 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5381 Underlying: *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5382
5383 void *InsertPos = nullptr;
5384 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5385 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5386 return QualType(Placeholder->getType(), 0);
5387
5388 void *Mem =
5389 Allocate(Size: TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5390 NestedNameSpecifier, QualType>(
5391 Counts: 1, Counts: !!Qualifier, Counts: !*TypeMatchesDeclOrNone),
5392 Align: alignof(TypedefType));
5393 auto *NewType =
5394 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5395 UnderlyingType, !*TypeMatchesDeclOrNone);
5396 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5397 FoldingSetPlaceholder<TypedefType>();
5398 TypedefTypes.InsertNode(N: Placeholder, InsertPos);
5399 Types.push_back(Elt: NewType);
5400 return QualType(NewType, 0);
5401}
5402
5403QualType ASTContext::getUsingType(ElaboratedTypeKeyword Keyword,
5404 NestedNameSpecifier Qualifier,
5405 const UsingShadowDecl *D,
5406 QualType UnderlyingType) const {
5407 // FIXME: This is expensive to compute every time!
5408 if (UnderlyingType.isNull()) {
5409 const auto *UD = cast<UsingDecl>(Val: D->getIntroducer());
5410 UnderlyingType =
5411 getTypeDeclType(Keyword: UD->hasTypename() ? ElaboratedTypeKeyword::Typename
5412 : ElaboratedTypeKeyword::None,
5413 Qualifier: UD->getQualifier(), Decl: cast<TypeDecl>(Val: D->getTargetDecl()));
5414 }
5415
5416 llvm::FoldingSetNodeID ID;
5417 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5418
5419 void *InsertPos = nullptr;
5420 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5421 return QualType(T, 0);
5422
5423 assert(!UnderlyingType.hasLocalQualifiers());
5424
5425 assert(
5426 hasSameType(getCanonicalTypeDeclType(cast<TypeDecl>(D->getTargetDecl())),
5427 UnderlyingType));
5428
5429 void *Mem =
5430 Allocate(Size: UsingType::totalSizeToAlloc<NestedNameSpecifier>(Counts: !!Qualifier),
5431 Align: alignof(UsingType));
5432 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5433 Types.push_back(Elt: T);
5434 UsingTypes.InsertNode(N: T, InsertPos);
5435 return QualType(T, 0);
5436}
5437
5438TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5439 NestedNameSpecifier Qualifier,
5440 const TagDecl *TD, bool OwnsTag,
5441 bool IsInjected,
5442 const Type *CanonicalType,
5443 bool WithFoldingSetNode) const {
5444 auto [TC, Size] = [&] {
5445 switch (TD->getDeclKind()) {
5446 case Decl::Enum:
5447 static_assert(alignof(EnumType) == alignof(TagType));
5448 return std::make_tuple(args: Type::Enum, args: sizeof(EnumType));
5449 case Decl::ClassTemplatePartialSpecialization:
5450 case Decl::ClassTemplateSpecialization:
5451 case Decl::CXXRecord:
5452 static_assert(alignof(RecordType) == alignof(TagType));
5453 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5454 if (cast<CXXRecordDecl>(Val: TD)->hasInjectedClassType())
5455 return std::make_tuple(args: Type::InjectedClassName,
5456 args: sizeof(InjectedClassNameType));
5457 [[fallthrough]];
5458 case Decl::Record:
5459 return std::make_tuple(args: Type::Record, args: sizeof(RecordType));
5460 default:
5461 llvm_unreachable("unexpected decl kind");
5462 }
5463 }();
5464
5465 if (Qualifier) {
5466 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5467 Size = llvm::alignTo(Value: Size, Align: alignof(NestedNameSpecifier)) +
5468 sizeof(NestedNameSpecifier);
5469 }
5470 void *Mem;
5471 if (WithFoldingSetNode) {
5472 // FIXME: It would be more profitable to tail allocate the folding set node
5473 // from the type, instead of the other way around, due to the greater
5474 // alignment requirements of the type. But this makes it harder to deal with
5475 // the different type node sizes. This would require either uniquing from
5476 // different folding sets, or having the folding setaccept a
5477 // contextual parameter which is not fixed at construction.
5478 Mem = Allocate(
5479 Size: sizeof(TagTypeFoldingSetPlaceholder) +
5480 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5481 Align: std::max(a: alignof(TagTypeFoldingSetPlaceholder), b: alignof(TagType)));
5482 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5483 Mem = T->getTagType();
5484 } else {
5485 Mem = Allocate(Size, Align: alignof(TagType));
5486 }
5487
5488 auto *T = [&, TC = TC]() -> TagType * {
5489 switch (TC) {
5490 case Type::Enum: {
5491 assert(isa<EnumDecl>(TD));
5492 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5493 IsInjected, CanonicalType);
5494 assert(reinterpret_cast<void *>(T) ==
5495 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5496 "TagType must be the first base of EnumType");
5497 return T;
5498 }
5499 case Type::Record: {
5500 assert(isa<RecordDecl>(TD));
5501 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5502 IsInjected, CanonicalType);
5503 assert(reinterpret_cast<void *>(T) ==
5504 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5505 "TagType must be the first base of RecordType");
5506 return T;
5507 }
5508 case Type::InjectedClassName: {
5509 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5510 IsInjected, CanonicalType);
5511 assert(reinterpret_cast<void *>(T) ==
5512 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5513 "TagType must be the first base of InjectedClassNameType");
5514 return T;
5515 }
5516 default:
5517 llvm_unreachable("unexpected type class");
5518 }
5519 }();
5520 assert(T->getKeyword() == Keyword);
5521 assert(T->getQualifier() == Qualifier);
5522 assert(T->getDecl() == TD);
5523 assert(T->isInjected() == IsInjected);
5524 assert(T->isTagOwned() == OwnsTag);
5525 assert((T->isCanonicalUnqualified()
5526 ? QualType()
5527 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5528 Types.push_back(Elt: T);
5529 return T;
5530}
5531
5532static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5533 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: TD);
5534 RD && RD->isInjectedClassName())
5535 return cast<TagDecl>(Val: RD->getDeclContext());
5536 return TD;
5537}
5538
5539CanQualType ASTContext::getCanonicalTagType(const TagDecl *TD) const {
5540 TD = ::getNonInjectedClassName(TD)->getCanonicalDecl();
5541 if (TD->TypeForDecl)
5542 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5543
5544 const Type *CanonicalType = getTagTypeInternal(
5545 Keyword: ElaboratedTypeKeyword::None,
5546 /*Qualifier=*/std::nullopt, TD,
5547 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5548 /*WithFoldingSetNode=*/false);
5549 TD->TypeForDecl = CanonicalType;
5550 return CanQualType::CreateUnsafe(Other: QualType(CanonicalType, 0));
5551}
5552
5553QualType ASTContext::getTagType(ElaboratedTypeKeyword Keyword,
5554 NestedNameSpecifier Qualifier,
5555 const TagDecl *TD, bool OwnsTag) const {
5556
5557 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5558 bool IsInjected = TD != NonInjectedTD;
5559
5560 ElaboratedTypeKeyword PreferredKeyword =
5561 getLangOpts().CPlusPlus ? ElaboratedTypeKeyword::None
5562 : KeywordHelpers::getKeywordForTagTypeKind(
5563 Tag: NonInjectedTD->getTagKind());
5564
5565 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5566 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5567 return QualType(T, 0);
5568
5569 const Type *CanonicalType = getCanonicalTagType(TD: NonInjectedTD).getTypePtr();
5570 const Type *T =
5571 getTagTypeInternal(Keyword,
5572 /*Qualifier=*/std::nullopt, TD: NonInjectedTD,
5573 /*OwnsTag=*/false, IsInjected, CanonicalType,
5574 /*WithFoldingSetNode=*/false);
5575 TD->TypeForDecl = T;
5576 return QualType(T, 0);
5577 }
5578
5579 llvm::FoldingSetNodeID ID;
5580 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, Tag: NonInjectedTD,
5581 OwnsTag, IsInjected);
5582
5583 void *InsertPos = nullptr;
5584 if (TagTypeFoldingSetPlaceholder *T =
5585 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5586 return QualType(T->getTagType(), 0);
5587
5588 const Type *CanonicalType = getCanonicalTagType(TD: NonInjectedTD).getTypePtr();
5589 TagType *T =
5590 getTagTypeInternal(Keyword, Qualifier, TD: NonInjectedTD, OwnsTag, IsInjected,
5591 CanonicalType, /*WithFoldingSetNode=*/true);
5592 TagTypes.InsertNode(N: TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5593 return QualType(T, 0);
5594}
5595
5596bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5597 unsigned NumPositiveBits,
5598 QualType &BestType,
5599 QualType &BestPromotionType) {
5600 unsigned IntWidth = Target->getIntWidth();
5601 unsigned CharWidth = Target->getCharWidth();
5602 unsigned ShortWidth = Target->getShortWidth();
5603 bool EnumTooLarge = false;
5604 unsigned BestWidth;
5605 if (NumNegativeBits) {
5606 // If there is a negative value, figure out the smallest integer type (of
5607 // int/long/longlong) that fits.
5608 // If it's packed, check also if it fits a char or a short.
5609 if (IsPacked && NumNegativeBits <= CharWidth &&
5610 NumPositiveBits < CharWidth) {
5611 BestType = SignedCharTy;
5612 BestWidth = CharWidth;
5613 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5614 NumPositiveBits < ShortWidth) {
5615 BestType = ShortTy;
5616 BestWidth = ShortWidth;
5617 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5618 BestType = IntTy;
5619 BestWidth = IntWidth;
5620 } else {
5621 BestWidth = Target->getLongWidth();
5622
5623 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5624 BestType = LongTy;
5625 } else {
5626 BestWidth = Target->getLongLongWidth();
5627
5628 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5629 EnumTooLarge = true;
5630 BestType = LongLongTy;
5631 }
5632 }
5633 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5634 } else {
5635 // If there is no negative value, figure out the smallest type that fits
5636 // all of the enumerator values.
5637 // If it's packed, check also if it fits a char or a short.
5638 if (IsPacked && NumPositiveBits <= CharWidth) {
5639 BestType = UnsignedCharTy;
5640 BestPromotionType = IntTy;
5641 BestWidth = CharWidth;
5642 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5643 BestType = UnsignedShortTy;
5644 BestPromotionType = IntTy;
5645 BestWidth = ShortWidth;
5646 } else if (NumPositiveBits <= IntWidth) {
5647 BestType = UnsignedIntTy;
5648 BestWidth = IntWidth;
5649 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5650 ? UnsignedIntTy
5651 : IntTy;
5652 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5653 BestType = UnsignedLongTy;
5654 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5655 ? UnsignedLongTy
5656 : LongTy;
5657 } else {
5658 BestWidth = Target->getLongLongWidth();
5659 if (NumPositiveBits > BestWidth) {
5660 // This can happen with bit-precise integer types, but those are not
5661 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5662 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5663 // a 128-bit integer, we should consider doing the same.
5664 EnumTooLarge = true;
5665 }
5666 BestType = UnsignedLongLongTy;
5667 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5668 ? UnsignedLongLongTy
5669 : LongLongTy;
5670 }
5671 }
5672 return EnumTooLarge;
5673}
5674
5675bool ASTContext::isRepresentableIntegerValue(llvm::APSInt &Value, QualType T) {
5676 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5677 "Integral type required!");
5678 unsigned BitWidth = getIntWidth(T);
5679
5680 if (Value.isUnsigned() || Value.isNonNegative()) {
5681 if (T->isSignedIntegerOrEnumerationType())
5682 --BitWidth;
5683 return Value.getActiveBits() <= BitWidth;
5684 }
5685 return Value.getSignificantBits() <= BitWidth;
5686}
5687
5688UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5689 ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier,
5690 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5691 const Type *CanonicalType) const {
5692 void *Mem = Allocate(
5693 Size: UnresolvedUsingType::totalSizeToAlloc<
5694 FoldingSetPlaceholder<UnresolvedUsingType>, NestedNameSpecifier>(
5695 Counts: !!InsertPos, Counts: !!Qualifier),
5696 Align: alignof(UnresolvedUsingType));
5697 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5698 if (InsertPos) {
5699 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5700 FoldingSetPlaceholder<TypedefType>();
5701 TypedefTypes.InsertNode(N: Placeholder, InsertPos);
5702 }
5703 Types.push_back(Elt: T);
5704 return T;
5705}
5706
5707CanQualType ASTContext::getCanonicalUnresolvedUsingType(
5708 const UnresolvedUsingTypenameDecl *D) const {
5709 D = D->getCanonicalDecl();
5710 if (D->TypeForDecl)
5711 return D->TypeForDecl->getCanonicalTypeUnqualified();
5712
5713 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5714 Keyword: ElaboratedTypeKeyword::None,
5715 /*Qualifier=*/std::nullopt, D,
5716 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5717 D->TypeForDecl = CanonicalType;
5718 return CanQualType::CreateUnsafe(Other: QualType(CanonicalType, 0));
5719}
5720
5721QualType
5722ASTContext::getUnresolvedUsingType(ElaboratedTypeKeyword Keyword,
5723 NestedNameSpecifier Qualifier,
5724 const UnresolvedUsingTypenameDecl *D) const {
5725 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5726 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5727 return QualType(T, 0);
5728
5729 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5730 const Type *T =
5731 getUnresolvedUsingTypeInternal(Keyword: ElaboratedTypeKeyword::None,
5732 /*Qualifier=*/std::nullopt, D,
5733 /*InsertPos=*/nullptr, CanonicalType);
5734 D->TypeForDecl = T;
5735 return QualType(T, 0);
5736 }
5737
5738 llvm::FoldingSetNodeID ID;
5739 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5740
5741 void *InsertPos = nullptr;
5742 if (FoldingSetPlaceholder<UnresolvedUsingType> *Placeholder =
5743 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5744 return QualType(Placeholder->getType(), 0);
5745 assert(InsertPos);
5746
5747 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5748 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5749 InsertPos, CanonicalType);
5750 return QualType(T, 0);
5751}
5752
5753QualType ASTContext::getAttributedType(attr::Kind attrKind,
5754 QualType modifiedType,
5755 QualType equivalentType,
5756 const Attr *attr) const {
5757 llvm::FoldingSetNodeID id;
5758 AttributedType::Profile(ID&: id, Ctx: *this, attrKind, modified: modifiedType, equivalent: equivalentType,
5759 attr);
5760
5761 void *insertPos = nullptr;
5762 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(ID: id, InsertPos&: insertPos);
5763 if (type) return QualType(type, 0);
5764
5765 assert(!attr || attr->getKind() == attrKind);
5766
5767 QualType canon = getCanonicalType(T: equivalentType);
5768 type = new (*this, alignof(AttributedType))
5769 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5770
5771 Types.push_back(Elt: type);
5772 AttributedTypes.InsertNode(N: type, InsertPos: insertPos);
5773
5774 return QualType(type, 0);
5775}
5776
5777QualType ASTContext::getAttributedType(const Attr *attr, QualType modifiedType,
5778 QualType equivalentType) const {
5779 return getAttributedType(attrKind: attr->getKind(), modifiedType, equivalentType, attr);
5780}
5781
5782QualType ASTContext::getAttributedType(NullabilityKind nullability,
5783 QualType modifiedType,
5784 QualType equivalentType) {
5785 switch (nullability) {
5786 case NullabilityKind::NonNull:
5787 return getAttributedType(attrKind: attr::TypeNonNull, modifiedType, equivalentType);
5788
5789 case NullabilityKind::Nullable:
5790 return getAttributedType(attrKind: attr::TypeNullable, modifiedType, equivalentType);
5791
5792 case NullabilityKind::NullableResult:
5793 return getAttributedType(attrKind: attr::TypeNullableResult, modifiedType,
5794 equivalentType);
5795
5796 case NullabilityKind::Unspecified:
5797 return getAttributedType(attrKind: attr::TypeNullUnspecified, modifiedType,
5798 equivalentType);
5799 }
5800
5801 llvm_unreachable("Unknown nullability kind");
5802}
5803
5804QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5805 QualType Wrapped) const {
5806 llvm::FoldingSetNodeID ID;
5807 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5808
5809 void *InsertPos = nullptr;
5810 BTFTagAttributedType *Ty =
5811 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5812 if (Ty)
5813 return QualType(Ty, 0);
5814
5815 QualType Canon = getCanonicalType(T: Wrapped);
5816 Ty = new (*this, alignof(BTFTagAttributedType))
5817 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5818
5819 Types.push_back(Elt: Ty);
5820 BTFTagAttributedTypes.InsertNode(N: Ty, InsertPos);
5821
5822 return QualType(Ty, 0);
5823}
5824
5825QualType ASTContext::getOverflowBehaviorType(const OverflowBehaviorAttr *Attr,
5826 QualType Underlying) const {
5827 const IdentifierInfo *II = Attr->getBehaviorKind();
5828 StringRef IdentName = II->getName();
5829 OverflowBehaviorType::OverflowBehaviorKind Kind;
5830 if (IdentName == "wrap") {
5831 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5832 } else if (IdentName == "trap") {
5833 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5834 } else {
5835 return Underlying;
5836 }
5837
5838 return getOverflowBehaviorType(Kind, Wrapped: Underlying);
5839}
5840
5841QualType ASTContext::getOverflowBehaviorType(
5842 OverflowBehaviorType::OverflowBehaviorKind Kind,
5843 QualType Underlying) const {
5844 assert(!Underlying->isOverflowBehaviorType() &&
5845 "Cannot have underlying types that are themselves OBTs");
5846 llvm::FoldingSetNodeID ID;
5847 OverflowBehaviorType::Profile(ID, Underlying, Kind);
5848 void *InsertPos = nullptr;
5849
5850 if (OverflowBehaviorType *OBT =
5851 OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5852 return QualType(OBT, 0);
5853 }
5854
5855 QualType Canonical;
5856 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5857 SplitQualType canonSplit = getCanonicalType(T: Underlying).split();
5858 Canonical = getOverflowBehaviorType(Kind, Underlying: QualType(canonSplit.Ty, 0));
5859 Canonical = getQualifiedType(T: Canonical, Qs: canonSplit.Quals);
5860 assert(!OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos) &&
5861 "Shouldn't be in the map");
5862 }
5863
5864 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5865 OverflowBehaviorType(Canonical, Underlying, Kind);
5866
5867 Types.push_back(Elt: Ty);
5868 OverflowBehaviorTypes.InsertNode(N: Ty, InsertPos);
5869 return QualType(Ty, 0);
5870}
5871
5872QualType ASTContext::getHLSLAttributedResourceType(
5873 QualType Wrapped, QualType Contained,
5874 const HLSLAttributedResourceType::Attributes &Attrs) {
5875
5876 llvm::FoldingSetNodeID ID;
5877 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5878
5879 void *InsertPos = nullptr;
5880 HLSLAttributedResourceType *Ty =
5881 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5882 if (Ty)
5883 return QualType(Ty, 0);
5884
5885 Ty = new (*this, alignof(HLSLAttributedResourceType))
5886 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5887
5888 Types.push_back(Elt: Ty);
5889 HLSLAttributedResourceTypes.InsertNode(N: Ty, InsertPos);
5890
5891 return QualType(Ty, 0);
5892}
5893
5894QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5895 uint32_t Alignment,
5896 ArrayRef<SpirvOperand> Operands) {
5897 llvm::FoldingSetNodeID ID;
5898 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5899
5900 void *InsertPos = nullptr;
5901 HLSLInlineSpirvType *Ty =
5902 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5903 if (Ty)
5904 return QualType(Ty, 0);
5905
5906 void *Mem = Allocate(
5907 Size: HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Counts: Operands.size()),
5908 Align: alignof(HLSLInlineSpirvType));
5909
5910 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5911
5912 Types.push_back(Elt: Ty);
5913 HLSLInlineSpirvTypes.InsertNode(N: Ty, InsertPos);
5914
5915 return QualType(Ty, 0);
5916}
5917
5918/// Retrieve a substitution-result type.
5919QualType ASTContext::getSubstTemplateTypeParmType(QualType Replacement,
5920 Decl *AssociatedDecl,
5921 unsigned Index,
5922 UnsignedOrNone PackIndex,
5923 bool Final) const {
5924 llvm::FoldingSetNodeID ID;
5925 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5926 PackIndex, Final);
5927 void *InsertPos = nullptr;
5928 SubstTemplateTypeParmType *SubstParm =
5929 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5930
5931 if (!SubstParm) {
5932 void *Mem = Allocate(Size: SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5933 Counts: !Replacement.isCanonical()),
5934 Align: alignof(SubstTemplateTypeParmType));
5935 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5936 Index, PackIndex, Final);
5937 Types.push_back(Elt: SubstParm);
5938 SubstTemplateTypeParmTypes.InsertNode(N: SubstParm, InsertPos);
5939 }
5940
5941 return QualType(SubstParm, 0);
5942}
5943
5944QualType
5945ASTContext::getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
5946 unsigned Index, bool Final,
5947 const TemplateArgument &ArgPack) {
5948#ifndef NDEBUG
5949 for (const auto &P : ArgPack.pack_elements())
5950 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5951#endif
5952
5953 llvm::FoldingSetNodeID ID;
5954 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5955 ArgPack);
5956 void *InsertPos = nullptr;
5957 if (SubstTemplateTypeParmPackType *SubstParm =
5958 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5959 return QualType(SubstParm, 0);
5960
5961 QualType Canon;
5962 {
5963 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(Arg: ArgPack);
5964 if (!AssociatedDecl->isCanonicalDecl() ||
5965 !CanonArgPack.structurallyEquals(Other: ArgPack)) {
5966 Canon = getSubstTemplateTypeParmPackType(
5967 AssociatedDecl: AssociatedDecl->getCanonicalDecl(), Index, Final, ArgPack: CanonArgPack);
5968 [[maybe_unused]] const auto *Nothing =
5969 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5970 assert(!Nothing);
5971 }
5972 }
5973
5974 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5975 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5976 ArgPack);
5977 Types.push_back(Elt: SubstParm);
5978 SubstTemplateTypeParmPackTypes.InsertNode(N: SubstParm, InsertPos);
5979 return QualType(SubstParm, 0);
5980}
5981
5982QualType
5983ASTContext::getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack) {
5984 assert(llvm::all_of(ArgPack.pack_elements(),
5985 [](const auto &P) {
5986 return P.getKind() == TemplateArgument::Type;
5987 }) &&
5988 "Pack contains a non-type");
5989
5990 llvm::FoldingSetNodeID ID;
5991 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5992
5993 void *InsertPos = nullptr;
5994 if (auto *T =
5995 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
5996 return QualType(T, 0);
5997
5998 QualType Canon;
5999 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(Arg: ArgPack);
6000 if (!CanonArgPack.structurallyEquals(Other: ArgPack)) {
6001 Canon = getSubstBuiltinTemplatePack(ArgPack: CanonArgPack);
6002 // Refresh InsertPos, in case the recursive call above caused rehashing,
6003 // which would invalidate the bucket pointer.
6004 [[maybe_unused]] const auto *Nothing =
6005 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos);
6006 assert(!Nothing);
6007 }
6008
6009 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
6010 SubstBuiltinTemplatePackType(Canon, ArgPack);
6011 Types.push_back(Elt: PackType);
6012 SubstBuiltinTemplatePackTypes.InsertNode(N: PackType, InsertPos);
6013 return QualType(PackType, 0);
6014}
6015
6016/// Retrieve the template type parameter type for a template
6017/// parameter or parameter pack with the given depth, index, and (optionally)
6018/// name.
6019QualType
6020ASTContext::getTemplateTypeParmType(int Depth, int Index, bool ParameterPack,
6021 TemplateTypeParmDecl *TTPDecl) const {
6022 assert(Depth >= 0 && "Depth must be non-negative");
6023 assert(Index >= 0 && "Index must be non-negative");
6024
6025 llvm::FoldingSetNodeID ID;
6026 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
6027 void *InsertPos = nullptr;
6028 TemplateTypeParmType *TypeParm
6029 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
6030
6031 if (TypeParm)
6032 return QualType(TypeParm, 0);
6033
6034 if (TTPDecl) {
6035 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
6036 TypeParm = new (*this, alignof(TemplateTypeParmType))
6037 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
6038
6039 TemplateTypeParmType *TypeCheck
6040 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
6041 assert(!TypeCheck && "Template type parameter canonical type broken");
6042 (void)TypeCheck;
6043 } else
6044 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
6045 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
6046
6047 Types.push_back(Elt: TypeParm);
6048 TemplateTypeParmTypes.InsertNode(N: TypeParm, InsertPos);
6049
6050 return QualType(TypeParm, 0);
6051}
6052
6053static ElaboratedTypeKeyword
6054getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword) {
6055 switch (Keyword) {
6056 // These are just themselves.
6057 case ElaboratedTypeKeyword::None:
6058 case ElaboratedTypeKeyword::Struct:
6059 case ElaboratedTypeKeyword::Union:
6060 case ElaboratedTypeKeyword::Enum:
6061 case ElaboratedTypeKeyword::Interface:
6062 return Keyword;
6063
6064 // These are equivalent.
6065 case ElaboratedTypeKeyword::Typename:
6066 return ElaboratedTypeKeyword::None;
6067
6068 // These are functionally equivalent, so relying on their equivalence is
6069 // IFNDR. By making them equivalent, we disallow overloading, which at least
6070 // can produce a diagnostic.
6071 case ElaboratedTypeKeyword::Class:
6072 return ElaboratedTypeKeyword::Struct;
6073 }
6074 llvm_unreachable("unexpected keyword kind");
6075}
6076
6077TypeSourceInfo *ASTContext::getTemplateSpecializationTypeInfo(
6078 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6079 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6080 TemplateName Name, SourceLocation NameLoc,
6081 const TemplateArgumentListInfo &SpecifiedArgs,
6082 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6083 QualType TST = getTemplateSpecializationType(
6084 Keyword, T: Name, SpecifiedArgs: SpecifiedArgs.arguments(), CanonicalArgs, Canon: Underlying);
6085
6086 TypeSourceInfo *TSI = CreateTypeSourceInfo(T: TST);
6087 TSI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>().set(
6088 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6089 TAL: SpecifiedArgs);
6090 return TSI;
6091}
6092
6093QualType ASTContext::getTemplateSpecializationType(
6094 ElaboratedTypeKeyword Keyword, TemplateName Template,
6095 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6096 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6097 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6098 SpecifiedArgVec.reserve(N: SpecifiedArgs.size());
6099 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6100 SpecifiedArgVec.push_back(Elt: Arg.getArgument());
6101
6102 return getTemplateSpecializationType(Keyword, T: Template, SpecifiedArgs: SpecifiedArgVec,
6103 CanonicalArgs, Underlying);
6104}
6105
6106[[maybe_unused]] static bool
6107hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
6108 for (const TemplateArgument &Arg : Args)
6109 if (Arg.isPackExpansion())
6110 return true;
6111 return false;
6112}
6113
6114QualType ASTContext::getCanonicalTemplateSpecializationType(
6115 ElaboratedTypeKeyword Keyword, TemplateName Template,
6116 ArrayRef<TemplateArgument> Args) const {
6117 assert(Template ==
6118 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6119 assert((Keyword == ElaboratedTypeKeyword::None ||
6120 Template.getAsDependentTemplateName()));
6121#ifndef NDEBUG
6122 for (const auto &Arg : Args)
6123 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6124#endif
6125
6126 llvm::FoldingSetNodeID ID;
6127 TemplateSpecializationType::Profile(ID, Keyword, T: Template, Args, Underlying: QualType(),
6128 Context: *this);
6129 void *InsertPos = nullptr;
6130 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6131 return QualType(T, 0);
6132
6133 void *Mem = Allocate(Size: sizeof(TemplateSpecializationType) +
6134 sizeof(TemplateArgument) * Args.size(),
6135 Align: alignof(TemplateSpecializationType));
6136 auto *Spec =
6137 new (Mem) TemplateSpecializationType(Keyword, Template,
6138 /*IsAlias=*/false, Args, QualType());
6139 assert(Spec->isDependentType() &&
6140 "canonical template specialization must be dependent");
6141 Types.push_back(Elt: Spec);
6142 TemplateSpecializationTypes.InsertNode(N: Spec, InsertPos);
6143 return QualType(Spec, 0);
6144}
6145
6146QualType ASTContext::getTemplateSpecializationType(
6147 ElaboratedTypeKeyword Keyword, TemplateName Template,
6148 ArrayRef<TemplateArgument> SpecifiedArgs,
6149 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6150 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6151 bool IsTypeAlias = TD && TD->isTypeAlias();
6152 if (Underlying.isNull()) {
6153 TemplateName CanonTemplate =
6154 getCanonicalTemplateName(Name: Template, /*IgnoreDeduced=*/true);
6155 ElaboratedTypeKeyword CanonKeyword =
6156 CanonTemplate.getAsDependentTemplateName()
6157 ? getCanonicalElaboratedTypeKeyword(Keyword)
6158 : ElaboratedTypeKeyword::None;
6159 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6160 SmallVector<TemplateArgument, 4> CanonArgsVec;
6161 if (CanonicalArgs.empty()) {
6162 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6163 NonCanonical |= canonicalizeTemplateArguments(Args: CanonArgsVec);
6164 CanonicalArgs = CanonArgsVec;
6165 } else {
6166 NonCanonical |= !llvm::equal(
6167 LRange&: SpecifiedArgs, RRange&: CanonicalArgs,
6168 P: [](const TemplateArgument &A, const TemplateArgument &B) {
6169 return A.structurallyEquals(Other: B);
6170 });
6171 }
6172
6173 // We can get here with an alias template when the specialization
6174 // contains a pack expansion that does not match up with a parameter
6175 // pack, or a builtin template which cannot be resolved due to dependency.
6176 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6177 hasAnyPackExpansions(CanonicalArgs)) &&
6178 "Caller must compute aliased type");
6179 IsTypeAlias = false;
6180
6181 Underlying = getCanonicalTemplateSpecializationType(
6182 Keyword: CanonKeyword, Template: CanonTemplate, Args: CanonicalArgs);
6183 if (!NonCanonical)
6184 return Underlying;
6185 }
6186 void *Mem = Allocate(Size: sizeof(TemplateSpecializationType) +
6187 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6188 (IsTypeAlias ? sizeof(QualType) : 0),
6189 Align: alignof(TemplateSpecializationType));
6190 auto *Spec = new (Mem) TemplateSpecializationType(
6191 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6192 Types.push_back(Elt: Spec);
6193 return QualType(Spec, 0);
6194}
6195
6196QualType
6197ASTContext::getParenType(QualType InnerType) const {
6198 llvm::FoldingSetNodeID ID;
6199 ParenType::Profile(ID, Inner: InnerType);
6200
6201 void *InsertPos = nullptr;
6202 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6203 if (T)
6204 return QualType(T, 0);
6205
6206 QualType Canon = InnerType;
6207 if (!Canon.isCanonical()) {
6208 Canon = getCanonicalType(T: InnerType);
6209 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6210 assert(!CheckT && "Paren canonical type broken");
6211 (void)CheckT;
6212 }
6213
6214 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6215 Types.push_back(Elt: T);
6216 ParenTypes.InsertNode(N: T, InsertPos);
6217 return QualType(T, 0);
6218}
6219
6220QualType
6221ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
6222 const IdentifierInfo *MacroII) const {
6223 QualType Canon = UnderlyingTy;
6224 if (!Canon.isCanonical())
6225 Canon = getCanonicalType(T: UnderlyingTy);
6226
6227 auto *newType = new (*this, alignof(MacroQualifiedType))
6228 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6229 Types.push_back(Elt: newType);
6230 return QualType(newType, 0);
6231}
6232
6233QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
6234 NestedNameSpecifier NNS,
6235 const IdentifierInfo *Name) const {
6236 llvm::FoldingSetNodeID ID;
6237 DependentNameType::Profile(ID, Keyword, NNS, Name);
6238
6239 void *InsertPos = nullptr;
6240 if (DependentNameType *T =
6241 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6242 return QualType(T, 0);
6243
6244 ElaboratedTypeKeyword CanonKeyword =
6245 getCanonicalElaboratedTypeKeyword(Keyword);
6246 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6247
6248 QualType Canon;
6249 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6250 Canon = getDependentNameType(Keyword: CanonKeyword, NNS: CanonNNS, Name);
6251 [[maybe_unused]] DependentNameType *T =
6252 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6253 assert(!T && "broken canonicalization");
6254 assert(Canon.isCanonical());
6255 }
6256
6257 DependentNameType *T = new (*this, alignof(DependentNameType))
6258 DependentNameType(Keyword, NNS, Name, Canon);
6259 Types.push_back(Elt: T);
6260 DependentNameTypes.InsertNode(N: T, InsertPos);
6261 return QualType(T, 0);
6262}
6263
6264TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) const {
6265 TemplateArgument Arg;
6266 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
6267 QualType ArgType = getTypeDeclType(Decl: TTP);
6268 if (TTP->isParameterPack())
6269 ArgType = getPackExpansionType(Pattern: ArgType, NumExpansions: std::nullopt);
6270
6271 Arg = TemplateArgument(ArgType);
6272 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
6273 QualType T =
6274 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(Context: *this);
6275 // For class NTTPs, ensure we include the 'const' so the type matches that
6276 // of a real template argument.
6277 // FIXME: It would be more faithful to model this as something like an
6278 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6279 ExprValueKind VK;
6280 if (T->isRecordType()) {
6281 // C++ [temp.param]p8: An id-expression naming a non-type
6282 // template-parameter of class type T denotes a static storage duration
6283 // object of type const T.
6284 T.addConst();
6285 VK = VK_LValue;
6286 } else {
6287 VK = Expr::getValueKindForType(T: NTTP->getType());
6288 }
6289 Expr *E = new (*this)
6290 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6291 T, VK, NTTP->getLocation());
6292
6293 if (NTTP->isParameterPack())
6294 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6295 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6296 } else {
6297 auto *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
6298 TemplateName Name = getQualifiedTemplateName(
6299 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6300 Template: TemplateName(TTP));
6301 if (TTP->isParameterPack())
6302 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6303 else
6304 Arg = TemplateArgument(Name);
6305 }
6306
6307 if (Param->isTemplateParameterPack())
6308 Arg =
6309 TemplateArgument::CreatePackCopy(Context&: const_cast<ASTContext &>(*this), Args: Arg);
6310
6311 return Arg;
6312}
6313
6314QualType ASTContext::getPackExpansionType(QualType Pattern,
6315 UnsignedOrNone NumExpansions,
6316 bool ExpectPackInType) const {
6317 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6318 "Pack expansions must expand one or more parameter packs");
6319
6320 llvm::FoldingSetNodeID ID;
6321 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6322
6323 void *InsertPos = nullptr;
6324 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6325 if (T)
6326 return QualType(T, 0);
6327
6328 QualType Canon;
6329 if (!Pattern.isCanonical()) {
6330 Canon = getPackExpansionType(Pattern: getCanonicalType(T: Pattern), NumExpansions,
6331 /*ExpectPackInType=*/false);
6332
6333 // Find the insert position again, in case we inserted an element into
6334 // PackExpansionTypes and invalidated our insert position.
6335 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6336 }
6337
6338 T = new (*this, alignof(PackExpansionType))
6339 PackExpansionType(Pattern, Canon, NumExpansions);
6340 Types.push_back(Elt: T);
6341 PackExpansionTypes.InsertNode(N: T, InsertPos);
6342 return QualType(T, 0);
6343}
6344
6345/// CmpProtocolNames - Comparison predicate for sorting protocols
6346/// alphabetically.
6347static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6348 ObjCProtocolDecl *const *RHS) {
6349 return DeclarationName::compare(LHS: (*LHS)->getDeclName(), RHS: (*RHS)->getDeclName());
6350}
6351
6352static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
6353 if (Protocols.empty()) return true;
6354
6355 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6356 return false;
6357
6358 for (unsigned i = 1; i != Protocols.size(); ++i)
6359 if (CmpProtocolNames(LHS: &Protocols[i - 1], RHS: &Protocols[i]) >= 0 ||
6360 Protocols[i]->getCanonicalDecl() != Protocols[i])
6361 return false;
6362 return true;
6363}
6364
6365static void
6366SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
6367 // Sort protocols, keyed by name.
6368 llvm::array_pod_sort(Start: Protocols.begin(), End: Protocols.end(), Compare: CmpProtocolNames);
6369
6370 // Canonicalize.
6371 for (ObjCProtocolDecl *&P : Protocols)
6372 P = P->getCanonicalDecl();
6373
6374 // Remove duplicates.
6375 auto ProtocolsEnd = llvm::unique(R&: Protocols);
6376 Protocols.erase(CS: ProtocolsEnd, CE: Protocols.end());
6377}
6378
6379QualType ASTContext::getObjCObjectType(QualType BaseType,
6380 ObjCProtocolDecl * const *Protocols,
6381 unsigned NumProtocols) const {
6382 return getObjCObjectType(Base: BaseType, typeArgs: {}, protocols: ArrayRef(Protocols, NumProtocols),
6383 /*isKindOf=*/false);
6384}
6385
6386QualType ASTContext::getObjCObjectType(
6387 QualType baseType,
6388 ArrayRef<QualType> typeArgs,
6389 ArrayRef<ObjCProtocolDecl *> protocols,
6390 bool isKindOf) const {
6391 // If the base type is an interface and there aren't any protocols or
6392 // type arguments to add, then the interface type will do just fine.
6393 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6394 isa<ObjCInterfaceType>(Val: baseType))
6395 return baseType;
6396
6397 // Look in the folding set for an existing type.
6398 llvm::FoldingSetNodeID ID;
6399 ObjCObjectTypeImpl::Profile(ID, Base: baseType, typeArgs, protocols, isKindOf);
6400 void *InsertPos = nullptr;
6401 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6402 return QualType(QT, 0);
6403
6404 // Determine the type arguments to be used for canonicalization,
6405 // which may be explicitly specified here or written on the base
6406 // type.
6407 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6408 if (effectiveTypeArgs.empty()) {
6409 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6410 effectiveTypeArgs = baseObject->getTypeArgs();
6411 }
6412
6413 // Build the canonical type, which has the canonical base type and a
6414 // sorted-and-uniqued list of protocols and the type arguments
6415 // canonicalized.
6416 QualType canonical;
6417 bool typeArgsAreCanonical = llvm::all_of(
6418 Range&: effectiveTypeArgs, P: [&](QualType type) { return type.isCanonical(); });
6419 bool protocolsSorted = areSortedAndUniqued(Protocols: protocols);
6420 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6421 // Determine the canonical type arguments.
6422 ArrayRef<QualType> canonTypeArgs;
6423 SmallVector<QualType, 4> canonTypeArgsVec;
6424 if (!typeArgsAreCanonical) {
6425 canonTypeArgsVec.reserve(N: effectiveTypeArgs.size());
6426 for (auto typeArg : effectiveTypeArgs)
6427 canonTypeArgsVec.push_back(Elt: getCanonicalType(T: typeArg));
6428 canonTypeArgs = canonTypeArgsVec;
6429 } else {
6430 canonTypeArgs = effectiveTypeArgs;
6431 }
6432
6433 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6434 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6435 if (!protocolsSorted) {
6436 canonProtocolsVec.append(in_start: protocols.begin(), in_end: protocols.end());
6437 SortAndUniqueProtocols(Protocols&: canonProtocolsVec);
6438 canonProtocols = canonProtocolsVec;
6439 } else {
6440 canonProtocols = protocols;
6441 }
6442
6443 canonical = getObjCObjectType(baseType: getCanonicalType(T: baseType), typeArgs: canonTypeArgs,
6444 protocols: canonProtocols, isKindOf);
6445
6446 // Regenerate InsertPos.
6447 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6448 }
6449
6450 unsigned size = sizeof(ObjCObjectTypeImpl);
6451 size += typeArgs.size() * sizeof(QualType);
6452 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6453 void *mem = Allocate(Size: size, Align: alignof(ObjCObjectTypeImpl));
6454 auto *T =
6455 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6456 isKindOf);
6457
6458 Types.push_back(Elt: T);
6459 ObjCObjectTypes.InsertNode(N: T, InsertPos);
6460 return QualType(T, 0);
6461}
6462
6463/// Apply Objective-C protocol qualifiers to the given type.
6464/// If this is for the canonical type of a type parameter, we can apply
6465/// protocol qualifiers on the ObjCObjectPointerType.
6466QualType
6467ASTContext::applyObjCProtocolQualifiers(QualType type,
6468 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6469 bool allowOnPointerType) const {
6470 hasError = false;
6471
6472 if (const auto *objT = dyn_cast<ObjCTypeParamType>(Val: type.getTypePtr())) {
6473 return getObjCTypeParamType(Decl: objT->getDecl(), protocols);
6474 }
6475
6476 // Apply protocol qualifiers to ObjCObjectPointerType.
6477 if (allowOnPointerType) {
6478 if (const auto *objPtr =
6479 dyn_cast<ObjCObjectPointerType>(Val: type.getTypePtr())) {
6480 const ObjCObjectType *objT = objPtr->getObjectType();
6481 // Merge protocol lists and construct ObjCObjectType.
6482 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
6483 protocolsVec.append(in_start: objT->qual_begin(),
6484 in_end: objT->qual_end());
6485 protocolsVec.append(in_start: protocols.begin(), in_end: protocols.end());
6486 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6487 type = getObjCObjectType(
6488 baseType: objT->getBaseType(),
6489 typeArgs: objT->getTypeArgsAsWritten(),
6490 protocols,
6491 isKindOf: objT->isKindOfTypeAsWritten());
6492 return getObjCObjectPointerType(OIT: type);
6493 }
6494 }
6495
6496 // Apply protocol qualifiers to ObjCObjectType.
6497 if (const auto *objT = dyn_cast<ObjCObjectType>(Val: type.getTypePtr())){
6498 // FIXME: Check for protocols to which the class type is already
6499 // known to conform.
6500
6501 return getObjCObjectType(baseType: objT->getBaseType(),
6502 typeArgs: objT->getTypeArgsAsWritten(),
6503 protocols,
6504 isKindOf: objT->isKindOfTypeAsWritten());
6505 }
6506
6507 // If the canonical type is ObjCObjectType, ...
6508 if (type->isObjCObjectType()) {
6509 // Silently overwrite any existing protocol qualifiers.
6510 // TODO: determine whether that's the right thing to do.
6511
6512 // FIXME: Check for protocols to which the class type is already
6513 // known to conform.
6514 return getObjCObjectType(baseType: type, typeArgs: {}, protocols, isKindOf: false);
6515 }
6516
6517 // id<protocol-list>
6518 if (type->isObjCIdType()) {
6519 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6520 type = getObjCObjectType(baseType: ObjCBuiltinIdTy, typeArgs: {}, protocols,
6521 isKindOf: objPtr->isKindOfType());
6522 return getObjCObjectPointerType(OIT: type);
6523 }
6524
6525 // Class<protocol-list>
6526 if (type->isObjCClassType()) {
6527 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6528 type = getObjCObjectType(baseType: ObjCBuiltinClassTy, typeArgs: {}, protocols,
6529 isKindOf: objPtr->isKindOfType());
6530 return getObjCObjectPointerType(OIT: type);
6531 }
6532
6533 hasError = true;
6534 return type;
6535}
6536
6537QualType
6538ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
6539 ArrayRef<ObjCProtocolDecl *> protocols) const {
6540 // Look in the folding set for an existing type.
6541 llvm::FoldingSetNodeID ID;
6542 ObjCTypeParamType::Profile(ID, OTPDecl: Decl, CanonicalType: Decl->getUnderlyingType(), protocols);
6543 void *InsertPos = nullptr;
6544 if (ObjCTypeParamType *TypeParam =
6545 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6546 return QualType(TypeParam, 0);
6547
6548 // We canonicalize to the underlying type.
6549 QualType Canonical = getCanonicalType(T: Decl->getUnderlyingType());
6550 if (!protocols.empty()) {
6551 // Apply the protocol qualifers.
6552 bool hasError;
6553 Canonical = getCanonicalType(T: applyObjCProtocolQualifiers(
6554 type: Canonical, protocols, hasError, allowOnPointerType: true /*allowOnPointerType*/));
6555 assert(!hasError && "Error when apply protocol qualifier to bound type");
6556 }
6557
6558 unsigned size = sizeof(ObjCTypeParamType);
6559 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6560 void *mem = Allocate(Size: size, Align: alignof(ObjCTypeParamType));
6561 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6562
6563 Types.push_back(Elt: newType);
6564 ObjCTypeParamTypes.InsertNode(N: newType, InsertPos);
6565 return QualType(newType, 0);
6566}
6567
6568void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
6569 ObjCTypeParamDecl *New) const {
6570 New->setTypeSourceInfo(getTrivialTypeSourceInfo(T: Orig->getUnderlyingType()));
6571 // Update TypeForDecl after updating TypeSourceInfo.
6572 auto *NewTypeParamTy = cast<ObjCTypeParamType>(Val: New->TypeForDecl);
6573 SmallVector<ObjCProtocolDecl *, 8> protocols;
6574 protocols.append(in_start: NewTypeParamTy->qual_begin(), in_end: NewTypeParamTy->qual_end());
6575 QualType UpdatedTy = getObjCTypeParamType(Decl: New, protocols);
6576 New->TypeForDecl = UpdatedTy.getTypePtr();
6577}
6578
6579/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6580/// protocol list adopt all protocols in QT's qualified-id protocol
6581/// list.
6582bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
6583 ObjCInterfaceDecl *IC) {
6584 if (!QT->isObjCQualifiedIdType())
6585 return false;
6586
6587 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6588 // If both the right and left sides have qualifiers.
6589 for (auto *Proto : OPT->quals()) {
6590 if (!IC->ClassImplementsProtocol(lProto: Proto, lookupCategory: false))
6591 return false;
6592 }
6593 return true;
6594 }
6595 return false;
6596}
6597
6598/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6599/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6600/// of protocols.
6601bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
6602 ObjCInterfaceDecl *IDecl) {
6603 if (!QT->isObjCQualifiedIdType())
6604 return false;
6605 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6606 if (!OPT)
6607 return false;
6608 if (!IDecl->hasDefinition())
6609 return false;
6610 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
6611 CollectInheritedProtocols(CDecl: IDecl, Protocols&: InheritedProtocols);
6612 if (InheritedProtocols.empty())
6613 return false;
6614 // Check that if every protocol in list of id<plist> conforms to a protocol
6615 // of IDecl's, then bridge casting is ok.
6616 bool Conforms = false;
6617 for (auto *Proto : OPT->quals()) {
6618 Conforms = false;
6619 for (auto *PI : InheritedProtocols) {
6620 if (ProtocolCompatibleWithProtocol(lProto: Proto, rProto: PI)) {
6621 Conforms = true;
6622 break;
6623 }
6624 }
6625 if (!Conforms)
6626 break;
6627 }
6628 if (Conforms)
6629 return true;
6630
6631 for (auto *PI : InheritedProtocols) {
6632 // If both the right and left sides have qualifiers.
6633 bool Adopts = false;
6634 for (auto *Proto : OPT->quals()) {
6635 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6636 if ((Adopts = ProtocolCompatibleWithProtocol(lProto: PI, rProto: Proto)))
6637 break;
6638 }
6639 if (!Adopts)
6640 return false;
6641 }
6642 return true;
6643}
6644
6645/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6646/// the given object type.
6647QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
6648 llvm::FoldingSetNodeID ID;
6649 ObjCObjectPointerType::Profile(ID, T: ObjectT);
6650
6651 void *InsertPos = nullptr;
6652 if (ObjCObjectPointerType *QT =
6653 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6654 return QualType(QT, 0);
6655
6656 // Find the canonical object type.
6657 QualType Canonical;
6658 if (!ObjectT.isCanonical()) {
6659 Canonical = getObjCObjectPointerType(ObjectT: getCanonicalType(T: ObjectT));
6660
6661 // Regenerate InsertPos.
6662 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6663 }
6664
6665 // No match.
6666 void *Mem =
6667 Allocate(Size: sizeof(ObjCObjectPointerType), Align: alignof(ObjCObjectPointerType));
6668 auto *QType =
6669 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6670
6671 Types.push_back(Elt: QType);
6672 ObjCObjectPointerTypes.InsertNode(N: QType, InsertPos);
6673 return QualType(QType, 0);
6674}
6675
6676/// getObjCInterfaceType - Return the unique reference to the type for the
6677/// specified ObjC interface decl. The list of protocols is optional.
6678QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
6679 ObjCInterfaceDecl *PrevDecl) const {
6680 if (Decl->TypeForDecl)
6681 return QualType(Decl->TypeForDecl, 0);
6682
6683 if (PrevDecl) {
6684 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6685 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6686 return QualType(PrevDecl->TypeForDecl, 0);
6687 }
6688
6689 // Prefer the definition, if there is one.
6690 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6691 Decl = Def;
6692
6693 void *Mem = Allocate(Size: sizeof(ObjCInterfaceType), Align: alignof(ObjCInterfaceType));
6694 auto *T = new (Mem) ObjCInterfaceType(Decl);
6695 Decl->TypeForDecl = T;
6696 Types.push_back(Elt: T);
6697 return QualType(T, 0);
6698}
6699
6700/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6701/// TypeOfExprType AST's (since expression's are never shared). For example,
6702/// multiple declarations that refer to "typeof(x)" all contain different
6703/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6704/// on canonical type's (which are always unique).
6705QualType ASTContext::getTypeOfExprType(Expr *tofExpr, TypeOfKind Kind) const {
6706 TypeOfExprType *toe;
6707 if (tofExpr->isTypeDependent()) {
6708 llvm::FoldingSetNodeID ID;
6709 DependentTypeOfExprType::Profile(ID, Context: *this, E: tofExpr,
6710 IsUnqual: Kind == TypeOfKind::Unqualified);
6711
6712 void *InsertPos = nullptr;
6713 DependentTypeOfExprType *Canon =
6714 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6715 if (Canon) {
6716 // We already have a "canonical" version of an identical, dependent
6717 // typeof(expr) type. Use that as our canonical type.
6718 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6719 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6720 } else {
6721 // Build a new, canonical typeof(expr) type.
6722 Canon = new (*this, alignof(DependentTypeOfExprType))
6723 DependentTypeOfExprType(*this, tofExpr, Kind);
6724 DependentTypeOfExprTypes.InsertNode(N: Canon, InsertPos);
6725 toe = Canon;
6726 }
6727 } else {
6728 QualType Canonical = getCanonicalType(T: tofExpr->getType());
6729 toe = new (*this, alignof(TypeOfExprType))
6730 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6731 }
6732 Types.push_back(Elt: toe);
6733 return QualType(toe, 0);
6734}
6735
6736/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6737/// TypeOfType nodes. The only motivation to unique these nodes would be
6738/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6739/// an issue. This doesn't affect the type checker, since it operates
6740/// on canonical types (which are always unique).
6741QualType ASTContext::getTypeOfType(QualType tofType, TypeOfKind Kind) const {
6742 QualType Canonical = getCanonicalType(T: tofType);
6743 auto *tot = new (*this, alignof(TypeOfType))
6744 TypeOfType(*this, tofType, Canonical, Kind);
6745 Types.push_back(Elt: tot);
6746 return QualType(tot, 0);
6747}
6748
6749/// getReferenceQualifiedType - Given an expr, will return the type for
6750/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6751/// and class member access into account.
6752QualType ASTContext::getReferenceQualifiedType(const Expr *E) const {
6753 // C++11 [dcl.type.simple]p4:
6754 // [...]
6755 QualType T = E->getType();
6756 switch (E->getValueKind()) {
6757 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6758 // type of e;
6759 case VK_XValue:
6760 return getRValueReferenceType(T);
6761 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6762 // type of e;
6763 case VK_LValue:
6764 return getLValueReferenceType(T);
6765 // - otherwise, decltype(e) is the type of e.
6766 case VK_PRValue:
6767 return T;
6768 }
6769 llvm_unreachable("Unknown value kind");
6770}
6771
6772/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6773/// nodes. This would never be helpful, since each such type has its own
6774/// expression, and would not give a significant memory saving, since there
6775/// is an Expr tree under each such type.
6776QualType ASTContext::getDecltypeType(Expr *E, QualType UnderlyingType) const {
6777 // C++11 [temp.type]p2:
6778 // If an expression e involves a template parameter, decltype(e) denotes a
6779 // unique dependent type. Two such decltype-specifiers refer to the same
6780 // type only if their expressions are equivalent (14.5.6.1).
6781 QualType CanonType;
6782 if (!E->isInstantiationDependent()) {
6783 CanonType = getCanonicalType(T: UnderlyingType);
6784 } else if (!UnderlyingType.isNull()) {
6785 CanonType = getDecltypeType(E, UnderlyingType: QualType());
6786 } else {
6787 llvm::FoldingSetNodeID ID;
6788 DependentDecltypeType::Profile(ID, Context: *this, E);
6789
6790 void *InsertPos = nullptr;
6791 if (DependentDecltypeType *Canon =
6792 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6793 return QualType(Canon, 0);
6794
6795 // Build a new, canonical decltype(expr) type.
6796 auto *DT =
6797 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6798 DependentDecltypeTypes.InsertNode(N: DT, InsertPos);
6799 Types.push_back(Elt: DT);
6800 return QualType(DT, 0);
6801 }
6802 auto *DT = new (*this, alignof(DecltypeType))
6803 DecltypeType(E, UnderlyingType, CanonType);
6804 Types.push_back(Elt: DT);
6805 return QualType(DT, 0);
6806}
6807
6808QualType ASTContext::getPackIndexingType(QualType Pattern, Expr *IndexExpr,
6809 bool FullySubstituted,
6810 ArrayRef<QualType> Expansions,
6811 UnsignedOrNone Index) const {
6812 QualType Canonical;
6813 if (FullySubstituted && Index) {
6814 Canonical = getCanonicalType(T: Expansions[*Index]);
6815 } else {
6816 llvm::FoldingSetNodeID ID;
6817 PackIndexingType::Profile(ID, Context: *this, Pattern: Pattern.getCanonicalType(), E: IndexExpr,
6818 FullySubstituted, Expansions);
6819 void *InsertPos = nullptr;
6820 PackIndexingType *Canon =
6821 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6822 if (!Canon) {
6823 void *Mem = Allocate(
6824 Size: PackIndexingType::totalSizeToAlloc<QualType>(Counts: Expansions.size()),
6825 Align: TypeAlignment);
6826 Canon =
6827 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6828 IndexExpr, FullySubstituted, Expansions);
6829 DependentPackIndexingTypes.InsertNode(N: Canon, InsertPos);
6830 }
6831 Canonical = QualType(Canon, 0);
6832 }
6833
6834 void *Mem =
6835 Allocate(Size: PackIndexingType::totalSizeToAlloc<QualType>(Counts: Expansions.size()),
6836 Align: TypeAlignment);
6837 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6838 FullySubstituted, Expansions);
6839 Types.push_back(Elt: T);
6840 return QualType(T, 0);
6841}
6842
6843/// getUnaryTransformationType - We don't unique these, since the memory
6844/// savings are minimal and these are rare.
6845QualType
6846ASTContext::getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
6847 UnaryTransformType::UTTKind Kind) const {
6848
6849 llvm::FoldingSetNodeID ID;
6850 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, UKind: Kind);
6851
6852 void *InsertPos = nullptr;
6853 if (UnaryTransformType *UT =
6854 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6855 return QualType(UT, 0);
6856
6857 QualType CanonType;
6858 if (!BaseType->isDependentType()) {
6859 CanonType = UnderlyingType.getCanonicalType();
6860 } else {
6861 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6862 UnderlyingType = QualType();
6863 if (QualType CanonBase = BaseType.getCanonicalType();
6864 BaseType != CanonBase) {
6865 CanonType = getUnaryTransformType(BaseType: CanonBase, UnderlyingType: QualType(), Kind);
6866 assert(CanonType.isCanonical());
6867
6868 // Find the insertion position again.
6869 [[maybe_unused]] UnaryTransformType *UT =
6870 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6871 assert(!UT && "broken canonicalization");
6872 }
6873 }
6874
6875 auto *UT = new (*this, alignof(UnaryTransformType))
6876 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6877 UnaryTransformTypes.InsertNode(N: UT, InsertPos);
6878 Types.push_back(Elt: UT);
6879 return QualType(UT, 0);
6880}
6881
6882/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6883/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6884/// canonical deduced-but-dependent 'auto' type.
6885QualType
6886ASTContext::getAutoType(DeducedKind DK, QualType DeducedAsType,
6887 AutoTypeKeyword Keyword,
6888 TemplateDecl *TypeConstraintConcept,
6889 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6890 if (DK == DeducedKind::Undeduced && Keyword == AutoTypeKeyword::Auto &&
6891 !TypeConstraintConcept) {
6892 assert(DeducedAsType.isNull() && "");
6893 assert(TypeConstraintArgs.empty() && "");
6894 return getAutoDeductType();
6895 }
6896
6897 // Look in the folding set for an existing type.
6898 llvm::FoldingSetNodeID ID;
6899 AutoType::Profile(ID, Context: *this, DK, Deduced: DeducedAsType, Keyword,
6900 CD: TypeConstraintConcept, Arguments: TypeConstraintArgs);
6901 if (auto const AT_iter = AutoTypes.find(Val: ID); AT_iter != AutoTypes.end())
6902 return QualType(AT_iter->getSecond(), 0);
6903
6904 if (DK == DeducedKind::Deduced) {
6905 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6906 } else {
6907 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6908 if (TypeConstraintConcept) {
6909 bool AnyNonCanonArgs = false;
6910 auto *CanonicalConcept =
6911 cast<TemplateDecl>(Val: TypeConstraintConcept->getCanonicalDecl());
6912 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6913 C: *this, Args: TypeConstraintArgs, AnyNonCanonArgs);
6914 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6915 DeducedAsType = getAutoType(DK, DeducedAsType: QualType(), Keyword, TypeConstraintConcept: CanonicalConcept,
6916 TypeConstraintArgs: CanonicalConceptArgs);
6917 }
6918 }
6919
6920 void *Mem = Allocate(Size: sizeof(AutoType) +
6921 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6922 Align: alignof(AutoType));
6923 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6924 TypeConstraintConcept, TypeConstraintArgs);
6925#ifndef NDEBUG
6926 llvm::FoldingSetNodeID InsertedID;
6927 AT->Profile(InsertedID, *this);
6928 assert(InsertedID == ID && "ID does not match");
6929#endif
6930 Types.push_back(Elt: AT);
6931 AutoTypes.try_emplace(Key: ID, Args&: AT);
6932 return QualType(AT, 0);
6933}
6934
6935QualType ASTContext::getUnconstrainedType(QualType T) const {
6936 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6937
6938 // Remove a type-constraint from a top-level auto or decltype(auto).
6939 if (auto *AT = CanonT->getAs<AutoType>()) {
6940 if (!AT->isConstrained())
6941 return T;
6942 return getQualifiedType(
6943 T: getAutoType(DK: AT->getDeducedKind(), DeducedAsType: QualType(), Keyword: AT->getKeyword()),
6944 Qs: T.getQualifiers());
6945 }
6946
6947 // FIXME: We only support constrained auto at the top level in the type of a
6948 // non-type template parameter at the moment. Once we lift that restriction,
6949 // we'll need to recursively build types containing auto here.
6950 assert(!CanonT->getContainedAutoType() ||
6951 !CanonT->getContainedAutoType()->isConstrained());
6952 return T;
6953}
6954
6955/// Return the uniqued reference to the deduced template specialization type
6956/// which has been deduced to the given type, or to the canonical undeduced
6957/// such type, or the canonical deduced-but-dependent such type.
6958QualType ASTContext::getDeducedTemplateSpecializationType(
6959 DeducedKind DK, QualType DeducedAsType, ElaboratedTypeKeyword Keyword,
6960 TemplateName Template) const {
6961 // Look in the folding set for an existing type.
6962 void *InsertPos = nullptr;
6963 llvm::FoldingSetNodeID ID;
6964 DeducedTemplateSpecializationType::Profile(ID, DK, Deduced: DeducedAsType, Keyword,
6965 Template);
6966 if (DeducedTemplateSpecializationType *DTST =
6967 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6968 return QualType(DTST, 0);
6969
6970 if (DK == DeducedKind::Deduced) {
6971 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6972 } else {
6973 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6974 TemplateName CanonTemplateName = getCanonicalTemplateName(Name: Template);
6975 // FIXME: Can this be formed from a DependentTemplateName, such that the
6976 // keyword should be part of the canonical type?
6977 if (Keyword != ElaboratedTypeKeyword::None ||
6978 Template != CanonTemplateName) {
6979 DeducedAsType = getDeducedTemplateSpecializationType(
6980 DK, DeducedAsType: QualType(), Keyword: ElaboratedTypeKeyword::None, Template: CanonTemplateName);
6981 // Find the insertion position again.
6982 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
6983 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
6984 assert(!DTST && "broken canonicalization");
6985 }
6986 }
6987
6988 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6989 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
6990
6991#ifndef NDEBUG
6992 llvm::FoldingSetNodeID TempID;
6993 DTST->Profile(TempID);
6994 assert(ID == TempID && "ID does not match");
6995#endif
6996 Types.push_back(Elt: DTST);
6997 DeducedTemplateSpecializationTypes.InsertNode(N: DTST, InsertPos);
6998 return QualType(DTST, 0);
6999}
7000
7001/// getAtomicType - Return the uniqued reference to the atomic type for
7002/// the given value type.
7003QualType ASTContext::getAtomicType(QualType T) const {
7004 // Unique pointers, to guarantee there is only one pointer of a particular
7005 // structure.
7006 llvm::FoldingSetNodeID ID;
7007 AtomicType::Profile(ID, T);
7008
7009 void *InsertPos = nullptr;
7010 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
7011 return QualType(AT, 0);
7012
7013 // If the atomic value type isn't canonical, this won't be a canonical type
7014 // either, so fill in the canonical type field.
7015 QualType Canonical;
7016 if (!T.isCanonical()) {
7017 Canonical = getAtomicType(T: getCanonicalType(T));
7018
7019 // Get the new insert position for the node we care about.
7020 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
7021 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
7022 }
7023 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
7024 Types.push_back(Elt: New);
7025 AtomicTypes.InsertNode(N: New, InsertPos);
7026 return QualType(New, 0);
7027}
7028
7029/// getAutoDeductType - Get type pattern for deducing against 'auto'.
7030QualType ASTContext::getAutoDeductType() const {
7031 if (AutoDeductTy.isNull())
7032 AutoDeductTy = QualType(new (*this, alignof(AutoType))
7033 AutoType(DeducedKind::Undeduced, QualType(),
7034 AutoTypeKeyword::Auto,
7035 /*TypeConstraintConcept=*/nullptr,
7036 /*TypeConstraintArgs=*/{}),
7037 0);
7038 return AutoDeductTy;
7039}
7040
7041/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7042QualType ASTContext::getAutoRRefDeductType() const {
7043 if (AutoRRefDeductTy.isNull())
7044 AutoRRefDeductTy = getRValueReferenceType(T: getAutoDeductType());
7045 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7046 return AutoRRefDeductTy;
7047}
7048
7049/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7050/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7051/// needs to agree with the definition in <stddef.h>.
7052QualType ASTContext::getSizeType() const {
7053 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::SizeT);
7054}
7055
7056CanQualType ASTContext::getCanonicalSizeType() const {
7057 return getFromTargetType(Type: Target->getSizeType());
7058}
7059
7060/// Return the unique signed counterpart of the integer type
7061/// corresponding to size_t.
7062QualType ASTContext::getSignedSizeType() const {
7063 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::SignedSizeT);
7064}
7065
7066/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7067/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7068QualType ASTContext::getPointerDiffType() const {
7069 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::PtrdiffT);
7070}
7071
7072/// Return the unique unsigned counterpart of "ptrdiff_t"
7073/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7074/// in the definition of %tu format specifier.
7075QualType ASTContext::getUnsignedPointerDiffType() const {
7076 return getFromTargetType(Type: Target->getUnsignedPtrDiffType(AddrSpace: LangAS::Default));
7077}
7078
7079/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7080CanQualType ASTContext::getIntMaxType() const {
7081 return getFromTargetType(Type: Target->getIntMaxType());
7082}
7083
7084/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7085CanQualType ASTContext::getUIntMaxType() const {
7086 return getFromTargetType(Type: Target->getUIntMaxType());
7087}
7088
7089/// getSignedWCharType - Return the type of "signed wchar_t".
7090/// Used when in C++, as a GCC extension.
7091QualType ASTContext::getSignedWCharType() const {
7092 // FIXME: derive from "Target" ?
7093 return WCharTy;
7094}
7095
7096/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7097/// Used when in C++, as a GCC extension.
7098QualType ASTContext::getUnsignedWCharType() const {
7099 // FIXME: derive from "Target" ?
7100 return UnsignedIntTy;
7101}
7102
7103QualType ASTContext::getIntPtrType() const {
7104 return getFromTargetType(Type: Target->getIntPtrType());
7105}
7106
7107QualType ASTContext::getUIntPtrType() const {
7108 return getCorrespondingUnsignedType(T: getIntPtrType());
7109}
7110
7111/// Return the unique type for "pid_t" defined in
7112/// <sys/types.h>. We need this to compute the correct type for vfork().
7113QualType ASTContext::getProcessIDType() const {
7114 return getFromTargetType(Type: Target->getProcessIDType());
7115}
7116
7117//===----------------------------------------------------------------------===//
7118// Type Operators
7119//===----------------------------------------------------------------------===//
7120
7121CanQualType ASTContext::getCanonicalParamType(QualType T) const {
7122 // Push qualifiers into arrays, and then discard any remaining
7123 // qualifiers.
7124 T = getCanonicalType(T);
7125 T = getVariableArrayDecayedType(type: T);
7126 const Type *Ty = T.getTypePtr();
7127 QualType Result;
7128 if (getLangOpts().HLSL && isa<ConstantArrayType>(Val: Ty)) {
7129 Result = getArrayParameterType(Ty: QualType(Ty, 0));
7130 } else if (isa<ArrayType>(Val: Ty)) {
7131 Result = getArrayDecayedType(T: QualType(Ty,0));
7132 } else if (isa<FunctionType>(Val: Ty)) {
7133 Result = getPointerType(T: QualType(Ty, 0));
7134 } else {
7135 Result = QualType(Ty, 0);
7136 }
7137
7138 return CanQualType::CreateUnsafe(Other: Result);
7139}
7140
7141QualType ASTContext::getUnqualifiedArrayType(QualType type,
7142 Qualifiers &quals) const {
7143 SplitQualType splitType = type.getSplitUnqualifiedType();
7144
7145 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7146 // the unqualified desugared type and then drops it on the floor.
7147 // We then have to strip that sugar back off with
7148 // getUnqualifiedDesugaredType(), which is silly.
7149 const auto *AT =
7150 dyn_cast<ArrayType>(Val: splitType.Ty->getUnqualifiedDesugaredType());
7151
7152 // If we don't have an array, just use the results in splitType.
7153 if (!AT) {
7154 quals = splitType.Quals;
7155 return QualType(splitType.Ty, 0);
7156 }
7157
7158 // Otherwise, recurse on the array's element type.
7159 QualType elementType = AT->getElementType();
7160 QualType unqualElementType = getUnqualifiedArrayType(type: elementType, quals);
7161
7162 // If that didn't change the element type, AT has no qualifiers, so we
7163 // can just use the results in splitType.
7164 if (elementType == unqualElementType) {
7165 assert(quals.empty()); // from the recursive call
7166 quals = splitType.Quals;
7167 return QualType(splitType.Ty, 0);
7168 }
7169
7170 // Otherwise, add in the qualifiers from the outermost type, then
7171 // build the type back up.
7172 quals.addConsistentQualifiers(qs: splitType.Quals);
7173
7174 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT)) {
7175 return getConstantArrayType(EltTy: unqualElementType, ArySizeIn: CAT->getSize(),
7176 SizeExpr: CAT->getSizeExpr(), ASM: CAT->getSizeModifier(), IndexTypeQuals: 0);
7177 }
7178
7179 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT)) {
7180 return getIncompleteArrayType(elementType: unqualElementType, ASM: IAT->getSizeModifier(), elementTypeQuals: 0);
7181 }
7182
7183 if (const auto *VAT = dyn_cast<VariableArrayType>(Val: AT)) {
7184 return getVariableArrayType(EltTy: unqualElementType, NumElts: VAT->getSizeExpr(),
7185 ASM: VAT->getSizeModifier(),
7186 IndexTypeQuals: VAT->getIndexTypeCVRQualifiers());
7187 }
7188
7189 const auto *DSAT = cast<DependentSizedArrayType>(Val: AT);
7190 return getDependentSizedArrayType(elementType: unqualElementType, numElements: DSAT->getSizeExpr(),
7191 ASM: DSAT->getSizeModifier(), elementTypeQuals: 0);
7192}
7193
7194/// Attempt to unwrap two types that may both be array types with the same bound
7195/// (or both be array types of unknown bound) for the purpose of comparing the
7196/// cv-decomposition of two types per C++ [conv.qual].
7197///
7198/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7199/// C++20 [conv.qual], if permitted by the current language mode.
7200void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
7201 bool AllowPiMismatch) const {
7202 while (true) {
7203 auto *AT1 = getAsArrayType(T: T1);
7204 if (!AT1)
7205 return;
7206
7207 auto *AT2 = getAsArrayType(T: T2);
7208 if (!AT2)
7209 return;
7210
7211 // If we don't have two array types with the same constant bound nor two
7212 // incomplete array types, we've unwrapped everything we can.
7213 // C++20 also permits one type to be a constant array type and the other
7214 // to be an incomplete array type.
7215 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7216 if (auto *CAT1 = dyn_cast<ConstantArrayType>(Val: AT1)) {
7217 auto *CAT2 = dyn_cast<ConstantArrayType>(Val: AT2);
7218 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7219 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7220 isa<IncompleteArrayType>(Val: AT2))))
7221 return;
7222 } else if (isa<IncompleteArrayType>(Val: AT1)) {
7223 if (!(isa<IncompleteArrayType>(Val: AT2) ||
7224 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7225 isa<ConstantArrayType>(Val: AT2))))
7226 return;
7227 } else {
7228 return;
7229 }
7230
7231 T1 = AT1->getElementType();
7232 T2 = AT2->getElementType();
7233 }
7234}
7235
7236/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7237///
7238/// If T1 and T2 are both pointer types of the same kind, or both array types
7239/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7240/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7241///
7242/// This function will typically be called in a loop that successively
7243/// "unwraps" pointer and pointer-to-member types to compare them at each
7244/// level.
7245///
7246/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7247/// C++20 [conv.qual], if permitted by the current language mode.
7248///
7249/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7250/// pair of types that can't be unwrapped further.
7251bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2,
7252 bool AllowPiMismatch) const {
7253 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7254
7255 const auto *T1PtrType = T1->getAs<PointerType>();
7256 const auto *T2PtrType = T2->getAs<PointerType>();
7257 if (T1PtrType && T2PtrType) {
7258 T1 = T1PtrType->getPointeeType();
7259 T2 = T2PtrType->getPointeeType();
7260 return true;
7261 }
7262
7263 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7264 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7265 T1MPType && T2MPType) {
7266 // Compare the qualifiers of the canonical type, as the non-canonical type
7267 // may have qualifiers pointing to a base or derived class.
7268 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7269 return false;
7270 // Get the pointee types of the non-canonical type, in order to preserve
7271 // their sugar.
7272 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7273 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7274 return true;
7275 }
7276
7277 if (getLangOpts().ObjC) {
7278 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7279 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7280 if (T1OPType && T2OPType) {
7281 T1 = T1OPType->getPointeeType();
7282 T2 = T2OPType->getPointeeType();
7283 return true;
7284 }
7285 }
7286
7287 // FIXME: Block pointers, too?
7288
7289 return false;
7290}
7291
7292bool ASTContext::hasSimilarType(QualType T1, QualType T2) const {
7293 while (true) {
7294 Qualifiers Quals;
7295 T1 = getUnqualifiedArrayType(type: T1, quals&: Quals);
7296 T2 = getUnqualifiedArrayType(type: T2, quals&: Quals);
7297 if (hasSameType(T1, T2))
7298 return true;
7299 if (!UnwrapSimilarTypes(T1, T2))
7300 return false;
7301 }
7302}
7303
7304bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
7305 while (true) {
7306 Qualifiers Quals1, Quals2;
7307 T1 = getUnqualifiedArrayType(type: T1, quals&: Quals1);
7308 T2 = getUnqualifiedArrayType(type: T2, quals&: Quals2);
7309
7310 Quals1.removeCVRQualifiers();
7311 Quals2.removeCVRQualifiers();
7312 if (Quals1 != Quals2)
7313 return false;
7314
7315 if (hasSameType(T1, T2))
7316 return true;
7317
7318 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7319 return false;
7320 }
7321}
7322
7323DeclarationNameInfo
7324ASTContext::getNameForTemplate(TemplateName Name,
7325 SourceLocation NameLoc) const {
7326 switch (Name.getKind()) {
7327 case TemplateName::QualifiedTemplate:
7328 case TemplateName::Template:
7329 // DNInfo work in progress: CHECKME: what about DNLoc?
7330 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
7331 NameLoc);
7332
7333 case TemplateName::OverloadedTemplate: {
7334 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
7335 // DNInfo work in progress: CHECKME: what about DNLoc?
7336 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7337 }
7338
7339 case TemplateName::AssumedTemplate: {
7340 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
7341 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7342 }
7343
7344 case TemplateName::DependentTemplate: {
7345 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7346 IdentifierOrOverloadedOperator TN = DTN->getName();
7347 DeclarationName DName;
7348 if (const IdentifierInfo *II = TN.getIdentifier()) {
7349 DName = DeclarationNames.getIdentifier(ID: II);
7350 return DeclarationNameInfo(DName, NameLoc);
7351 } else {
7352 DName = DeclarationNames.getCXXOperatorName(Op: TN.getOperator());
7353 // DNInfo work in progress: FIXME: source locations?
7354 DeclarationNameLoc DNLoc =
7355 DeclarationNameLoc::makeCXXOperatorNameLoc(Range: SourceRange());
7356 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7357 }
7358 }
7359
7360 case TemplateName::SubstTemplateTemplateParm: {
7361 SubstTemplateTemplateParmStorage *subst
7362 = Name.getAsSubstTemplateTemplateParm();
7363 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7364 NameLoc);
7365 }
7366
7367 case TemplateName::SubstTemplateTemplateParmPack: {
7368 SubstTemplateTemplateParmPackStorage *subst
7369 = Name.getAsSubstTemplateTemplateParmPack();
7370 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
7371 NameLoc);
7372 }
7373 case TemplateName::UsingTemplate:
7374 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
7375 NameLoc);
7376 case TemplateName::DeducedTemplate: {
7377 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7378 return getNameForTemplate(Name: DTS->getUnderlying(), NameLoc);
7379 }
7380 }
7381
7382 llvm_unreachable("bad template name kind!");
7383}
7384
7385const TemplateArgument *
7386ASTContext::getDefaultTemplateArgumentOrNone(const NamedDecl *P) const {
7387 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7388 if (!TP->hasDefaultArgument())
7389 return nullptr;
7390 return &TP->getDefaultArgument().getArgument();
7391 };
7392 switch (P->getKind()) {
7393 case NamedDecl::TemplateTypeParm:
7394 return handleParam(cast<TemplateTypeParmDecl>(Val: P));
7395 case NamedDecl::NonTypeTemplateParm:
7396 return handleParam(cast<NonTypeTemplateParmDecl>(Val: P));
7397 case NamedDecl::TemplateTemplateParm:
7398 return handleParam(cast<TemplateTemplateParmDecl>(Val: P));
7399 default:
7400 llvm_unreachable("Unexpected template parameter kind");
7401 }
7402}
7403
7404TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name,
7405 bool IgnoreDeduced) const {
7406 while (std::optional<TemplateName> UnderlyingOrNone =
7407 Name.desugar(IgnoreDeduced))
7408 Name = *UnderlyingOrNone;
7409
7410 switch (Name.getKind()) {
7411 case TemplateName::Template: {
7412 TemplateDecl *Template = Name.getAsTemplateDecl();
7413 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: Template))
7414 Template = getCanonicalTemplateTemplateParmDecl(TTP);
7415
7416 // The canonical template name is the canonical template declaration.
7417 return TemplateName(cast<TemplateDecl>(Val: Template->getCanonicalDecl()));
7418 }
7419
7420 case TemplateName::AssumedTemplate:
7421 // An assumed template is just a name, so it is already canonical.
7422 return Name;
7423
7424 case TemplateName::OverloadedTemplate:
7425 llvm_unreachable("cannot canonicalize overloaded template");
7426
7427 case TemplateName::DependentTemplate: {
7428 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7429 assert(DTN && "Non-dependent template names must refer to template decls.");
7430 NestedNameSpecifier Qualifier = DTN->getQualifier();
7431 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7432 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7433 return getDependentTemplateName(Name: {CanonQualifier, DTN->getName(),
7434 /*HasTemplateKeyword=*/true});
7435 return Name;
7436 }
7437
7438 case TemplateName::SubstTemplateTemplateParmPack: {
7439 SubstTemplateTemplateParmPackStorage *subst =
7440 Name.getAsSubstTemplateTemplateParmPack();
7441 TemplateArgument canonArgPack =
7442 getCanonicalTemplateArgument(Arg: subst->getArgumentPack());
7443 return getSubstTemplateTemplateParmPack(
7444 ArgPack: canonArgPack, AssociatedDecl: subst->getAssociatedDecl()->getCanonicalDecl(),
7445 Index: subst->getIndex(), Final: subst->getFinal());
7446 }
7447 case TemplateName::DeducedTemplate: {
7448 assert(IgnoreDeduced == false);
7449 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7450 DefaultArguments DefArgs = DTS->getDefaultArguments();
7451 TemplateName Underlying = DTS->getUnderlying();
7452
7453 TemplateName CanonUnderlying =
7454 getCanonicalTemplateName(Name: Underlying, /*IgnoreDeduced=*/true);
7455 bool NonCanonical = CanonUnderlying != Underlying;
7456 auto CanonArgs =
7457 getCanonicalTemplateArguments(C: *this, Args: DefArgs.Args, AnyNonCanonArgs&: NonCanonical);
7458
7459 ArrayRef<NamedDecl *> Params =
7460 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7461 assert(CanonArgs.size() <= Params.size());
7462 // A deduced template name which deduces the same default arguments already
7463 // declared in the underlying template is the same template as the
7464 // underlying template. We need need to note any arguments which differ from
7465 // the corresponding declaration. If any argument differs, we must build a
7466 // deduced template name.
7467 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7468 const TemplateArgument *A = getDefaultTemplateArgumentOrNone(P: Params[I]);
7469 if (!A)
7470 break;
7471 auto CanonParamDefArg = getCanonicalTemplateArgument(Arg: *A);
7472 TemplateArgument &CanonDefArg = CanonArgs[I];
7473 if (CanonDefArg.structurallyEquals(Other: CanonParamDefArg))
7474 continue;
7475 // Keep popping from the back any deault arguments which are the same.
7476 if (I == int(CanonArgs.size() - 1))
7477 CanonArgs.pop_back();
7478 NonCanonical = true;
7479 }
7480 return NonCanonical ? getDeducedTemplateName(
7481 Underlying: CanonUnderlying,
7482 /*DefaultArgs=*/{.StartPos: DefArgs.StartPos, .Args: CanonArgs})
7483 : Name;
7484 }
7485 case TemplateName::UsingTemplate:
7486 case TemplateName::QualifiedTemplate:
7487 case TemplateName::SubstTemplateTemplateParm:
7488 llvm_unreachable("always sugar node");
7489 }
7490
7491 llvm_unreachable("bad template name!");
7492}
7493
7494bool ASTContext::hasSameTemplateName(const TemplateName &X,
7495 const TemplateName &Y,
7496 bool IgnoreDeduced) const {
7497 return getCanonicalTemplateName(Name: X, IgnoreDeduced) ==
7498 getCanonicalTemplateName(Name: Y, IgnoreDeduced);
7499}
7500
7501bool ASTContext::isSameAssociatedConstraint(
7502 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7503 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7504 return false;
7505 if (!isSameConstraintExpr(XCE: ACX.ConstraintExpr, YCE: ACY.ConstraintExpr))
7506 return false;
7507 return true;
7508}
7509
7510bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7511 if (!XCE != !YCE)
7512 return false;
7513
7514 if (!XCE)
7515 return true;
7516
7517 llvm::FoldingSetNodeID XCEID, YCEID;
7518 XCE->Profile(ID&: XCEID, Context: *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7519 YCE->Profile(ID&: YCEID, Context: *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7520 return XCEID == YCEID;
7521}
7522
7523bool ASTContext::isSameTypeConstraint(const TypeConstraint *XTC,
7524 const TypeConstraint *YTC) const {
7525 if (!XTC != !YTC)
7526 return false;
7527
7528 if (!XTC)
7529 return true;
7530
7531 auto *NCX = XTC->getNamedConcept();
7532 auto *NCY = YTC->getNamedConcept();
7533 if (!NCX || !NCY || !isSameEntity(X: NCX, Y: NCY))
7534 return false;
7535 if (XTC->getConceptReference()->hasExplicitTemplateArgs() !=
7536 YTC->getConceptReference()->hasExplicitTemplateArgs())
7537 return false;
7538 if (XTC->getConceptReference()->hasExplicitTemplateArgs())
7539 if (XTC->getConceptReference()
7540 ->getTemplateArgsAsWritten()
7541 ->NumTemplateArgs !=
7542 YTC->getConceptReference()->getTemplateArgsAsWritten()->NumTemplateArgs)
7543 return false;
7544
7545 // Compare slowly by profiling.
7546 //
7547 // We couldn't compare the profiling result for the template
7548 // args here. Consider the following example in different modules:
7549 //
7550 // template <__integer_like _Tp, C<_Tp> Sentinel>
7551 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7552 // return __t;
7553 // }
7554 //
7555 // When we compare the profiling result for `C<_Tp>` in different
7556 // modules, it will compare the type of `_Tp` in different modules.
7557 // However, the type of `_Tp` in different modules refer to different
7558 // types here naturally. So we couldn't compare the profiling result
7559 // for the template args directly.
7560 return isSameConstraintExpr(XCE: XTC->getImmediatelyDeclaredConstraint(),
7561 YCE: YTC->getImmediatelyDeclaredConstraint());
7562}
7563
7564bool ASTContext::isSameTemplateParameter(const NamedDecl *X,
7565 const NamedDecl *Y) const {
7566 if (X->getKind() != Y->getKind())
7567 return false;
7568
7569 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(Val: X)) {
7570 auto *TY = cast<TemplateTypeParmDecl>(Val: Y);
7571 if (TX->isParameterPack() != TY->isParameterPack())
7572 return false;
7573 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7574 return false;
7575 return isSameTypeConstraint(XTC: TX->getTypeConstraint(),
7576 YTC: TY->getTypeConstraint());
7577 }
7578
7579 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(Val: X)) {
7580 auto *TY = cast<NonTypeTemplateParmDecl>(Val: Y);
7581 return TX->isParameterPack() == TY->isParameterPack() &&
7582 TX->getASTContext().hasSameType(T1: TX->getType(), T2: TY->getType()) &&
7583 isSameConstraintExpr(XCE: TX->getPlaceholderTypeConstraint(),
7584 YCE: TY->getPlaceholderTypeConstraint());
7585 }
7586
7587 auto *TX = cast<TemplateTemplateParmDecl>(Val: X);
7588 auto *TY = cast<TemplateTemplateParmDecl>(Val: Y);
7589 return TX->isParameterPack() == TY->isParameterPack() &&
7590 isSameTemplateParameterList(X: TX->getTemplateParameters(),
7591 Y: TY->getTemplateParameters());
7592}
7593
7594bool ASTContext::isSameTemplateParameterList(
7595 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7596 if (X->size() != Y->size())
7597 return false;
7598
7599 for (unsigned I = 0, N = X->size(); I != N; ++I)
7600 if (!isSameTemplateParameter(X: X->getParam(Idx: I), Y: Y->getParam(Idx: I)))
7601 return false;
7602
7603 return isSameConstraintExpr(XCE: X->getRequiresClause(), YCE: Y->getRequiresClause());
7604}
7605
7606bool ASTContext::isSameDefaultTemplateArgument(const NamedDecl *X,
7607 const NamedDecl *Y) const {
7608 // If the type parameter isn't the same already, we don't need to check the
7609 // default argument further.
7610 if (!isSameTemplateParameter(X, Y))
7611 return false;
7612
7613 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(Val: X)) {
7614 auto *TTPY = cast<TemplateTypeParmDecl>(Val: Y);
7615 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7616 return false;
7617
7618 return hasSameType(T1: TTPX->getDefaultArgument().getArgument().getAsType(),
7619 T2: TTPY->getDefaultArgument().getArgument().getAsType());
7620 }
7621
7622 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(Val: X)) {
7623 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Val: Y);
7624 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7625 return false;
7626
7627 Expr *DefaultArgumentX =
7628 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7629 Expr *DefaultArgumentY =
7630 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7631 llvm::FoldingSetNodeID XID, YID;
7632 DefaultArgumentX->Profile(ID&: XID, Context: *this, /*Canonical=*/true);
7633 DefaultArgumentY->Profile(ID&: YID, Context: *this, /*Canonical=*/true);
7634 return XID == YID;
7635 }
7636
7637 auto *TTPX = cast<TemplateTemplateParmDecl>(Val: X);
7638 auto *TTPY = cast<TemplateTemplateParmDecl>(Val: Y);
7639
7640 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7641 return false;
7642
7643 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7644 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7645 return hasSameTemplateName(X: TAX.getAsTemplate(), Y: TAY.getAsTemplate());
7646}
7647
7648static bool isSameQualifier(const NestedNameSpecifier X,
7649 const NestedNameSpecifier Y) {
7650 if (X == Y)
7651 return true;
7652 if (!X || !Y)
7653 return false;
7654
7655 auto Kind = X.getKind();
7656 if (Kind != Y.getKind())
7657 return false;
7658
7659 // FIXME: For namespaces and types, we're permitted to check that the entity
7660 // is named via the same tokens. We should probably do so.
7661 switch (Kind) {
7662 case NestedNameSpecifier::Kind::Namespace: {
7663 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7664 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7665 if (!declaresSameEntity(D1: NamespaceX->getNamespace(),
7666 D2: NamespaceY->getNamespace()))
7667 return false;
7668 return isSameQualifier(X: PrefixX, Y: PrefixY);
7669 }
7670 case NestedNameSpecifier::Kind::Type: {
7671 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7672 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7673 return false;
7674 return isSameQualifier(X: TX->getPrefix(), Y: TY->getPrefix());
7675 }
7676 case NestedNameSpecifier::Kind::Null:
7677 case NestedNameSpecifier::Kind::Global:
7678 case NestedNameSpecifier::Kind::MicrosoftSuper:
7679 return true;
7680 }
7681 llvm_unreachable("unhandled qualifier kind");
7682}
7683
7684static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7685 if (!A->getASTContext().getLangOpts().CUDA)
7686 return true; // Target attributes are overloadable in CUDA compilation only.
7687 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7688 return false;
7689 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7690 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7691 return true; // unattributed and __host__ functions are the same.
7692}
7693
7694/// Determine whether the attributes we can overload on are identical for A and
7695/// B. Will ignore any overloadable attrs represented in the type of A and B.
7696static bool hasSameOverloadableAttrs(const FunctionDecl *A,
7697 const FunctionDecl *B) {
7698 // Note that pass_object_size attributes are represented in the function's
7699 // ExtParameterInfo, so we don't need to check them here.
7700
7701 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7702 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7703 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7704
7705 for (auto Pair : zip_longest(t&: AEnableIfAttrs, u&: BEnableIfAttrs)) {
7706 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
7707 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
7708
7709 // Return false if the number of enable_if attributes is different.
7710 if (!Cand1A || !Cand2A)
7711 return false;
7712
7713 Cand1ID.clear();
7714 Cand2ID.clear();
7715
7716 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: A->getASTContext(), Canonical: true);
7717 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: B->getASTContext(), Canonical: true);
7718
7719 // Return false if any of the enable_if expressions of A and B are
7720 // different.
7721 if (Cand1ID != Cand2ID)
7722 return false;
7723 }
7724 return hasSameCudaAttrs(A, B);
7725}
7726
7727bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7728 // Caution: this function is called by the AST reader during deserialization,
7729 // so it cannot rely on AST invariants being met. Non-trivial accessors
7730 // should be avoided, along with any traversal of redeclaration chains.
7731
7732 if (X == Y)
7733 return true;
7734
7735 if (X->getDeclName() != Y->getDeclName())
7736 return false;
7737
7738 // Must be in the same context.
7739 //
7740 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7741 // could be two different declarations of the same function. (We will fix the
7742 // semantic DC to refer to the primary definition after merging.)
7743 if (!declaresSameEntity(D1: cast<Decl>(Val: X->getDeclContext()->getRedeclContext()),
7744 D2: cast<Decl>(Val: Y->getDeclContext()->getRedeclContext())))
7745 return false;
7746
7747 // If either X or Y are local to the owning module, they are only possible to
7748 // be the same entity if they are in the same module.
7749 if (X->isModuleLocal() || Y->isModuleLocal())
7750 if (!isInSameModule(M1: X->getOwningModule(), M2: Y->getOwningModule()))
7751 return false;
7752
7753 // Two typedefs refer to the same entity if they have the same underlying
7754 // type.
7755 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(Val: X))
7756 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Val: Y))
7757 return hasSameType(T1: TypedefX->getUnderlyingType(),
7758 T2: TypedefY->getUnderlyingType());
7759
7760 // Must have the same kind.
7761 if (X->getKind() != Y->getKind())
7762 return false;
7763
7764 // Objective-C classes and protocols with the same name always match.
7765 if (isa<ObjCInterfaceDecl>(Val: X) || isa<ObjCProtocolDecl>(Val: X))
7766 return true;
7767
7768 if (isa<ClassTemplateSpecializationDecl>(Val: X)) {
7769 // No need to handle these here: we merge them when adding them to the
7770 // template.
7771 return false;
7772 }
7773
7774 // Compatible tags match.
7775 if (const auto *TagX = dyn_cast<TagDecl>(Val: X)) {
7776 const auto *TagY = cast<TagDecl>(Val: Y);
7777 return (TagX->getTagKind() == TagY->getTagKind()) ||
7778 ((TagX->getTagKind() == TagTypeKind::Struct ||
7779 TagX->getTagKind() == TagTypeKind::Class ||
7780 TagX->getTagKind() == TagTypeKind::Interface) &&
7781 (TagY->getTagKind() == TagTypeKind::Struct ||
7782 TagY->getTagKind() == TagTypeKind::Class ||
7783 TagY->getTagKind() == TagTypeKind::Interface));
7784 }
7785
7786 // Functions with the same type and linkage match.
7787 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7788 // functions, etc.
7789 if (const auto *FuncX = dyn_cast<FunctionDecl>(Val: X)) {
7790 const auto *FuncY = cast<FunctionDecl>(Val: Y);
7791 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(Val: X)) {
7792 const auto *CtorY = cast<CXXConstructorDecl>(Val: Y);
7793 if (CtorX->getInheritedConstructor() &&
7794 !isSameEntity(X: CtorX->getInheritedConstructor().getConstructor(),
7795 Y: CtorY->getInheritedConstructor().getConstructor()))
7796 return false;
7797 }
7798
7799 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7800 return false;
7801
7802 // Multiversioned functions with different feature strings are represented
7803 // as separate declarations.
7804 if (FuncX->isMultiVersion()) {
7805 const auto *TAX = FuncX->getAttr<TargetAttr>();
7806 const auto *TAY = FuncY->getAttr<TargetAttr>();
7807 assert(TAX && TAY && "Multiversion Function without target attribute");
7808
7809 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7810 return false;
7811 }
7812
7813 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7814 // not the same entity if they are constrained.
7815 if ((FuncX->isMemberLikeConstrainedFriend() ||
7816 FuncY->isMemberLikeConstrainedFriend()) &&
7817 !FuncX->getLexicalDeclContext()->Equals(
7818 DC: FuncY->getLexicalDeclContext())) {
7819 return false;
7820 }
7821
7822 if (!isSameAssociatedConstraint(ACX: FuncX->getTrailingRequiresClause(),
7823 ACY: FuncY->getTrailingRequiresClause()))
7824 return false;
7825
7826 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7827 // Map to the first declaration that we've already merged into this one.
7828 // The TSI of redeclarations might not match (due to calling conventions
7829 // being inherited onto the type but not the TSI), but the TSI type of
7830 // the first declaration of the function should match across modules.
7831 FD = FD->getCanonicalDecl();
7832 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7833 : FD->getType();
7834 };
7835 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7836 if (!hasSameType(T1: XT, T2: YT)) {
7837 // We can get functions with different types on the redecl chain in C++17
7838 // if they have differing exception specifications and at least one of
7839 // the excpetion specs is unresolved.
7840 auto *XFPT = XT->getAs<FunctionProtoType>();
7841 auto *YFPT = YT->getAs<FunctionProtoType>();
7842 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7843 (isUnresolvedExceptionSpec(ESpecType: XFPT->getExceptionSpecType()) ||
7844 isUnresolvedExceptionSpec(ESpecType: YFPT->getExceptionSpecType())) &&
7845 hasSameFunctionTypeIgnoringExceptionSpec(T: XT, U: YT))
7846 return true;
7847 return false;
7848 }
7849
7850 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7851 hasSameOverloadableAttrs(A: FuncX, B: FuncY);
7852 }
7853
7854 // Variables with the same type and linkage match.
7855 if (const auto *VarX = dyn_cast<VarDecl>(Val: X)) {
7856 const auto *VarY = cast<VarDecl>(Val: Y);
7857 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7858 // During deserialization, we might compare variables before we load
7859 // their types. Assume the types will end up being the same.
7860 if (VarX->getType().isNull() || VarY->getType().isNull())
7861 return true;
7862
7863 if (hasSameType(T1: VarX->getType(), T2: VarY->getType()))
7864 return true;
7865
7866 // We can get decls with different types on the redecl chain. Eg.
7867 // template <typename T> struct S { static T Var[]; }; // #1
7868 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7869 // Only? happens when completing an incomplete array type. In this case
7870 // when comparing #1 and #2 we should go through their element type.
7871 const ArrayType *VarXTy = getAsArrayType(T: VarX->getType());
7872 const ArrayType *VarYTy = getAsArrayType(T: VarY->getType());
7873 if (!VarXTy || !VarYTy)
7874 return false;
7875 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7876 return hasSameType(T1: VarXTy->getElementType(), T2: VarYTy->getElementType());
7877 }
7878 return false;
7879 }
7880
7881 // Namespaces with the same name and inlinedness match.
7882 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(Val: X)) {
7883 const auto *NamespaceY = cast<NamespaceDecl>(Val: Y);
7884 return NamespaceX->isInline() == NamespaceY->isInline();
7885 }
7886
7887 // Identical template names and kinds match if their template parameter lists
7888 // and patterns match.
7889 if (const auto *TemplateX = dyn_cast<TemplateDecl>(Val: X)) {
7890 const auto *TemplateY = cast<TemplateDecl>(Val: Y);
7891
7892 // ConceptDecl wouldn't be the same if their constraint expression differs.
7893 if (const auto *ConceptX = dyn_cast<ConceptDecl>(Val: X)) {
7894 const auto *ConceptY = cast<ConceptDecl>(Val: Y);
7895 if (!isSameConstraintExpr(XCE: ConceptX->getConstraintExpr(),
7896 YCE: ConceptY->getConstraintExpr()))
7897 return false;
7898 }
7899
7900 return isSameEntity(X: TemplateX->getTemplatedDecl(),
7901 Y: TemplateY->getTemplatedDecl()) &&
7902 isSameTemplateParameterList(X: TemplateX->getTemplateParameters(),
7903 Y: TemplateY->getTemplateParameters());
7904 }
7905
7906 // Fields with the same name and the same type match.
7907 if (const auto *FDX = dyn_cast<FieldDecl>(Val: X)) {
7908 const auto *FDY = cast<FieldDecl>(Val: Y);
7909 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7910 return hasSameType(T1: FDX->getType(), T2: FDY->getType());
7911 }
7912
7913 // Indirect fields with the same target field match.
7914 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(Val: X)) {
7915 const auto *IFDY = cast<IndirectFieldDecl>(Val: Y);
7916 return IFDX->getAnonField()->getCanonicalDecl() ==
7917 IFDY->getAnonField()->getCanonicalDecl();
7918 }
7919
7920 // Enumerators with the same name match.
7921 if (isa<EnumConstantDecl>(Val: X))
7922 // FIXME: Also check the value is odr-equivalent.
7923 return true;
7924
7925 // Using shadow declarations with the same target match.
7926 if (const auto *USX = dyn_cast<UsingShadowDecl>(Val: X)) {
7927 const auto *USY = cast<UsingShadowDecl>(Val: Y);
7928 return declaresSameEntity(D1: USX->getTargetDecl(), D2: USY->getTargetDecl());
7929 }
7930
7931 // Using declarations with the same qualifier match. (We already know that
7932 // the name matches.)
7933 if (const auto *UX = dyn_cast<UsingDecl>(Val: X)) {
7934 const auto *UY = cast<UsingDecl>(Val: Y);
7935 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
7936 UX->hasTypename() == UY->hasTypename() &&
7937 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7938 }
7939 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(Val: X)) {
7940 const auto *UY = cast<UnresolvedUsingValueDecl>(Val: Y);
7941 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
7942 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7943 }
7944 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(Val: X)) {
7945 return isSameQualifier(
7946 X: UX->getQualifier(),
7947 Y: cast<UnresolvedUsingTypenameDecl>(Val: Y)->getQualifier());
7948 }
7949
7950 // Using-pack declarations are only created by instantiation, and match if
7951 // they're instantiated from matching UnresolvedUsing...Decls.
7952 if (const auto *UX = dyn_cast<UsingPackDecl>(Val: X)) {
7953 return declaresSameEntity(
7954 D1: UX->getInstantiatedFromUsingDecl(),
7955 D2: cast<UsingPackDecl>(Val: Y)->getInstantiatedFromUsingDecl());
7956 }
7957
7958 // Namespace alias definitions with the same target match.
7959 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(Val: X)) {
7960 const auto *NAY = cast<NamespaceAliasDecl>(Val: Y);
7961 return NAX->getNamespace()->Equals(DC: NAY->getNamespace());
7962 }
7963
7964 if (const auto *UX = dyn_cast<UsingEnumDecl>(Val: X)) {
7965 const auto *UY = cast<UsingEnumDecl>(Val: Y);
7966 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
7967 declaresSameEntity(D1: UX->getEnumDecl(), D2: UY->getEnumDecl());
7968 }
7969
7970 return false;
7971}
7972
7973TemplateArgument
7974ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
7975 switch (Arg.getKind()) {
7976 case TemplateArgument::Null:
7977 return Arg;
7978
7979 case TemplateArgument::Expression:
7980 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7981 Arg.getIsDefaulted());
7982
7983 case TemplateArgument::Declaration: {
7984 auto *D = cast<ValueDecl>(Val: Arg.getAsDecl()->getCanonicalDecl());
7985 return TemplateArgument(D, getCanonicalType(T: Arg.getParamTypeForDecl()),
7986 Arg.getIsDefaulted());
7987 }
7988
7989 case TemplateArgument::NullPtr:
7990 return TemplateArgument(getCanonicalType(T: Arg.getNullPtrType()),
7991 /*isNullPtr*/ true, Arg.getIsDefaulted());
7992
7993 case TemplateArgument::Template:
7994 return TemplateArgument(getCanonicalTemplateName(Name: Arg.getAsTemplate()),
7995 Arg.getIsDefaulted());
7996
7997 case TemplateArgument::TemplateExpansion:
7998 return TemplateArgument(
7999 getCanonicalTemplateName(Name: Arg.getAsTemplateOrTemplatePattern()),
8000 Arg.getNumTemplateExpansions(), Arg.getIsDefaulted());
8001
8002 case TemplateArgument::Integral:
8003 return TemplateArgument(Arg, getCanonicalType(T: Arg.getIntegralType()));
8004
8005 case TemplateArgument::StructuralValue:
8006 return TemplateArgument(*this,
8007 getCanonicalType(T: Arg.getStructuralValueType()),
8008 Arg.getAsStructuralValue(), Arg.getIsDefaulted());
8009
8010 case TemplateArgument::Type:
8011 return TemplateArgument(getCanonicalType(T: Arg.getAsType()),
8012 /*isNullPtr*/ false, Arg.getIsDefaulted());
8013
8014 case TemplateArgument::Pack: {
8015 bool AnyNonCanonArgs = false;
8016 auto CanonArgs = ::getCanonicalTemplateArguments(
8017 C: *this, Args: Arg.pack_elements(), AnyNonCanonArgs);
8018 if (!AnyNonCanonArgs)
8019 return Arg;
8020 auto NewArg = TemplateArgument::CreatePackCopy(
8021 Context&: const_cast<ASTContext &>(*this), Args: CanonArgs);
8022 NewArg.setIsDefaulted(Arg.getIsDefaulted());
8023 return NewArg;
8024 }
8025 }
8026
8027 // Silence GCC warning
8028 llvm_unreachable("Unhandled template argument kind");
8029}
8030
8031bool ASTContext::isSameTemplateArgument(const TemplateArgument &Arg1,
8032 const TemplateArgument &Arg2) const {
8033 if (Arg1.getKind() != Arg2.getKind())
8034 return false;
8035
8036 switch (Arg1.getKind()) {
8037 case TemplateArgument::Null:
8038 llvm_unreachable("Comparing NULL template argument");
8039
8040 case TemplateArgument::Type:
8041 return hasSameType(T1: Arg1.getAsType(), T2: Arg2.getAsType());
8042
8043 case TemplateArgument::Declaration:
8044 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
8045 Arg2.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl();
8046
8047 case TemplateArgument::NullPtr:
8048 return hasSameType(T1: Arg1.getNullPtrType(), T2: Arg2.getNullPtrType());
8049
8050 case TemplateArgument::Template:
8051 case TemplateArgument::TemplateExpansion:
8052 return getCanonicalTemplateName(Name: Arg1.getAsTemplateOrTemplatePattern()) ==
8053 getCanonicalTemplateName(Name: Arg2.getAsTemplateOrTemplatePattern());
8054
8055 case TemplateArgument::Integral:
8056 return llvm::APSInt::isSameValue(I1: Arg1.getAsIntegral(),
8057 I2: Arg2.getAsIntegral());
8058
8059 case TemplateArgument::StructuralValue:
8060 return Arg1.structurallyEquals(Other: Arg2);
8061
8062 case TemplateArgument::Expression: {
8063 llvm::FoldingSetNodeID ID1, ID2;
8064 Arg1.getAsExpr()->Profile(ID&: ID1, Context: *this, /*Canonical=*/true);
8065 Arg2.getAsExpr()->Profile(ID&: ID2, Context: *this, /*Canonical=*/true);
8066 return ID1 == ID2;
8067 }
8068
8069 case TemplateArgument::Pack:
8070 return llvm::equal(
8071 LRange: Arg1.getPackAsArray(), RRange: Arg2.getPackAsArray(),
8072 P: [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8073 return isSameTemplateArgument(Arg1, Arg2);
8074 });
8075 }
8076
8077 llvm_unreachable("Unhandled template argument kind");
8078}
8079
8080const ArrayType *ASTContext::getAsArrayType(QualType T) const {
8081 // Handle the non-qualified case efficiently.
8082 if (!T.hasLocalQualifiers()) {
8083 // Handle the common positive case fast.
8084 if (const auto *AT = dyn_cast<ArrayType>(Val&: T))
8085 return AT;
8086 }
8087
8088 // Handle the common negative case fast.
8089 if (!isa<ArrayType>(Val: T.getCanonicalType()))
8090 return nullptr;
8091
8092 // Apply any qualifiers from the array type to the element type. This
8093 // implements C99 6.7.3p8: "If the specification of an array type includes
8094 // any type qualifiers, the element type is so qualified, not the array type."
8095
8096 // If we get here, we either have type qualifiers on the type, or we have
8097 // sugar such as a typedef in the way. If we have type qualifiers on the type
8098 // we must propagate them down into the element type.
8099
8100 SplitQualType split = T.getSplitDesugaredType();
8101 Qualifiers qs = split.Quals;
8102
8103 // If we have a simple case, just return now.
8104 const auto *ATy = dyn_cast<ArrayType>(Val: split.Ty);
8105 if (!ATy || qs.empty())
8106 return ATy;
8107
8108 // Otherwise, we have an array and we have qualifiers on it. Push the
8109 // qualifiers into the array element type and return a new array type.
8110 QualType NewEltTy = getQualifiedType(T: ATy->getElementType(), Qs: qs);
8111
8112 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: ATy))
8113 return cast<ArrayType>(Val: getConstantArrayType(EltTy: NewEltTy, ArySizeIn: CAT->getSize(),
8114 SizeExpr: CAT->getSizeExpr(),
8115 ASM: CAT->getSizeModifier(),
8116 IndexTypeQuals: CAT->getIndexTypeCVRQualifiers()));
8117 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: ATy))
8118 return cast<ArrayType>(Val: getIncompleteArrayType(elementType: NewEltTy,
8119 ASM: IAT->getSizeModifier(),
8120 elementTypeQuals: IAT->getIndexTypeCVRQualifiers()));
8121
8122 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(Val: ATy))
8123 return cast<ArrayType>(Val: getDependentSizedArrayType(
8124 elementType: NewEltTy, numElements: DSAT->getSizeExpr(), ASM: DSAT->getSizeModifier(),
8125 elementTypeQuals: DSAT->getIndexTypeCVRQualifiers()));
8126
8127 const auto *VAT = cast<VariableArrayType>(Val: ATy);
8128 return cast<ArrayType>(
8129 Val: getVariableArrayType(EltTy: NewEltTy, NumElts: VAT->getSizeExpr(), ASM: VAT->getSizeModifier(),
8130 IndexTypeQuals: VAT->getIndexTypeCVRQualifiers()));
8131}
8132
8133QualType ASTContext::getAdjustedParameterType(QualType T) const {
8134 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8135 return getLValueReferenceType(T);
8136 if (getLangOpts().HLSL && T->isConstantArrayType())
8137 return getArrayParameterType(Ty: T);
8138 if (T->isArrayType() || T->isFunctionType())
8139 return getDecayedType(T);
8140 return T;
8141}
8142
8143QualType ASTContext::getSignatureParameterType(QualType T) const {
8144 T = getVariableArrayDecayedType(type: T);
8145 T = getAdjustedParameterType(T);
8146 return T.getUnqualifiedType();
8147}
8148
8149QualType ASTContext::getExceptionObjectType(QualType T) const {
8150 // C++ [except.throw]p3:
8151 // A throw-expression initializes a temporary object, called the exception
8152 // object, the type of which is determined by removing any top-level
8153 // cv-qualifiers from the static type of the operand of throw and adjusting
8154 // the type from "array of T" or "function returning T" to "pointer to T"
8155 // or "pointer to function returning T", [...]
8156 T = getVariableArrayDecayedType(type: T);
8157 if (T->isArrayType() || T->isFunctionType())
8158 T = getDecayedType(T);
8159 return T.getUnqualifiedType();
8160}
8161
8162/// getArrayDecayedType - Return the properly qualified result of decaying the
8163/// specified array type to a pointer. This operation is non-trivial when
8164/// handling typedefs etc. The canonical type of "T" must be an array type,
8165/// this returns a pointer to a properly qualified element of the array.
8166///
8167/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8168QualType ASTContext::getArrayDecayedType(QualType Ty) const {
8169 // Get the element type with 'getAsArrayType' so that we don't lose any
8170 // typedefs in the element type of the array. This also handles propagation
8171 // of type qualifiers from the array type into the element type if present
8172 // (C99 6.7.3p8).
8173 const ArrayType *PrettyArrayType = getAsArrayType(T: Ty);
8174 assert(PrettyArrayType && "Not an array type!");
8175
8176 QualType PtrTy = getPointerType(T: PrettyArrayType->getElementType());
8177
8178 // int x[restrict 4] -> int *restrict
8179 QualType Result = getQualifiedType(T: PtrTy,
8180 Qs: PrettyArrayType->getIndexTypeQualifiers());
8181
8182 // int x[_Nullable] -> int * _Nullable
8183 if (auto Nullability = Ty->getNullability()) {
8184 Result = const_cast<ASTContext *>(this)->getAttributedType(nullability: *Nullability,
8185 modifiedType: Result, equivalentType: Result);
8186 }
8187 return Result;
8188}
8189
8190QualType ASTContext::getBaseElementType(const ArrayType *array) const {
8191 return getBaseElementType(QT: array->getElementType());
8192}
8193
8194QualType ASTContext::getBaseElementType(QualType type) const {
8195 Qualifiers qs;
8196 while (true) {
8197 SplitQualType split = type.getSplitDesugaredType();
8198 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8199 if (!array) break;
8200
8201 type = array->getElementType();
8202 qs.addConsistentQualifiers(qs: split.Quals);
8203 }
8204
8205 return getQualifiedType(T: type, Qs: qs);
8206}
8207
8208/// getConstantArrayElementCount - Returns number of constant array elements.
8209uint64_t
8210ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
8211 uint64_t ElementCount = 1;
8212 do {
8213 ElementCount *= CA->getZExtSize();
8214 CA = dyn_cast_or_null<ConstantArrayType>(
8215 Val: CA->getElementType()->getAsArrayTypeUnsafe());
8216 } while (CA);
8217 return ElementCount;
8218}
8219
8220uint64_t ASTContext::getArrayInitLoopExprElementCount(
8221 const ArrayInitLoopExpr *AILE) const {
8222 if (!AILE)
8223 return 0;
8224
8225 uint64_t ElementCount = 1;
8226
8227 do {
8228 ElementCount *= AILE->getArraySize().getZExtValue();
8229 AILE = dyn_cast<ArrayInitLoopExpr>(Val: AILE->getSubExpr());
8230 } while (AILE);
8231
8232 return ElementCount;
8233}
8234
8235/// getFloatingRank - Return a relative rank for floating point types.
8236/// This routine will assert if passed a built-in type that isn't a float.
8237static FloatingRank getFloatingRank(QualType T) {
8238 if (const auto *CT = T->getAs<ComplexType>())
8239 return getFloatingRank(T: CT->getElementType());
8240
8241 switch (T->castAs<BuiltinType>()->getKind()) {
8242 default: llvm_unreachable("getFloatingRank(): not a floating type");
8243 case BuiltinType::Float16: return Float16Rank;
8244 case BuiltinType::Half: return HalfRank;
8245 case BuiltinType::Float: return FloatRank;
8246 case BuiltinType::Double: return DoubleRank;
8247 case BuiltinType::LongDouble: return LongDoubleRank;
8248 case BuiltinType::Float128: return Float128Rank;
8249 case BuiltinType::BFloat16: return BFloat16Rank;
8250 case BuiltinType::Ibm128: return Ibm128Rank;
8251 }
8252}
8253
8254/// getFloatingTypeOrder - Compare the rank of the two specified floating
8255/// point types, ignoring the domain of the type (i.e. 'double' ==
8256/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8257/// LHS < RHS, return -1.
8258int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
8259 FloatingRank LHSR = getFloatingRank(T: LHS);
8260 FloatingRank RHSR = getFloatingRank(T: RHS);
8261
8262 if (LHSR == RHSR)
8263 return 0;
8264 if (LHSR > RHSR)
8265 return 1;
8266 return -1;
8267}
8268
8269int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
8270 if (&getFloatTypeSemantics(T: LHS) == &getFloatTypeSemantics(T: RHS))
8271 return 0;
8272 return getFloatingTypeOrder(LHS, RHS);
8273}
8274
8275/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8276/// routine will assert if passed a built-in type that isn't an integer or enum,
8277/// or if it is not canonicalized.
8278unsigned ASTContext::getIntegerRank(const Type *T) const {
8279 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8280
8281 // Results in this 'losing' to any type of the same size, but winning if
8282 // larger.
8283 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
8284 return 0 + (EIT->getNumBits() << 3);
8285
8286 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
8287 return getIntegerRank(T: OBT->getUnderlyingType().getTypePtr());
8288
8289 switch (cast<BuiltinType>(Val: T)->getKind()) {
8290 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8291 case BuiltinType::Bool:
8292 return 1 + (getIntWidth(T: BoolTy) << 3);
8293 case BuiltinType::Char_S:
8294 case BuiltinType::Char_U:
8295 case BuiltinType::SChar:
8296 case BuiltinType::UChar:
8297 return 2 + (getIntWidth(T: CharTy) << 3);
8298 case BuiltinType::Short:
8299 case BuiltinType::UShort:
8300 return 3 + (getIntWidth(T: ShortTy) << 3);
8301 case BuiltinType::Int:
8302 case BuiltinType::UInt:
8303 return 4 + (getIntWidth(T: IntTy) << 3);
8304 case BuiltinType::Long:
8305 case BuiltinType::ULong:
8306 return 5 + (getIntWidth(T: LongTy) << 3);
8307 case BuiltinType::LongLong:
8308 case BuiltinType::ULongLong:
8309 return 6 + (getIntWidth(T: LongLongTy) << 3);
8310 case BuiltinType::Int128:
8311 case BuiltinType::UInt128:
8312 return 7 + (getIntWidth(T: Int128Ty) << 3);
8313
8314 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8315 // their underlying types" [c++20 conv.rank]
8316 case BuiltinType::Char8:
8317 return getIntegerRank(T: UnsignedCharTy.getTypePtr());
8318 case BuiltinType::Char16:
8319 return getIntegerRank(
8320 T: getFromTargetType(Type: Target->getChar16Type()).getTypePtr());
8321 case BuiltinType::Char32:
8322 return getIntegerRank(
8323 T: getFromTargetType(Type: Target->getChar32Type()).getTypePtr());
8324 case BuiltinType::WChar_S:
8325 case BuiltinType::WChar_U:
8326 return getIntegerRank(
8327 T: getFromTargetType(Type: Target->getWCharType()).getTypePtr());
8328 }
8329}
8330
8331/// Whether this is a promotable bitfield reference according
8332/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8333///
8334/// \returns the type this bit-field will promote to, or NULL if no
8335/// promotion occurs.
8336QualType ASTContext::isPromotableBitField(Expr *E) const {
8337 if (E->isTypeDependent() || E->isValueDependent())
8338 return {};
8339
8340 // C++ [conv.prom]p5:
8341 // If the bit-field has an enumerated type, it is treated as any other
8342 // value of that type for promotion purposes.
8343 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
8344 return {};
8345
8346 // FIXME: We should not do this unless E->refersToBitField() is true. This
8347 // matters in C where getSourceBitField() will find bit-fields for various
8348 // cases where the source expression is not a bit-field designator.
8349
8350 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8351 if (!Field)
8352 return {};
8353
8354 QualType FT = Field->getType();
8355
8356 uint64_t BitWidth = Field->getBitWidthValue();
8357 uint64_t IntSize = getTypeSize(T: IntTy);
8358 // C++ [conv.prom]p5:
8359 // A prvalue for an integral bit-field can be converted to a prvalue of type
8360 // int if int can represent all the values of the bit-field; otherwise, it
8361 // can be converted to unsigned int if unsigned int can represent all the
8362 // values of the bit-field. If the bit-field is larger yet, no integral
8363 // promotion applies to it.
8364 // C11 6.3.1.1/2:
8365 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8366 // If an int can represent all values of the original type (as restricted by
8367 // the width, for a bit-field), the value is converted to an int; otherwise,
8368 // it is converted to an unsigned int.
8369 //
8370 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8371 // We perform that promotion here to match GCC and C++.
8372 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8373 // greater than that of 'int'. We perform that promotion to match GCC.
8374 //
8375 // C23 6.3.1.1p2:
8376 // The value from a bit-field of a bit-precise integer type is converted to
8377 // the corresponding bit-precise integer type. (The rest is the same as in
8378 // C11.)
8379 if (QualType QT = Field->getType(); QT->isBitIntType())
8380 return QT;
8381
8382 if (BitWidth < IntSize)
8383 return IntTy;
8384
8385 if (BitWidth == IntSize)
8386 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8387
8388 // Bit-fields wider than int are not subject to promotions, and therefore act
8389 // like the base type. GCC has some weird bugs in this area that we
8390 // deliberately do not follow (GCC follows a pre-standard resolution to
8391 // C's DR315 which treats bit-width as being part of the type, and this leaks
8392 // into their semantics in some cases).
8393 return {};
8394}
8395
8396/// getPromotedIntegerType - Returns the type that Promotable will
8397/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8398/// integer type.
8399QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
8400 assert(!Promotable.isNull());
8401 assert(isPromotableIntegerType(Promotable));
8402 if (const auto *ED = Promotable->getAsEnumDecl())
8403 return ED->getPromotionType();
8404
8405 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8406 // qualifier.
8407 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8408 QualType PromotedUnderlying =
8409 getPromotedIntegerType(Promotable: OBT->getUnderlyingType());
8410 return getOverflowBehaviorType(Kind: OBT->getBehaviorKind(), Underlying: PromotedUnderlying);
8411 }
8412
8413 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8414 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8415 // (3.9.1) can be converted to a prvalue of the first of the following
8416 // types that can represent all the values of its underlying type:
8417 // int, unsigned int, long int, unsigned long int, long long int, or
8418 // unsigned long long int [...]
8419 // FIXME: Is there some better way to compute this?
8420 if (BT->getKind() == BuiltinType::WChar_S ||
8421 BT->getKind() == BuiltinType::WChar_U ||
8422 BT->getKind() == BuiltinType::Char8 ||
8423 BT->getKind() == BuiltinType::Char16 ||
8424 BT->getKind() == BuiltinType::Char32) {
8425 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8426 uint64_t FromSize = getTypeSize(T: BT);
8427 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8428 LongLongTy, UnsignedLongLongTy };
8429 for (const auto &PT : PromoteTypes) {
8430 uint64_t ToSize = getTypeSize(T: PT);
8431 if (FromSize < ToSize ||
8432 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8433 return PT;
8434 }
8435 llvm_unreachable("char type should fit into long long");
8436 }
8437 }
8438
8439 // At this point, we should have a signed or unsigned integer type.
8440 if (Promotable->isSignedIntegerType())
8441 return IntTy;
8442 uint64_t PromotableSize = getIntWidth(T: Promotable);
8443 uint64_t IntSize = getIntWidth(T: IntTy);
8444 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8445 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8446}
8447
8448/// Recurses in pointer/array types until it finds an objc retainable
8449/// type and returns its ownership.
8450Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
8451 while (!T.isNull()) {
8452 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8453 return T.getObjCLifetime();
8454 if (T->isArrayType())
8455 T = getBaseElementType(type: T);
8456 else if (const auto *PT = T->getAs<PointerType>())
8457 T = PT->getPointeeType();
8458 else if (const auto *RT = T->getAs<ReferenceType>())
8459 T = RT->getPointeeType();
8460 else
8461 break;
8462 }
8463
8464 return Qualifiers::OCL_None;
8465}
8466
8467static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8468 // Incomplete enum types are not treated as integer types.
8469 // FIXME: In C++, enum types are never integer types.
8470 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8471 if (ED->isComplete() && !ED->isScoped())
8472 return ED->getIntegerType().getTypePtr();
8473 return nullptr;
8474}
8475
8476/// getIntegerTypeOrder - Returns the highest ranked integer type:
8477/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8478/// LHS < RHS, return -1.
8479int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
8480 const Type *LHSC = getCanonicalType(T: LHS).getTypePtr();
8481 const Type *RHSC = getCanonicalType(T: RHS).getTypePtr();
8482
8483 // Unwrap enums to their underlying type.
8484 if (const auto *ET = dyn_cast<EnumType>(Val: LHSC))
8485 LHSC = getIntegerTypeForEnum(ET);
8486 if (const auto *ET = dyn_cast<EnumType>(Val: RHSC))
8487 RHSC = getIntegerTypeForEnum(ET);
8488
8489 if (LHSC == RHSC) return 0;
8490
8491 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8492 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8493
8494 unsigned LHSRank = getIntegerRank(T: LHSC);
8495 unsigned RHSRank = getIntegerRank(T: RHSC);
8496
8497 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8498 if (LHSRank == RHSRank) return 0;
8499 return LHSRank > RHSRank ? 1 : -1;
8500 }
8501
8502 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8503 if (LHSUnsigned) {
8504 // If the unsigned [LHS] type is larger, return it.
8505 if (LHSRank >= RHSRank)
8506 return 1;
8507
8508 // If the signed type can represent all values of the unsigned type, it
8509 // wins. Because we are dealing with 2's complement and types that are
8510 // powers of two larger than each other, this is always safe.
8511 return -1;
8512 }
8513
8514 // If the unsigned [RHS] type is larger, return it.
8515 if (RHSRank >= LHSRank)
8516 return -1;
8517
8518 // If the signed type can represent all values of the unsigned type, it
8519 // wins. Because we are dealing with 2's complement and types that are
8520 // powers of two larger than each other, this is always safe.
8521 return 1;
8522}
8523
8524TypedefDecl *ASTContext::getCFConstantStringDecl() const {
8525 if (CFConstantStringTypeDecl)
8526 return CFConstantStringTypeDecl;
8527
8528 assert(!CFConstantStringTagDecl &&
8529 "tag and typedef should be initialized together");
8530 CFConstantStringTagDecl = buildImplicitRecord(Name: "__NSConstantString_tag");
8531 CFConstantStringTagDecl->startDefinition();
8532
8533 struct {
8534 QualType Type;
8535 const char *Name;
8536 } Fields[5];
8537 unsigned Count = 0;
8538
8539 /// Objective-C ABI
8540 ///
8541 /// typedef struct __NSConstantString_tag {
8542 /// const int *isa;
8543 /// int flags;
8544 /// const char *str;
8545 /// long length;
8546 /// } __NSConstantString;
8547 ///
8548 /// Swift ABI (4.1, 4.2)
8549 ///
8550 /// typedef struct __NSConstantString_tag {
8551 /// uintptr_t _cfisa;
8552 /// uintptr_t _swift_rc;
8553 /// _Atomic(uint64_t) _cfinfoa;
8554 /// const char *_ptr;
8555 /// uint32_t _length;
8556 /// } __NSConstantString;
8557 ///
8558 /// Swift ABI (5.0)
8559 ///
8560 /// typedef struct __NSConstantString_tag {
8561 /// uintptr_t _cfisa;
8562 /// uintptr_t _swift_rc;
8563 /// _Atomic(uint64_t) _cfinfoa;
8564 /// const char *_ptr;
8565 /// uintptr_t _length;
8566 /// } __NSConstantString;
8567
8568 const auto CFRuntime = getLangOpts().CFRuntime;
8569 if (static_cast<unsigned>(CFRuntime) <
8570 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8571 Fields[Count++] = { .Type: getPointerType(T: IntTy.withConst()), .Name: "isa" };
8572 Fields[Count++] = { .Type: IntTy, .Name: "flags" };
8573 Fields[Count++] = { .Type: getPointerType(T: CharTy.withConst()), .Name: "str" };
8574 Fields[Count++] = { .Type: LongTy, .Name: "length" };
8575 } else {
8576 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_cfisa" };
8577 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_swift_rc" };
8578 Fields[Count++] = { .Type: getFromTargetType(Type: Target->getUInt64Type()), .Name: "_swift_rc" };
8579 Fields[Count++] = { .Type: getPointerType(T: CharTy.withConst()), .Name: "_ptr" };
8580 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
8581 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
8582 Fields[Count++] = { .Type: IntTy, .Name: "_ptr" };
8583 else
8584 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_ptr" };
8585 }
8586
8587 // Create fields
8588 for (unsigned i = 0; i < Count; ++i) {
8589 FieldDecl *Field =
8590 FieldDecl::Create(C: *this, DC: CFConstantStringTagDecl, StartLoc: SourceLocation(),
8591 IdLoc: SourceLocation(), Id: &Idents.get(Name: Fields[i].Name),
8592 T: Fields[i].Type, /*TInfo=*/nullptr,
8593 /*BitWidth=*/BW: nullptr, /*Mutable=*/false, InitStyle: ICIS_NoInit);
8594 Field->setAccess(AS_public);
8595 CFConstantStringTagDecl->addDecl(D: Field);
8596 }
8597
8598 CFConstantStringTagDecl->completeDefinition();
8599 // This type is designed to be compatible with NSConstantString, but cannot
8600 // use the same name, since NSConstantString is an interface.
8601 CanQualType tagType = getCanonicalTagType(TD: CFConstantStringTagDecl);
8602 CFConstantStringTypeDecl =
8603 buildImplicitTypedef(T: tagType, Name: "__NSConstantString");
8604
8605 return CFConstantStringTypeDecl;
8606}
8607
8608RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
8609 if (!CFConstantStringTagDecl)
8610 getCFConstantStringDecl(); // Build the tag and the typedef.
8611 return CFConstantStringTagDecl;
8612}
8613
8614// getCFConstantStringType - Return the type used for constant CFStrings.
8615QualType ASTContext::getCFConstantStringType() const {
8616 return getTypedefType(Keyword: ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt,
8617 Decl: getCFConstantStringDecl());
8618}
8619
8620QualType ASTContext::getObjCSuperType() const {
8621 if (ObjCSuperType.isNull()) {
8622 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord(Name: "objc_super");
8623 getTranslationUnitDecl()->addDecl(D: ObjCSuperTypeDecl);
8624 ObjCSuperType = getCanonicalTagType(TD: ObjCSuperTypeDecl);
8625 }
8626 return ObjCSuperType;
8627}
8628
8629void ASTContext::setCFConstantStringType(QualType T) {
8630 const auto *TT = T->castAs<TypedefType>();
8631 CFConstantStringTypeDecl = cast<TypedefDecl>(Val: TT->getDecl());
8632 CFConstantStringTagDecl = TT->castAsRecordDecl();
8633}
8634
8635QualType ASTContext::getBlockDescriptorType() const {
8636 if (BlockDescriptorType)
8637 return getCanonicalTagType(TD: BlockDescriptorType);
8638
8639 RecordDecl *RD;
8640 // FIXME: Needs the FlagAppleBlock bit.
8641 RD = buildImplicitRecord(Name: "__block_descriptor");
8642 RD->startDefinition();
8643
8644 QualType FieldTypes[] = {
8645 UnsignedLongTy,
8646 UnsignedLongTy,
8647 };
8648
8649 static const char *const FieldNames[] = {
8650 "reserved",
8651 "Size"
8652 };
8653
8654 for (size_t i = 0; i < 2; ++i) {
8655 FieldDecl *Field = FieldDecl::Create(
8656 C: *this, DC: RD, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
8657 Id: &Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
8658 /*BitWidth=*/BW: nullptr, /*Mutable=*/false, InitStyle: ICIS_NoInit);
8659 Field->setAccess(AS_public);
8660 RD->addDecl(D: Field);
8661 }
8662
8663 RD->completeDefinition();
8664
8665 BlockDescriptorType = RD;
8666
8667 return getCanonicalTagType(TD: BlockDescriptorType);
8668}
8669
8670QualType ASTContext::getBlockDescriptorExtendedType() const {
8671 if (BlockDescriptorExtendedType)
8672 return getCanonicalTagType(TD: BlockDescriptorExtendedType);
8673
8674 RecordDecl *RD;
8675 // FIXME: Needs the FlagAppleBlock bit.
8676 RD = buildImplicitRecord(Name: "__block_descriptor_withcopydispose");
8677 RD->startDefinition();
8678
8679 QualType FieldTypes[] = {
8680 UnsignedLongTy,
8681 UnsignedLongTy,
8682 getPointerType(T: VoidPtrTy),
8683 getPointerType(T: VoidPtrTy)
8684 };
8685
8686 static const char *const FieldNames[] = {
8687 "reserved",
8688 "Size",
8689 "CopyFuncPtr",
8690 "DestroyFuncPtr"
8691 };
8692
8693 for (size_t i = 0; i < 4; ++i) {
8694 FieldDecl *Field = FieldDecl::Create(
8695 C: *this, DC: RD, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
8696 Id: &Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
8697 /*BitWidth=*/BW: nullptr,
8698 /*Mutable=*/false, InitStyle: ICIS_NoInit);
8699 Field->setAccess(AS_public);
8700 RD->addDecl(D: Field);
8701 }
8702
8703 RD->completeDefinition();
8704
8705 BlockDescriptorExtendedType = RD;
8706 return getCanonicalTagType(TD: BlockDescriptorExtendedType);
8707}
8708
8709OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
8710 const auto *BT = dyn_cast<BuiltinType>(Val: T);
8711
8712 if (!BT) {
8713 if (isa<PipeType>(Val: T))
8714 return OCLTK_Pipe;
8715
8716 return OCLTK_Default;
8717 }
8718
8719 switch (BT->getKind()) {
8720#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8721 case BuiltinType::Id: \
8722 return OCLTK_Image;
8723#include "clang/Basic/OpenCLImageTypes.def"
8724
8725 case BuiltinType::OCLClkEvent:
8726 return OCLTK_ClkEvent;
8727
8728 case BuiltinType::OCLEvent:
8729 return OCLTK_Event;
8730
8731 case BuiltinType::OCLQueue:
8732 return OCLTK_Queue;
8733
8734 case BuiltinType::OCLReserveID:
8735 return OCLTK_ReserveID;
8736
8737 case BuiltinType::OCLSampler:
8738 return OCLTK_Sampler;
8739
8740 default:
8741 return OCLTK_Default;
8742 }
8743}
8744
8745LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
8746 return Target->getOpenCLTypeAddrSpace(TK: getOpenCLTypeKind(T));
8747}
8748
8749/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8750/// requires copy/dispose. Note that this must match the logic
8751/// in buildByrefHelpers.
8752bool ASTContext::BlockRequiresCopying(QualType Ty,
8753 const VarDecl *D) {
8754 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8755 const Expr *copyExpr = getBlockVarCopyInit(VD: D).getCopyExpr();
8756 if (!copyExpr && record->hasTrivialDestructor()) return false;
8757
8758 return true;
8759 }
8760
8761 if (Ty.hasAddressDiscriminatedPointerAuth())
8762 return true;
8763
8764 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8765 // move or destroy.
8766 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
8767 return true;
8768
8769 if (!Ty->isObjCRetainableType()) return false;
8770
8771 Qualifiers qs = Ty.getQualifiers();
8772
8773 // If we have lifetime, that dominates.
8774 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8775 switch (lifetime) {
8776 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8777
8778 // These are just bits as far as the runtime is concerned.
8779 case Qualifiers::OCL_ExplicitNone:
8780 case Qualifiers::OCL_Autoreleasing:
8781 return false;
8782
8783 // These cases should have been taken care of when checking the type's
8784 // non-triviality.
8785 case Qualifiers::OCL_Weak:
8786 case Qualifiers::OCL_Strong:
8787 llvm_unreachable("impossible");
8788 }
8789 llvm_unreachable("fell out of lifetime switch!");
8790 }
8791 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8792 Ty->isObjCObjectPointerType());
8793}
8794
8795bool ASTContext::getByrefLifetime(QualType Ty,
8796 Qualifiers::ObjCLifetime &LifeTime,
8797 bool &HasByrefExtendedLayout) const {
8798 if (!getLangOpts().ObjC ||
8799 getLangOpts().getGC() != LangOptions::NonGC)
8800 return false;
8801
8802 HasByrefExtendedLayout = false;
8803 if (Ty->isRecordType()) {
8804 HasByrefExtendedLayout = true;
8805 LifeTime = Qualifiers::OCL_None;
8806 } else if ((LifeTime = Ty.getObjCLifetime())) {
8807 // Honor the ARC qualifiers.
8808 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8809 // The MRR rule.
8810 LifeTime = Qualifiers::OCL_ExplicitNone;
8811 } else {
8812 LifeTime = Qualifiers::OCL_None;
8813 }
8814 return true;
8815}
8816
8817CanQualType ASTContext::getNSUIntegerType() const {
8818 assert(Target && "Expected target to be initialized");
8819 const llvm::Triple &T = Target->getTriple();
8820 // Windows is LLP64 rather than LP64
8821 if (T.isOSWindows() && T.isArch64Bit())
8822 return UnsignedLongLongTy;
8823 return UnsignedLongTy;
8824}
8825
8826CanQualType ASTContext::getNSIntegerType() const {
8827 assert(Target && "Expected target to be initialized");
8828 const llvm::Triple &T = Target->getTriple();
8829 // Windows is LLP64 rather than LP64
8830 if (T.isOSWindows() && T.isArch64Bit())
8831 return LongLongTy;
8832 return LongTy;
8833}
8834
8835TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
8836 if (!ObjCInstanceTypeDecl)
8837 ObjCInstanceTypeDecl =
8838 buildImplicitTypedef(T: getObjCIdType(), Name: "instancetype");
8839 return ObjCInstanceTypeDecl;
8840}
8841
8842// This returns true if a type has been typedefed to BOOL:
8843// typedef <type> BOOL;
8844static bool isTypeTypedefedAsBOOL(QualType T) {
8845 if (const auto *TT = dyn_cast<TypedefType>(Val&: T))
8846 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8847 return II->isStr(Str: "BOOL");
8848
8849 return false;
8850}
8851
8852/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8853/// purpose.
8854CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
8855 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8856 return CharUnits::Zero();
8857
8858 CharUnits sz = getTypeSizeInChars(T: type);
8859
8860 // Make all integer and enum types at least as large as an int
8861 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8862 sz = std::max(a: sz, b: getTypeSizeInChars(T: IntTy));
8863 // Treat arrays as pointers, since that's how they're passed in.
8864 else if (type->isArrayType())
8865 sz = getTypeSizeInChars(T: VoidPtrTy);
8866 return sz;
8867}
8868
8869bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
8870 return getTargetInfo().getCXXABI().isMicrosoft() &&
8871 VD->isStaticDataMember() &&
8872 VD->getType()->isIntegralOrEnumerationType() &&
8873 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
8874}
8875
8876ASTContext::InlineVariableDefinitionKind
8877ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
8878 if (!VD->isInline())
8879 return InlineVariableDefinitionKind::None;
8880
8881 // In almost all cases, it's a weak definition.
8882 auto *First = VD->getFirstDecl();
8883 if (First->isInlineSpecified() || !First->isStaticDataMember())
8884 return InlineVariableDefinitionKind::Weak;
8885
8886 // If there's a file-context declaration in this translation unit, it's a
8887 // non-discardable definition.
8888 for (auto *D : VD->redecls())
8889 if (D->getLexicalDeclContext()->isFileContext() &&
8890 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8891 return InlineVariableDefinitionKind::Strong;
8892
8893 // If we've not seen one yet, we don't know.
8894 return InlineVariableDefinitionKind::WeakUnknown;
8895}
8896
8897static std::string charUnitsToString(const CharUnits &CU) {
8898 return llvm::itostr(X: CU.getQuantity());
8899}
8900
8901/// getObjCEncodingForBlock - Return the encoded type for this block
8902/// declaration.
8903std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
8904 std::string S;
8905
8906 const BlockDecl *Decl = Expr->getBlockDecl();
8907 QualType BlockTy =
8908 Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
8909 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8910 // Encode result type.
8911 if (getLangOpts().EncodeExtendedBlockSig)
8912 getObjCEncodingForMethodParameter(QT: Decl::OBJC_TQ_None, T: BlockReturnTy, S,
8913 Extended: true /*Extended*/);
8914 else
8915 getObjCEncodingForType(T: BlockReturnTy, S);
8916 // Compute size of all parameters.
8917 // Start with computing size of a pointer in number of bytes.
8918 // FIXME: There might(should) be a better way of doing this computation!
8919 CharUnits PtrSize = getTypeSizeInChars(T: VoidPtrTy);
8920 CharUnits ParmOffset = PtrSize;
8921 for (auto *PI : Decl->parameters()) {
8922 QualType PType = PI->getType();
8923 CharUnits sz = getObjCEncodingTypeSize(type: PType);
8924 if (sz.isZero())
8925 continue;
8926 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8927 ParmOffset += sz;
8928 }
8929 // Size of the argument frame
8930 S += charUnitsToString(CU: ParmOffset);
8931 // Block pointer and offset.
8932 S += "@?0";
8933
8934 // Argument types.
8935 ParmOffset = PtrSize;
8936 for (auto *PVDecl : Decl->parameters()) {
8937 QualType PType = PVDecl->getOriginalType();
8938 if (const auto *AT =
8939 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
8940 // Use array's original type only if it has known number of
8941 // elements.
8942 if (!isa<ConstantArrayType>(Val: AT))
8943 PType = PVDecl->getType();
8944 } else if (PType->isFunctionType())
8945 PType = PVDecl->getType();
8946 if (getLangOpts().EncodeExtendedBlockSig)
8947 getObjCEncodingForMethodParameter(QT: Decl::OBJC_TQ_None, T: PType,
8948 S, Extended: true /*Extended*/);
8949 else
8950 getObjCEncodingForType(T: PType, S);
8951 S += charUnitsToString(CU: ParmOffset);
8952 ParmOffset += getObjCEncodingTypeSize(type: PType);
8953 }
8954
8955 return S;
8956}
8957
8958std::string
8959ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
8960 std::string S;
8961 // Encode result type.
8962 getObjCEncodingForType(T: Decl->getReturnType(), S);
8963 CharUnits ParmOffset;
8964 // Compute size of all parameters.
8965 for (auto *PI : Decl->parameters()) {
8966 QualType PType = PI->getType();
8967 CharUnits sz = getObjCEncodingTypeSize(type: PType);
8968 if (sz.isZero())
8969 continue;
8970
8971 assert(sz.isPositive() &&
8972 "getObjCEncodingForFunctionDecl - Incomplete param type");
8973 ParmOffset += sz;
8974 }
8975 S += charUnitsToString(CU: ParmOffset);
8976 ParmOffset = CharUnits::Zero();
8977
8978 // Argument types.
8979 for (auto *PVDecl : Decl->parameters()) {
8980 QualType PType = PVDecl->getOriginalType();
8981 if (const auto *AT =
8982 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
8983 // Use array's original type only if it has known number of
8984 // elements.
8985 if (!isa<ConstantArrayType>(Val: AT))
8986 PType = PVDecl->getType();
8987 } else if (PType->isFunctionType())
8988 PType = PVDecl->getType();
8989 getObjCEncodingForType(T: PType, S);
8990 S += charUnitsToString(CU: ParmOffset);
8991 ParmOffset += getObjCEncodingTypeSize(type: PType);
8992 }
8993
8994 return S;
8995}
8996
8997/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8998/// method parameter or return type. If Extended, include class names and
8999/// block object types.
9000void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
9001 QualType T, std::string& S,
9002 bool Extended) const {
9003 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
9004 getObjCEncodingForTypeQualifier(QT, S);
9005 // Encode parameter type.
9006 ObjCEncOptions Options = ObjCEncOptions()
9007 .setExpandPointedToStructures()
9008 .setExpandStructures()
9009 .setIsOutermostType();
9010 if (Extended)
9011 Options.setEncodeBlockParameters().setEncodeClassNames();
9012 getObjCEncodingForTypeImpl(t: T, S, Options, /*Field=*/nullptr);
9013}
9014
9015/// getObjCEncodingForMethodDecl - Return the encoded type for this method
9016/// declaration.
9017std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
9018 bool Extended) const {
9019 // FIXME: This is not very efficient.
9020 // Encode return type.
9021 std::string S;
9022 getObjCEncodingForMethodParameter(QT: Decl->getObjCDeclQualifier(),
9023 T: Decl->getReturnType(), S, Extended);
9024 // Compute size of all parameters.
9025 // Start with computing size of a pointer in number of bytes.
9026 // FIXME: There might(should) be a better way of doing this computation!
9027 CharUnits PtrSize = getTypeSizeInChars(T: VoidPtrTy);
9028 // The first two arguments (self and _cmd) are pointers; account for
9029 // their size.
9030 CharUnits ParmOffset = 2 * PtrSize;
9031 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9032 E = Decl->sel_param_end(); PI != E; ++PI) {
9033 QualType PType = (*PI)->getType();
9034 CharUnits sz = getObjCEncodingTypeSize(type: PType);
9035 if (sz.isZero())
9036 continue;
9037
9038 assert(sz.isPositive() &&
9039 "getObjCEncodingForMethodDecl - Incomplete param type");
9040 ParmOffset += sz;
9041 }
9042 S += charUnitsToString(CU: ParmOffset);
9043 S += "@0:";
9044 S += charUnitsToString(CU: PtrSize);
9045
9046 // Argument types.
9047 ParmOffset = 2 * PtrSize;
9048 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9049 E = Decl->sel_param_end(); PI != E; ++PI) {
9050 const ParmVarDecl *PVDecl = *PI;
9051 QualType PType = PVDecl->getOriginalType();
9052 if (const auto *AT =
9053 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
9054 // Use array's original type only if it has known number of
9055 // elements.
9056 if (!isa<ConstantArrayType>(Val: AT))
9057 PType = PVDecl->getType();
9058 } else if (PType->isFunctionType())
9059 PType = PVDecl->getType();
9060 getObjCEncodingForMethodParameter(QT: PVDecl->getObjCDeclQualifier(),
9061 T: PType, S, Extended);
9062 S += charUnitsToString(CU: ParmOffset);
9063 ParmOffset += getObjCEncodingTypeSize(type: PType);
9064 }
9065
9066 return S;
9067}
9068
9069ObjCPropertyImplDecl *
9070ASTContext::getObjCPropertyImplDeclForPropertyDecl(
9071 const ObjCPropertyDecl *PD,
9072 const Decl *Container) const {
9073 if (!Container)
9074 return nullptr;
9075 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Val: Container)) {
9076 for (auto *PID : CID->property_impls())
9077 if (PID->getPropertyDecl() == PD)
9078 return PID;
9079 } else {
9080 const auto *OID = cast<ObjCImplementationDecl>(Val: Container);
9081 for (auto *PID : OID->property_impls())
9082 if (PID->getPropertyDecl() == PD)
9083 return PID;
9084 }
9085 return nullptr;
9086}
9087
9088/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9089/// property declaration. If non-NULL, Container must be either an
9090/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9091/// NULL when getting encodings for protocol properties.
9092/// Property attributes are stored as a comma-delimited C string. The simple
9093/// attributes readonly and bycopy are encoded as single characters. The
9094/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9095/// encoded as single characters, followed by an identifier. Property types
9096/// are also encoded as a parametrized attribute. The characters used to encode
9097/// these attributes are defined by the following enumeration:
9098/// @code
9099/// enum PropertyAttributes {
9100/// kPropertyReadOnly = 'R', // property is read-only.
9101/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9102/// kPropertyByref = '&', // property is a reference to the value last assigned
9103/// kPropertyDynamic = 'D', // property is dynamic
9104/// kPropertyGetter = 'G', // followed by getter selector name
9105/// kPropertySetter = 'S', // followed by setter selector name
9106/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9107/// kPropertyType = 'T' // followed by old-style type encoding.
9108/// kPropertyWeak = 'W' // 'weak' property
9109/// kPropertyStrong = 'P' // property GC'able
9110/// kPropertyNonAtomic = 'N' // property non-atomic
9111/// kPropertyOptional = '?' // property optional
9112/// };
9113/// @endcode
9114std::string
9115ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
9116 const Decl *Container) const {
9117 // Collect information from the property implementation decl(s).
9118 bool Dynamic = false;
9119 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9120
9121 if (ObjCPropertyImplDecl *PropertyImpDecl =
9122 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
9123 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9124 Dynamic = true;
9125 else
9126 SynthesizePID = PropertyImpDecl;
9127 }
9128
9129 // FIXME: This is not very efficient.
9130 std::string S = "T";
9131
9132 // Encode result type.
9133 // GCC has some special rules regarding encoding of properties which
9134 // closely resembles encoding of ivars.
9135 getObjCEncodingForPropertyType(T: PD->getType(), S);
9136
9137 if (PD->isOptional())
9138 S += ",?";
9139
9140 if (PD->isReadOnly()) {
9141 S += ",R";
9142 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
9143 S += ",C";
9144 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
9145 S += ",&";
9146 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
9147 S += ",W";
9148 } else {
9149 switch (PD->getSetterKind()) {
9150 case ObjCPropertyDecl::Assign: break;
9151 case ObjCPropertyDecl::Copy: S += ",C"; break;
9152 case ObjCPropertyDecl::Retain: S += ",&"; break;
9153 case ObjCPropertyDecl::Weak: S += ",W"; break;
9154 }
9155 }
9156
9157 // It really isn't clear at all what this means, since properties
9158 // are "dynamic by default".
9159 if (Dynamic)
9160 S += ",D";
9161
9162 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
9163 S += ",N";
9164
9165 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
9166 S += ",G";
9167 S += PD->getGetterName().getAsString();
9168 }
9169
9170 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
9171 S += ",S";
9172 S += PD->getSetterName().getAsString();
9173 }
9174
9175 if (SynthesizePID) {
9176 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9177 S += ",V";
9178 S += OID->getNameAsString();
9179 }
9180
9181 // FIXME: OBJCGC: weak & strong
9182 return S;
9183}
9184
9185/// getLegacyIntegralTypeEncoding -
9186/// Another legacy compatibility encoding: 32-bit longs are encoded as
9187/// 'l' or 'L' , but not always. For typedefs, we need to use
9188/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9189void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
9190 if (PointeeTy->getAs<TypedefType>()) {
9191 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9192 if (BT->getKind() == BuiltinType::ULong && getIntWidth(T: PointeeTy) == 32)
9193 PointeeTy = UnsignedIntTy;
9194 else
9195 if (BT->getKind() == BuiltinType::Long && getIntWidth(T: PointeeTy) == 32)
9196 PointeeTy = IntTy;
9197 }
9198 }
9199}
9200
9201void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
9202 const FieldDecl *Field,
9203 QualType *NotEncodedT) const {
9204 // We follow the behavior of gcc, expanding structures which are
9205 // directly pointed to, and expanding embedded structures. Note that
9206 // these rules are sufficient to prevent recursive encoding of the
9207 // same type.
9208 getObjCEncodingForTypeImpl(t: T, S,
9209 Options: ObjCEncOptions()
9210 .setExpandPointedToStructures()
9211 .setExpandStructures()
9212 .setIsOutermostType(),
9213 Field, NotEncodedT);
9214}
9215
9216void ASTContext::getObjCEncodingForPropertyType(QualType T,
9217 std::string& S) const {
9218 // Encode result type.
9219 // GCC has some special rules regarding encoding of properties which
9220 // closely resembles encoding of ivars.
9221 getObjCEncodingForTypeImpl(t: T, S,
9222 Options: ObjCEncOptions()
9223 .setExpandPointedToStructures()
9224 .setExpandStructures()
9225 .setIsOutermostType()
9226 .setEncodingProperty(),
9227 /*Field=*/nullptr);
9228}
9229
9230static char getObjCEncodingForPrimitiveType(const ASTContext *C,
9231 const BuiltinType *BT) {
9232 BuiltinType::Kind kind = BT->getKind();
9233 switch (kind) {
9234 case BuiltinType::Void: return 'v';
9235 case BuiltinType::Bool: return 'B';
9236 case BuiltinType::Char8:
9237 case BuiltinType::Char_U:
9238 case BuiltinType::UChar: return 'C';
9239 case BuiltinType::Char16:
9240 case BuiltinType::UShort: return 'S';
9241 case BuiltinType::Char32:
9242 case BuiltinType::UInt: return 'I';
9243 case BuiltinType::ULong:
9244 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9245 case BuiltinType::UInt128: return 'T';
9246 case BuiltinType::ULongLong: return 'Q';
9247 case BuiltinType::Char_S:
9248 case BuiltinType::SChar: return 'c';
9249 case BuiltinType::Short: return 's';
9250 case BuiltinType::WChar_S:
9251 case BuiltinType::WChar_U:
9252 case BuiltinType::Int: return 'i';
9253 case BuiltinType::Long:
9254 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9255 case BuiltinType::LongLong: return 'q';
9256 case BuiltinType::Int128: return 't';
9257 case BuiltinType::Float: return 'f';
9258 case BuiltinType::Double: return 'd';
9259 case BuiltinType::LongDouble: return 'D';
9260 case BuiltinType::NullPtr: return '*'; // like char*
9261
9262 case BuiltinType::BFloat16:
9263 case BuiltinType::Float16:
9264 case BuiltinType::Float128:
9265 case BuiltinType::Ibm128:
9266 case BuiltinType::Half:
9267 case BuiltinType::ShortAccum:
9268 case BuiltinType::Accum:
9269 case BuiltinType::LongAccum:
9270 case BuiltinType::UShortAccum:
9271 case BuiltinType::UAccum:
9272 case BuiltinType::ULongAccum:
9273 case BuiltinType::ShortFract:
9274 case BuiltinType::Fract:
9275 case BuiltinType::LongFract:
9276 case BuiltinType::UShortFract:
9277 case BuiltinType::UFract:
9278 case BuiltinType::ULongFract:
9279 case BuiltinType::SatShortAccum:
9280 case BuiltinType::SatAccum:
9281 case BuiltinType::SatLongAccum:
9282 case BuiltinType::SatUShortAccum:
9283 case BuiltinType::SatUAccum:
9284 case BuiltinType::SatULongAccum:
9285 case BuiltinType::SatShortFract:
9286 case BuiltinType::SatFract:
9287 case BuiltinType::SatLongFract:
9288 case BuiltinType::SatUShortFract:
9289 case BuiltinType::SatUFract:
9290 case BuiltinType::SatULongFract:
9291 // FIXME: potentially need @encodes for these!
9292 return ' ';
9293
9294#define SVE_TYPE(Name, Id, SingletonId) \
9295 case BuiltinType::Id:
9296#include "clang/Basic/AArch64ACLETypes.def"
9297#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9298#include "clang/Basic/RISCVVTypes.def"
9299#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9300#include "clang/Basic/WebAssemblyReferenceTypes.def"
9301#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9302#include "clang/Basic/AMDGPUTypes.def"
9303 {
9304 DiagnosticsEngine &Diags = C->getDiagnostics();
9305 Diags.Report(DiagID: diag::err_unsupported_objc_primitive_encoding)
9306 << QualType(BT, 0);
9307 return ' ';
9308 }
9309
9310 case BuiltinType::ObjCId:
9311 case BuiltinType::ObjCClass:
9312 case BuiltinType::ObjCSel:
9313 llvm_unreachable("@encoding ObjC primitive type");
9314
9315 // OpenCL and placeholder types don't need @encodings.
9316#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9317 case BuiltinType::Id:
9318#include "clang/Basic/OpenCLImageTypes.def"
9319#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9320 case BuiltinType::Id:
9321#include "clang/Basic/OpenCLExtensionTypes.def"
9322 case BuiltinType::OCLEvent:
9323 case BuiltinType::OCLClkEvent:
9324 case BuiltinType::OCLQueue:
9325 case BuiltinType::OCLReserveID:
9326 case BuiltinType::OCLSampler:
9327 case BuiltinType::Dependent:
9328#define PPC_VECTOR_TYPE(Name, Id, Size) \
9329 case BuiltinType::Id:
9330#include "clang/Basic/PPCTypes.def"
9331#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9332#include "clang/Basic/HLSLIntangibleTypes.def"
9333#define BUILTIN_TYPE(KIND, ID)
9334#define PLACEHOLDER_TYPE(KIND, ID) \
9335 case BuiltinType::KIND:
9336#include "clang/AST/BuiltinTypes.def"
9337 llvm_unreachable("invalid builtin type for @encode");
9338 }
9339 llvm_unreachable("invalid BuiltinType::Kind value");
9340}
9341
9342static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9343 EnumDecl *Enum = ED->getDefinitionOrSelf();
9344
9345 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9346 if (!Enum->isFixed())
9347 return 'i';
9348
9349 // The encoding of a fixed enum type matches its fixed underlying type.
9350 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9351 return getObjCEncodingForPrimitiveType(C, BT);
9352}
9353
9354static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9355 QualType T, const FieldDecl *FD) {
9356 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9357 S += 'b';
9358 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9359 // The GNU runtime requires more information; bitfields are encoded as b,
9360 // then the offset (in bits) of the first element, then the type of the
9361 // bitfield, then the size in bits. For example, in this structure:
9362 //
9363 // struct
9364 // {
9365 // int integer;
9366 // int flags:2;
9367 // };
9368 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9369 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9370 // information is not especially sensible, but we're stuck with it for
9371 // compatibility with GCC, although providing it breaks anything that
9372 // actually uses runtime introspection and wants to work on both runtimes...
9373 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9374 uint64_t Offset;
9375
9376 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(Val: FD)) {
9377 Offset = Ctx->lookupFieldBitOffset(OID: IVD->getContainingInterface(), Ivar: IVD);
9378 } else {
9379 const RecordDecl *RD = FD->getParent();
9380 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(D: RD);
9381 Offset = RL.getFieldOffset(FieldNo: FD->getFieldIndex());
9382 }
9383
9384 S += llvm::utostr(X: Offset);
9385
9386 if (const auto *ET = T->getAsCanonical<EnumType>())
9387 S += ObjCEncodingForEnumDecl(C: Ctx, ED: ET->getDecl());
9388 else {
9389 const auto *BT = T->castAs<BuiltinType>();
9390 S += getObjCEncodingForPrimitiveType(C: Ctx, BT);
9391 }
9392 }
9393 S += llvm::utostr(X: FD->getBitWidthValue());
9394}
9395
9396// Helper function for determining whether the encoded type string would include
9397// a template specialization type.
9398static bool hasTemplateSpecializationInEncodedString(const Type *T,
9399 bool VisitBasesAndFields) {
9400 T = T->getBaseElementTypeUnsafe();
9401
9402 if (auto *PT = T->getAs<PointerType>())
9403 return hasTemplateSpecializationInEncodedString(
9404 T: PT->getPointeeType().getTypePtr(), VisitBasesAndFields: false);
9405
9406 auto *CXXRD = T->getAsCXXRecordDecl();
9407
9408 if (!CXXRD)
9409 return false;
9410
9411 if (isa<ClassTemplateSpecializationDecl>(Val: CXXRD))
9412 return true;
9413
9414 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9415 return false;
9416
9417 for (const auto &B : CXXRD->bases())
9418 if (hasTemplateSpecializationInEncodedString(T: B.getType().getTypePtr(),
9419 VisitBasesAndFields: true))
9420 return true;
9421
9422 for (auto *FD : CXXRD->fields())
9423 if (hasTemplateSpecializationInEncodedString(T: FD->getType().getTypePtr(),
9424 VisitBasesAndFields: true))
9425 return true;
9426
9427 return false;
9428}
9429
9430// FIXME: Use SmallString for accumulating string.
9431void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9432 const ObjCEncOptions Options,
9433 const FieldDecl *FD,
9434 QualType *NotEncodedT) const {
9435 CanQualType CT = getCanonicalType(T);
9436 switch (CT->getTypeClass()) {
9437 case Type::Builtin:
9438 case Type::Enum:
9439 if (FD && FD->isBitField())
9440 return EncodeBitField(Ctx: this, S, T, FD);
9441 if (const auto *BT = dyn_cast<BuiltinType>(Val&: CT))
9442 S += getObjCEncodingForPrimitiveType(C: this, BT);
9443 else
9444 S += ObjCEncodingForEnumDecl(C: this, ED: cast<EnumType>(Val&: CT)->getDecl());
9445 return;
9446
9447 case Type::Complex:
9448 S += 'j';
9449 getObjCEncodingForTypeImpl(T: T->castAs<ComplexType>()->getElementType(), S,
9450 Options: ObjCEncOptions(),
9451 /*Field=*/FD: nullptr);
9452 return;
9453
9454 case Type::Atomic:
9455 S += 'A';
9456 getObjCEncodingForTypeImpl(T: T->castAs<AtomicType>()->getValueType(), S,
9457 Options: ObjCEncOptions(),
9458 /*Field=*/FD: nullptr);
9459 return;
9460
9461 // encoding for pointer or reference types.
9462 case Type::Pointer:
9463 case Type::LValueReference:
9464 case Type::RValueReference: {
9465 QualType PointeeTy;
9466 if (isa<PointerType>(Val: CT)) {
9467 const auto *PT = T->castAs<PointerType>();
9468 if (PT->isObjCSelType()) {
9469 S += ':';
9470 return;
9471 }
9472 PointeeTy = PT->getPointeeType();
9473 } else {
9474 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9475 }
9476
9477 bool isReadOnly = false;
9478 // For historical/compatibility reasons, the read-only qualifier of the
9479 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9480 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9481 // Also, do not emit the 'r' for anything but the outermost type!
9482 if (T->getAs<TypedefType>()) {
9483 if (Options.IsOutermostType() && T.isConstQualified()) {
9484 isReadOnly = true;
9485 S += 'r';
9486 }
9487 } else if (Options.IsOutermostType()) {
9488 QualType P = PointeeTy;
9489 while (auto PT = P->getAs<PointerType>())
9490 P = PT->getPointeeType();
9491 if (P.isConstQualified()) {
9492 isReadOnly = true;
9493 S += 'r';
9494 }
9495 }
9496 if (isReadOnly) {
9497 // Another legacy compatibility encoding. Some ObjC qualifier and type
9498 // combinations need to be rearranged.
9499 // Rewrite "in const" from "nr" to "rn"
9500 if (StringRef(S).ends_with(Suffix: "nr"))
9501 S.replace(i1: S.end()-2, i2: S.end(), s: "rn");
9502 }
9503
9504 if (PointeeTy->isCharType()) {
9505 // char pointer types should be encoded as '*' unless it is a
9506 // type that has been typedef'd to 'BOOL'.
9507 if (!isTypeTypedefedAsBOOL(T: PointeeTy)) {
9508 S += '*';
9509 return;
9510 }
9511 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9512 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9513 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9514 if (II == &Idents.get(Name: "objc_class")) {
9515 S += '#';
9516 return;
9517 }
9518 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9519 if (II == &Idents.get(Name: "objc_object")) {
9520 S += '@';
9521 return;
9522 }
9523 // If the encoded string for the class includes template names, just emit
9524 // "^v" for pointers to the class.
9525 if (getLangOpts().CPlusPlus &&
9526 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9527 hasTemplateSpecializationInEncodedString(
9528 T: RTy, VisitBasesAndFields: Options.ExpandPointedToStructures()))) {
9529 S += "^v";
9530 return;
9531 }
9532 // fall through...
9533 }
9534 S += '^';
9535 getLegacyIntegralTypeEncoding(PointeeTy);
9536
9537 ObjCEncOptions NewOptions;
9538 if (Options.ExpandPointedToStructures())
9539 NewOptions.setExpandStructures();
9540 getObjCEncodingForTypeImpl(T: PointeeTy, S, Options: NewOptions,
9541 /*Field=*/FD: nullptr, NotEncodedT);
9542 return;
9543 }
9544
9545 case Type::ConstantArray:
9546 case Type::IncompleteArray:
9547 case Type::VariableArray: {
9548 const auto *AT = cast<ArrayType>(Val&: CT);
9549
9550 if (isa<IncompleteArrayType>(Val: AT) && !Options.IsStructField()) {
9551 // Incomplete arrays are encoded as a pointer to the array element.
9552 S += '^';
9553
9554 getObjCEncodingForTypeImpl(
9555 T: AT->getElementType(), S,
9556 Options: Options.keepingOnly(Mask: ObjCEncOptions().setExpandStructures()), FD);
9557 } else {
9558 S += '[';
9559
9560 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT))
9561 S += llvm::utostr(X: CAT->getZExtSize());
9562 else {
9563 //Variable length arrays are encoded as a regular array with 0 elements.
9564 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
9565 "Unknown array type!");
9566 S += '0';
9567 }
9568
9569 getObjCEncodingForTypeImpl(
9570 T: AT->getElementType(), S,
9571 Options: Options.keepingOnly(Mask: ObjCEncOptions().setExpandStructures()), FD,
9572 NotEncodedT);
9573 S += ']';
9574 }
9575 return;
9576 }
9577
9578 case Type::FunctionNoProto:
9579 case Type::FunctionProto:
9580 S += '?';
9581 return;
9582
9583 case Type::Record: {
9584 RecordDecl *RDecl = cast<RecordType>(Val&: CT)->getDecl();
9585 S += RDecl->isUnion() ? '(' : '{';
9586 // Anonymous structures print as '?'
9587 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9588 S += II->getName();
9589 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: RDecl)) {
9590 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9591 llvm::raw_string_ostream OS(S);
9592 printTemplateArgumentList(OS, Args: TemplateArgs.asArray(),
9593 Policy: getPrintingPolicy());
9594 }
9595 } else {
9596 S += '?';
9597 }
9598 if (Options.ExpandStructures()) {
9599 S += '=';
9600 if (!RDecl->isUnion()) {
9601 getObjCEncodingForStructureImpl(RD: RDecl, S, Field: FD, includeVBases: true, NotEncodedT);
9602 } else {
9603 for (const auto *Field : RDecl->fields()) {
9604 if (FD) {
9605 S += '"';
9606 S += Field->getNameAsString();
9607 S += '"';
9608 }
9609
9610 // Special case bit-fields.
9611 if (Field->isBitField()) {
9612 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9613 Options: ObjCEncOptions().setExpandStructures(),
9614 FD: Field);
9615 } else {
9616 QualType qt = Field->getType();
9617 getLegacyIntegralTypeEncoding(PointeeTy&: qt);
9618 getObjCEncodingForTypeImpl(
9619 T: qt, S,
9620 Options: ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9621 NotEncodedT);
9622 }
9623 }
9624 }
9625 }
9626 S += RDecl->isUnion() ? ')' : '}';
9627 return;
9628 }
9629
9630 case Type::BlockPointer: {
9631 const auto *BT = T->castAs<BlockPointerType>();
9632 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9633 if (Options.EncodeBlockParameters()) {
9634 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9635
9636 S += '<';
9637 // Block return type
9638 getObjCEncodingForTypeImpl(T: FT->getReturnType(), S,
9639 Options: Options.forComponentType(), FD, NotEncodedT);
9640 // Block self
9641 S += "@?";
9642 // Block parameters
9643 if (const auto *FPT = dyn_cast<FunctionProtoType>(Val: FT)) {
9644 for (const auto &I : FPT->param_types())
9645 getObjCEncodingForTypeImpl(T: I, S, Options: Options.forComponentType(), FD,
9646 NotEncodedT);
9647 }
9648 S += '>';
9649 }
9650 return;
9651 }
9652
9653 case Type::ObjCObject: {
9654 // hack to match legacy encoding of *id and *Class
9655 QualType Ty = getObjCObjectPointerType(ObjectT: CT);
9656 if (Ty->isObjCIdType()) {
9657 S += "{objc_object=}";
9658 return;
9659 }
9660 else if (Ty->isObjCClassType()) {
9661 S += "{objc_class=}";
9662 return;
9663 }
9664 // TODO: Double check to make sure this intentionally falls through.
9665 [[fallthrough]];
9666 }
9667
9668 case Type::ObjCInterface: {
9669 // Ignore protocol qualifiers when mangling at this level.
9670 // @encode(class_name)
9671 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9672 S += '{';
9673 S += OI->getObjCRuntimeNameAsString();
9674 if (Options.ExpandStructures()) {
9675 S += '=';
9676 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9677 DeepCollectObjCIvars(OI, leafClass: true, Ivars);
9678 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9679 const FieldDecl *Field = Ivars[i];
9680 if (Field->isBitField())
9681 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9682 Options: ObjCEncOptions().setExpandStructures(),
9683 FD: Field);
9684 else
9685 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9686 Options: ObjCEncOptions().setExpandStructures(), FD,
9687 NotEncodedT);
9688 }
9689 }
9690 S += '}';
9691 return;
9692 }
9693
9694 case Type::ObjCObjectPointer: {
9695 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9696 if (OPT->isObjCIdType()) {
9697 S += '@';
9698 return;
9699 }
9700
9701 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9702 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9703 // Since this is a binary compatibility issue, need to consult with
9704 // runtime folks. Fortunately, this is a *very* obscure construct.
9705 S += '#';
9706 return;
9707 }
9708
9709 if (OPT->isObjCQualifiedIdType()) {
9710 getObjCEncodingForTypeImpl(
9711 T: getObjCIdType(), S,
9712 Options: Options.keepingOnly(Mask: ObjCEncOptions()
9713 .setExpandPointedToStructures()
9714 .setExpandStructures()),
9715 FD);
9716 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9717 // Note that we do extended encoding of protocol qualifier list
9718 // Only when doing ivar or property encoding.
9719 S += '"';
9720 for (const auto *I : OPT->quals()) {
9721 S += '<';
9722 S += I->getObjCRuntimeNameAsString();
9723 S += '>';
9724 }
9725 S += '"';
9726 }
9727 return;
9728 }
9729
9730 S += '@';
9731 if (OPT->getInterfaceDecl() &&
9732 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9733 S += '"';
9734 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9735 for (const auto *I : OPT->quals()) {
9736 S += '<';
9737 S += I->getObjCRuntimeNameAsString();
9738 S += '>';
9739 }
9740 S += '"';
9741 }
9742 return;
9743 }
9744
9745 // gcc just blithely ignores member pointers.
9746 // FIXME: we should do better than that. 'M' is available.
9747 case Type::MemberPointer:
9748 // This matches gcc's encoding, even though technically it is insufficient.
9749 //FIXME. We should do a better job than gcc.
9750 case Type::Vector:
9751 case Type::ExtVector:
9752 // Until we have a coherent encoding of these three types, issue warning.
9753 if (NotEncodedT)
9754 *NotEncodedT = T;
9755 return;
9756
9757 case Type::ConstantMatrix:
9758 if (NotEncodedT)
9759 *NotEncodedT = T;
9760 return;
9761
9762 case Type::BitInt:
9763 if (NotEncodedT)
9764 *NotEncodedT = T;
9765 return;
9766
9767 // We could see an undeduced auto type here during error recovery.
9768 // Just ignore it.
9769 case Type::Auto:
9770 case Type::DeducedTemplateSpecialization:
9771 return;
9772
9773 case Type::HLSLAttributedResource:
9774 case Type::HLSLInlineSpirv:
9775 case Type::OverflowBehavior:
9776 llvm_unreachable("unexpected type");
9777
9778 case Type::ArrayParameter:
9779 case Type::Pipe:
9780#define ABSTRACT_TYPE(KIND, BASE)
9781#define TYPE(KIND, BASE)
9782#define DEPENDENT_TYPE(KIND, BASE) \
9783 case Type::KIND:
9784#define NON_CANONICAL_TYPE(KIND, BASE) \
9785 case Type::KIND:
9786#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9787 case Type::KIND:
9788#include "clang/AST/TypeNodes.inc"
9789 llvm_unreachable("@encode for dependent type!");
9790 }
9791 llvm_unreachable("bad type kind!");
9792}
9793
9794void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9795 std::string &S,
9796 const FieldDecl *FD,
9797 bool includeVBases,
9798 QualType *NotEncodedT) const {
9799 assert(RDecl && "Expected non-null RecordDecl");
9800 assert(!RDecl->isUnion() && "Should not be called for unions");
9801 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9802 return;
9803
9804 const auto *CXXRec = dyn_cast<CXXRecordDecl>(Val: RDecl);
9805 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9806 const ASTRecordLayout &layout = getASTRecordLayout(D: RDecl);
9807
9808 if (CXXRec) {
9809 for (const auto &BI : CXXRec->bases()) {
9810 if (!BI.isVirtual()) {
9811 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9812 if (base->isEmpty())
9813 continue;
9814 uint64_t offs = toBits(CharSize: layout.getBaseClassOffset(Base: base));
9815 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9816 x: std::make_pair(x&: offs, y&: base));
9817 }
9818 }
9819 }
9820
9821 for (FieldDecl *Field : RDecl->fields()) {
9822 if (!Field->isZeroLengthBitField() && Field->isZeroSize(Ctx: *this))
9823 continue;
9824 uint64_t offs = layout.getFieldOffset(FieldNo: Field->getFieldIndex());
9825 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9826 x: std::make_pair(x&: offs, y&: Field));
9827 }
9828
9829 if (CXXRec && includeVBases) {
9830 for (const auto &BI : CXXRec->vbases()) {
9831 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9832 if (base->isEmpty())
9833 continue;
9834 uint64_t offs = toBits(CharSize: layout.getVBaseClassOffset(VBase: base));
9835 if (offs >= uint64_t(toBits(CharSize: layout.getNonVirtualSize())) &&
9836 FieldOrBaseOffsets.find(x: offs) == FieldOrBaseOffsets.end())
9837 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.end(),
9838 x: std::make_pair(x&: offs, y&: base));
9839 }
9840 }
9841
9842 CharUnits size;
9843 if (CXXRec) {
9844 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9845 } else {
9846 size = layout.getSize();
9847 }
9848
9849#ifndef NDEBUG
9850 uint64_t CurOffs = 0;
9851#endif
9852 std::multimap<uint64_t, NamedDecl *>::iterator
9853 CurLayObj = FieldOrBaseOffsets.begin();
9854
9855 if (CXXRec && CXXRec->isDynamicClass() &&
9856 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9857 if (FD) {
9858 S += "\"_vptr$";
9859 std::string recname = CXXRec->getNameAsString();
9860 if (recname.empty()) recname = "?";
9861 S += recname;
9862 S += '"';
9863 }
9864 S += "^^?";
9865#ifndef NDEBUG
9866 CurOffs += getTypeSize(VoidPtrTy);
9867#endif
9868 }
9869
9870 if (!RDecl->hasFlexibleArrayMember()) {
9871 // Mark the end of the structure.
9872 uint64_t offs = toBits(CharSize: size);
9873 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9874 x: std::make_pair(x&: offs, y: nullptr));
9875 }
9876
9877 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9878#ifndef NDEBUG
9879 assert(CurOffs <= CurLayObj->first);
9880 if (CurOffs < CurLayObj->first) {
9881 uint64_t padding = CurLayObj->first - CurOffs;
9882 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9883 // packing/alignment of members is different that normal, in which case
9884 // the encoding will be out-of-sync with the real layout.
9885 // If the runtime switches to just consider the size of types without
9886 // taking into account alignment, we could make padding explicit in the
9887 // encoding (e.g. using arrays of chars). The encoding strings would be
9888 // longer then though.
9889 CurOffs += padding;
9890 }
9891#endif
9892
9893 NamedDecl *dcl = CurLayObj->second;
9894 if (!dcl)
9895 break; // reached end of structure.
9896
9897 if (auto *base = dyn_cast<CXXRecordDecl>(Val: dcl)) {
9898 // We expand the bases without their virtual bases since those are going
9899 // in the initial structure. Note that this differs from gcc which
9900 // expands virtual bases each time one is encountered in the hierarchy,
9901 // making the encoding type bigger than it really is.
9902 getObjCEncodingForStructureImpl(RDecl: base, S, FD, /*includeVBases*/false,
9903 NotEncodedT);
9904 assert(!base->isEmpty());
9905#ifndef NDEBUG
9906 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9907#endif
9908 } else {
9909 const auto *field = cast<FieldDecl>(Val: dcl);
9910 if (FD) {
9911 S += '"';
9912 S += field->getNameAsString();
9913 S += '"';
9914 }
9915
9916 if (field->isBitField()) {
9917 EncodeBitField(Ctx: this, S, T: field->getType(), FD: field);
9918#ifndef NDEBUG
9919 CurOffs += field->getBitWidthValue();
9920#endif
9921 } else {
9922 QualType qt = field->getType();
9923 getLegacyIntegralTypeEncoding(PointeeTy&: qt);
9924 getObjCEncodingForTypeImpl(
9925 T: qt, S, Options: ObjCEncOptions().setExpandStructures().setIsStructField(),
9926 FD, NotEncodedT);
9927#ifndef NDEBUG
9928 CurOffs += getTypeSize(field->getType());
9929#endif
9930 }
9931 }
9932 }
9933}
9934
9935void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
9936 std::string& S) const {
9937 if (QT & Decl::OBJC_TQ_In)
9938 S += 'n';
9939 if (QT & Decl::OBJC_TQ_Inout)
9940 S += 'N';
9941 if (QT & Decl::OBJC_TQ_Out)
9942 S += 'o';
9943 if (QT & Decl::OBJC_TQ_Bycopy)
9944 S += 'O';
9945 if (QT & Decl::OBJC_TQ_Byref)
9946 S += 'R';
9947 if (QT & Decl::OBJC_TQ_Oneway)
9948 S += 'V';
9949}
9950
9951TypedefDecl *ASTContext::getObjCIdDecl() const {
9952 if (!ObjCIdDecl) {
9953 QualType T = getObjCObjectType(BaseType: ObjCBuiltinIdTy, Protocols: {}, NumProtocols: {});
9954 T = getObjCObjectPointerType(ObjectT: T);
9955 ObjCIdDecl = buildImplicitTypedef(T, Name: "id");
9956 }
9957 return ObjCIdDecl;
9958}
9959
9960TypedefDecl *ASTContext::getObjCSelDecl() const {
9961 if (!ObjCSelDecl) {
9962 QualType T = getPointerType(T: ObjCBuiltinSelTy);
9963 ObjCSelDecl = buildImplicitTypedef(T, Name: "SEL");
9964 }
9965 return ObjCSelDecl;
9966}
9967
9968TypedefDecl *ASTContext::getObjCClassDecl() const {
9969 if (!ObjCClassDecl) {
9970 QualType T = getObjCObjectType(BaseType: ObjCBuiltinClassTy, Protocols: {}, NumProtocols: {});
9971 T = getObjCObjectPointerType(ObjectT: T);
9972 ObjCClassDecl = buildImplicitTypedef(T, Name: "Class");
9973 }
9974 return ObjCClassDecl;
9975}
9976
9977ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
9978 if (!ObjCProtocolClassDecl) {
9979 ObjCProtocolClassDecl
9980 = ObjCInterfaceDecl::Create(C: *this, DC: getTranslationUnitDecl(),
9981 atLoc: SourceLocation(),
9982 Id: &Idents.get(Name: "Protocol"),
9983 /*typeParamList=*/nullptr,
9984 /*PrevDecl=*/nullptr,
9985 ClassLoc: SourceLocation(), isInternal: true);
9986 }
9987
9988 return ObjCProtocolClassDecl;
9989}
9990
9991PointerAuthQualifier ASTContext::getObjCMemberSelTypePtrAuth() {
9992 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9993 return PointerAuthQualifier();
9994 return PointerAuthQualifier::Create(
9995 Key: getLangOpts().PointerAuthObjcInterfaceSelKey,
9996 /*isAddressDiscriminated=*/IsAddressDiscriminated: true, ExtraDiscriminator: SelPointerConstantDiscriminator,
9997 AuthenticationMode: PointerAuthenticationMode::SignAndAuth,
9998 /*isIsaPointer=*/IsIsaPointer: false,
9999 /*authenticatesNullValues=*/AuthenticatesNullValues: false);
10000}
10001
10002//===----------------------------------------------------------------------===//
10003// __builtin_va_list Construction Functions
10004//===----------------------------------------------------------------------===//
10005
10006static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
10007 StringRef Name) {
10008 // typedef char* __builtin[_ms]_va_list;
10009 QualType T = Context->getPointerType(T: Context->CharTy);
10010 return Context->buildImplicitTypedef(T, Name);
10011}
10012
10013static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
10014 return CreateCharPtrNamedVaListDecl(Context, Name: "__builtin_ms_va_list");
10015}
10016
10017static TypedefDecl *CreateZOSVaListDecl(const ASTContext *Context) {
10018 // typedef char *__builtin_zos_va_list[2];
10019 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 2);
10020 QualType T = Context->getPointerType(T: Context->CharTy);
10021 QualType ArrayType = Context->getConstantArrayType(
10022 EltTy: T, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10023 return Context->buildImplicitTypedef(T: ArrayType, Name: "__builtin_zos_va_list");
10024}
10025
10026static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
10027 return CreateCharPtrNamedVaListDecl(Context, Name: "__builtin_va_list");
10028}
10029
10030static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
10031 // typedef void* __builtin_va_list;
10032 QualType T = Context->getPointerType(T: Context->VoidTy);
10033 return Context->buildImplicitTypedef(T, Name: "__builtin_va_list");
10034}
10035
10036static TypedefDecl *
10037CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
10038 // struct __va_list
10039 RecordDecl *VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list");
10040 if (Context->getLangOpts().CPlusPlus) {
10041 // namespace std { struct __va_list {
10042 auto *NS = NamespaceDecl::Create(
10043 C&: const_cast<ASTContext &>(*Context), DC: Context->getTranslationUnitDecl(),
10044 /*Inline=*/false, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
10045 Id: &Context->Idents.get(Name: "std"),
10046 /*PrevDecl=*/nullptr, /*Nested=*/false);
10047 NS->setImplicit();
10048 VaListTagDecl->setDeclContext(NS);
10049 }
10050
10051 VaListTagDecl->startDefinition();
10052
10053 const size_t NumFields = 5;
10054 QualType FieldTypes[NumFields];
10055 const char *FieldNames[NumFields];
10056
10057 // void *__stack;
10058 FieldTypes[0] = Context->getPointerType(T: Context->VoidTy);
10059 FieldNames[0] = "__stack";
10060
10061 // void *__gr_top;
10062 FieldTypes[1] = Context->getPointerType(T: Context->VoidTy);
10063 FieldNames[1] = "__gr_top";
10064
10065 // void *__vr_top;
10066 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10067 FieldNames[2] = "__vr_top";
10068
10069 // int __gr_offs;
10070 FieldTypes[3] = Context->IntTy;
10071 FieldNames[3] = "__gr_offs";
10072
10073 // int __vr_offs;
10074 FieldTypes[4] = Context->IntTy;
10075 FieldNames[4] = "__vr_offs";
10076
10077 // Create fields
10078 for (unsigned i = 0; i < NumFields; ++i) {
10079 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10080 DC: VaListTagDecl,
10081 StartLoc: SourceLocation(),
10082 IdLoc: SourceLocation(),
10083 Id: &Context->Idents.get(Name: FieldNames[i]),
10084 T: FieldTypes[i], /*TInfo=*/nullptr,
10085 /*BitWidth=*/BW: nullptr,
10086 /*Mutable=*/false,
10087 InitStyle: ICIS_NoInit);
10088 Field->setAccess(AS_public);
10089 VaListTagDecl->addDecl(D: Field);
10090 }
10091 VaListTagDecl->completeDefinition();
10092 Context->VaListTagDecl = VaListTagDecl;
10093 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10094
10095 // } __builtin_va_list;
10096 return Context->buildImplicitTypedef(T: VaListTagType, Name: "__builtin_va_list");
10097}
10098
10099static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
10100 // typedef struct __va_list_tag {
10101 RecordDecl *VaListTagDecl;
10102
10103 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10104 VaListTagDecl->startDefinition();
10105
10106 const size_t NumFields = 5;
10107 QualType FieldTypes[NumFields];
10108 const char *FieldNames[NumFields];
10109
10110 // unsigned char gpr;
10111 FieldTypes[0] = Context->UnsignedCharTy;
10112 FieldNames[0] = "gpr";
10113
10114 // unsigned char fpr;
10115 FieldTypes[1] = Context->UnsignedCharTy;
10116 FieldNames[1] = "fpr";
10117
10118 // unsigned short reserved;
10119 FieldTypes[2] = Context->UnsignedShortTy;
10120 FieldNames[2] = "reserved";
10121
10122 // void* overflow_arg_area;
10123 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10124 FieldNames[3] = "overflow_arg_area";
10125
10126 // void* reg_save_area;
10127 FieldTypes[4] = Context->getPointerType(T: Context->VoidTy);
10128 FieldNames[4] = "reg_save_area";
10129
10130 // Create fields
10131 for (unsigned i = 0; i < NumFields; ++i) {
10132 FieldDecl *Field = FieldDecl::Create(C: *Context, DC: VaListTagDecl,
10133 StartLoc: SourceLocation(),
10134 IdLoc: SourceLocation(),
10135 Id: &Context->Idents.get(Name: FieldNames[i]),
10136 T: FieldTypes[i], /*TInfo=*/nullptr,
10137 /*BitWidth=*/BW: nullptr,
10138 /*Mutable=*/false,
10139 InitStyle: ICIS_NoInit);
10140 Field->setAccess(AS_public);
10141 VaListTagDecl->addDecl(D: Field);
10142 }
10143 VaListTagDecl->completeDefinition();
10144 Context->VaListTagDecl = VaListTagDecl;
10145 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10146
10147 // } __va_list_tag;
10148 TypedefDecl *VaListTagTypedefDecl =
10149 Context->buildImplicitTypedef(T: VaListTagType, Name: "__va_list_tag");
10150
10151 QualType VaListTagTypedefType =
10152 Context->getTypedefType(Keyword: ElaboratedTypeKeyword::None,
10153 /*Qualifier=*/std::nullopt, Decl: VaListTagTypedefDecl);
10154
10155 // typedef __va_list_tag __builtin_va_list[1];
10156 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10157 QualType VaListTagArrayType = Context->getConstantArrayType(
10158 EltTy: VaListTagTypedefType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10159 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10160}
10161
10162static TypedefDecl *
10163CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
10164 // struct __va_list_tag {
10165 RecordDecl *VaListTagDecl;
10166 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10167 VaListTagDecl->startDefinition();
10168
10169 const size_t NumFields = 4;
10170 QualType FieldTypes[NumFields];
10171 const char *FieldNames[NumFields];
10172
10173 // unsigned gp_offset;
10174 FieldTypes[0] = Context->UnsignedIntTy;
10175 FieldNames[0] = "gp_offset";
10176
10177 // unsigned fp_offset;
10178 FieldTypes[1] = Context->UnsignedIntTy;
10179 FieldNames[1] = "fp_offset";
10180
10181 // void* overflow_arg_area;
10182 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10183 FieldNames[2] = "overflow_arg_area";
10184
10185 // void* reg_save_area;
10186 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10187 FieldNames[3] = "reg_save_area";
10188
10189 // Create fields
10190 for (unsigned i = 0; i < NumFields; ++i) {
10191 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10192 DC: VaListTagDecl,
10193 StartLoc: SourceLocation(),
10194 IdLoc: SourceLocation(),
10195 Id: &Context->Idents.get(Name: FieldNames[i]),
10196 T: FieldTypes[i], /*TInfo=*/nullptr,
10197 /*BitWidth=*/BW: nullptr,
10198 /*Mutable=*/false,
10199 InitStyle: ICIS_NoInit);
10200 Field->setAccess(AS_public);
10201 VaListTagDecl->addDecl(D: Field);
10202 }
10203 VaListTagDecl->completeDefinition();
10204 Context->VaListTagDecl = VaListTagDecl;
10205 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10206
10207 // };
10208
10209 // typedef struct __va_list_tag __builtin_va_list[1];
10210 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10211 QualType VaListTagArrayType = Context->getConstantArrayType(
10212 EltTy: VaListTagType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10213 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10214}
10215
10216static TypedefDecl *
10217CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
10218 // struct __va_list
10219 RecordDecl *VaListDecl = Context->buildImplicitRecord(Name: "__va_list");
10220 if (Context->getLangOpts().CPlusPlus) {
10221 // namespace std { struct __va_list {
10222 NamespaceDecl *NS;
10223 NS = NamespaceDecl::Create(C&: const_cast<ASTContext &>(*Context),
10224 DC: Context->getTranslationUnitDecl(),
10225 /*Inline=*/false, StartLoc: SourceLocation(),
10226 IdLoc: SourceLocation(), Id: &Context->Idents.get(Name: "std"),
10227 /*PrevDecl=*/nullptr, /*Nested=*/false);
10228 NS->setImplicit();
10229 VaListDecl->setDeclContext(NS);
10230 }
10231
10232 VaListDecl->startDefinition();
10233
10234 // void * __ap;
10235 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10236 DC: VaListDecl,
10237 StartLoc: SourceLocation(),
10238 IdLoc: SourceLocation(),
10239 Id: &Context->Idents.get(Name: "__ap"),
10240 T: Context->getPointerType(T: Context->VoidTy),
10241 /*TInfo=*/nullptr,
10242 /*BitWidth=*/BW: nullptr,
10243 /*Mutable=*/false,
10244 InitStyle: ICIS_NoInit);
10245 Field->setAccess(AS_public);
10246 VaListDecl->addDecl(D: Field);
10247
10248 // };
10249 VaListDecl->completeDefinition();
10250 Context->VaListTagDecl = VaListDecl;
10251
10252 // typedef struct __va_list __builtin_va_list;
10253 CanQualType T = Context->getCanonicalTagType(TD: VaListDecl);
10254 return Context->buildImplicitTypedef(T, Name: "__builtin_va_list");
10255}
10256
10257static TypedefDecl *
10258CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
10259 // struct __va_list_tag {
10260 RecordDecl *VaListTagDecl;
10261 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10262 VaListTagDecl->startDefinition();
10263
10264 const size_t NumFields = 4;
10265 QualType FieldTypes[NumFields];
10266 const char *FieldNames[NumFields];
10267
10268 // long __gpr;
10269 FieldTypes[0] = Context->LongTy;
10270 FieldNames[0] = "__gpr";
10271
10272 // long __fpr;
10273 FieldTypes[1] = Context->LongTy;
10274 FieldNames[1] = "__fpr";
10275
10276 // void *__overflow_arg_area;
10277 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10278 FieldNames[2] = "__overflow_arg_area";
10279
10280 // void *__reg_save_area;
10281 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10282 FieldNames[3] = "__reg_save_area";
10283
10284 // Create fields
10285 for (unsigned i = 0; i < NumFields; ++i) {
10286 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10287 DC: VaListTagDecl,
10288 StartLoc: SourceLocation(),
10289 IdLoc: SourceLocation(),
10290 Id: &Context->Idents.get(Name: FieldNames[i]),
10291 T: FieldTypes[i], /*TInfo=*/nullptr,
10292 /*BitWidth=*/BW: nullptr,
10293 /*Mutable=*/false,
10294 InitStyle: ICIS_NoInit);
10295 Field->setAccess(AS_public);
10296 VaListTagDecl->addDecl(D: Field);
10297 }
10298 VaListTagDecl->completeDefinition();
10299 Context->VaListTagDecl = VaListTagDecl;
10300 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10301
10302 // };
10303
10304 // typedef __va_list_tag __builtin_va_list[1];
10305 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10306 QualType VaListTagArrayType = Context->getConstantArrayType(
10307 EltTy: VaListTagType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10308
10309 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10310}
10311
10312static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
10313 // typedef struct __va_list_tag {
10314 RecordDecl *VaListTagDecl;
10315 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10316 VaListTagDecl->startDefinition();
10317
10318 const size_t NumFields = 3;
10319 QualType FieldTypes[NumFields];
10320 const char *FieldNames[NumFields];
10321
10322 // void *CurrentSavedRegisterArea;
10323 FieldTypes[0] = Context->getPointerType(T: Context->VoidTy);
10324 FieldNames[0] = "__current_saved_reg_area_pointer";
10325
10326 // void *SavedRegAreaEnd;
10327 FieldTypes[1] = Context->getPointerType(T: Context->VoidTy);
10328 FieldNames[1] = "__saved_reg_area_end_pointer";
10329
10330 // void *OverflowArea;
10331 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10332 FieldNames[2] = "__overflow_area_pointer";
10333
10334 // Create fields
10335 for (unsigned i = 0; i < NumFields; ++i) {
10336 FieldDecl *Field = FieldDecl::Create(
10337 C: const_cast<ASTContext &>(*Context), DC: VaListTagDecl, StartLoc: SourceLocation(),
10338 IdLoc: SourceLocation(), Id: &Context->Idents.get(Name: FieldNames[i]), T: FieldTypes[i],
10339 /*TInfo=*/nullptr,
10340 /*BitWidth=*/BW: nullptr,
10341 /*Mutable=*/false, InitStyle: ICIS_NoInit);
10342 Field->setAccess(AS_public);
10343 VaListTagDecl->addDecl(D: Field);
10344 }
10345 VaListTagDecl->completeDefinition();
10346 Context->VaListTagDecl = VaListTagDecl;
10347 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10348
10349 // } __va_list_tag;
10350 TypedefDecl *VaListTagTypedefDecl =
10351 Context->buildImplicitTypedef(T: VaListTagType, Name: "__va_list_tag");
10352
10353 QualType VaListTagTypedefType =
10354 Context->getTypedefType(Keyword: ElaboratedTypeKeyword::None,
10355 /*Qualifier=*/std::nullopt, Decl: VaListTagTypedefDecl);
10356
10357 // typedef __va_list_tag __builtin_va_list[1];
10358 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10359 QualType VaListTagArrayType = Context->getConstantArrayType(
10360 EltTy: VaListTagTypedefType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10361
10362 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10363}
10364
10365static TypedefDecl *
10366CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context) {
10367 // typedef struct __va_list_tag {
10368 RecordDecl *VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10369
10370 VaListTagDecl->startDefinition();
10371
10372 // int* __va_stk;
10373 // int* __va_reg;
10374 // int __va_ndx;
10375 constexpr size_t NumFields = 3;
10376 QualType FieldTypes[NumFields] = {Context->getPointerType(T: Context->IntTy),
10377 Context->getPointerType(T: Context->IntTy),
10378 Context->IntTy};
10379 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10380
10381 // Create fields
10382 for (unsigned i = 0; i < NumFields; ++i) {
10383 FieldDecl *Field = FieldDecl::Create(
10384 C: *Context, DC: VaListTagDecl, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
10385 Id: &Context->Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
10386 /*BitWidth=*/BW: nullptr,
10387 /*Mutable=*/false, InitStyle: ICIS_NoInit);
10388 Field->setAccess(AS_public);
10389 VaListTagDecl->addDecl(D: Field);
10390 }
10391 VaListTagDecl->completeDefinition();
10392 Context->VaListTagDecl = VaListTagDecl;
10393 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10394
10395 // } __va_list_tag;
10396 TypedefDecl *VaListTagTypedefDecl =
10397 Context->buildImplicitTypedef(T: VaListTagType, Name: "__builtin_va_list");
10398
10399 return VaListTagTypedefDecl;
10400}
10401
10402static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
10403 TargetInfo::BuiltinVaListKind Kind) {
10404 switch (Kind) {
10405 case TargetInfo::CharPtrBuiltinVaList:
10406 return CreateCharPtrBuiltinVaListDecl(Context);
10407 case TargetInfo::VoidPtrBuiltinVaList:
10408 return CreateVoidPtrBuiltinVaListDecl(Context);
10409 case TargetInfo::AArch64ABIBuiltinVaList:
10410 return CreateAArch64ABIBuiltinVaListDecl(Context);
10411 case TargetInfo::PowerABIBuiltinVaList:
10412 return CreatePowerABIBuiltinVaListDecl(Context);
10413 case TargetInfo::X86_64ABIBuiltinVaList:
10414 return CreateX86_64ABIBuiltinVaListDecl(Context);
10415 case TargetInfo::AAPCSABIBuiltinVaList:
10416 return CreateAAPCSABIBuiltinVaListDecl(Context);
10417 case TargetInfo::SystemZBuiltinVaList:
10418 return CreateSystemZBuiltinVaListDecl(Context);
10419 case TargetInfo::HexagonBuiltinVaList:
10420 return CreateHexagonBuiltinVaListDecl(Context);
10421 case TargetInfo::XtensaABIBuiltinVaList:
10422 return CreateXtensaABIBuiltinVaListDecl(Context);
10423 }
10424
10425 llvm_unreachable("Unhandled __builtin_va_list type kind");
10426}
10427
10428TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
10429 if (!BuiltinVaListDecl) {
10430 BuiltinVaListDecl = CreateVaListDecl(Context: this, Kind: Target->getBuiltinVaListKind());
10431 assert(BuiltinVaListDecl->isImplicit());
10432 }
10433
10434 return BuiltinVaListDecl;
10435}
10436
10437Decl *ASTContext::getVaListTagDecl() const {
10438 // Force the creation of VaListTagDecl by building the __builtin_va_list
10439 // declaration.
10440 if (!VaListTagDecl)
10441 (void)getBuiltinVaListDecl();
10442
10443 return VaListTagDecl;
10444}
10445
10446TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
10447 if (!BuiltinMSVaListDecl)
10448 BuiltinMSVaListDecl = CreateMSVaListDecl(Context: this);
10449
10450 return BuiltinMSVaListDecl;
10451}
10452
10453TypedefDecl *ASTContext::getBuiltinZOSVaListDecl() const {
10454 if (!BuiltinZOSVaListDecl)
10455 BuiltinZOSVaListDecl = CreateZOSVaListDecl(Context: this);
10456
10457 return BuiltinZOSVaListDecl;
10458}
10459
10460bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
10461 // Allow redecl custom type checking builtin for HLSL.
10462 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10463 BuiltinInfo.hasCustomTypechecking(ID: FD->getBuiltinID()))
10464 return true;
10465 // Allow redecl custom type checking builtin for SPIR-V.
10466 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10467 BuiltinInfo.isTSBuiltin(ID: FD->getBuiltinID()) &&
10468 BuiltinInfo.hasCustomTypechecking(ID: FD->getBuiltinID()))
10469 return true;
10470 return BuiltinInfo.canBeRedeclared(ID: FD->getBuiltinID());
10471}
10472
10473void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
10474 assert(ObjCConstantStringType.isNull() &&
10475 "'NSConstantString' type already set!");
10476
10477 ObjCConstantStringType = getObjCInterfaceType(Decl);
10478}
10479
10480/// Retrieve the template name that corresponds to a non-empty
10481/// lookup.
10482TemplateName
10483ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
10484 UnresolvedSetIterator End) const {
10485 unsigned size = End - Begin;
10486 assert(size > 1 && "set is not overloaded!");
10487
10488 void *memory = Allocate(Size: sizeof(OverloadedTemplateStorage) +
10489 size * sizeof(FunctionTemplateDecl*));
10490 auto *OT = new (memory) OverloadedTemplateStorage(size);
10491
10492 NamedDecl **Storage = OT->getStorage();
10493 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10494 NamedDecl *D = *I;
10495 assert(isa<FunctionTemplateDecl>(D) ||
10496 isa<UnresolvedUsingValueDecl>(D) ||
10497 (isa<UsingShadowDecl>(D) &&
10498 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
10499 *Storage++ = D;
10500 }
10501
10502 return TemplateName(OT);
10503}
10504
10505/// Retrieve a template name representing an unqualified-id that has been
10506/// assumed to name a template for ADL purposes.
10507TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
10508 auto *OT = new (*this) AssumedTemplateStorage(Name);
10509 return TemplateName(OT);
10510}
10511
10512/// Retrieve the template name that represents a qualified
10513/// template name such as \c std::vector.
10514TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier Qualifier,
10515 bool TemplateKeyword,
10516 TemplateName Template) const {
10517 assert(Template.getKind() == TemplateName::Template ||
10518 Template.getKind() == TemplateName::UsingTemplate);
10519
10520 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10521 assert(!Qualifier && "unexpected qualified template template parameter");
10522 assert(TemplateKeyword == false);
10523 return Template;
10524 }
10525
10526 // FIXME: Canonicalization?
10527 llvm::FoldingSetNodeID ID;
10528 QualifiedTemplateName::Profile(ID, NNS: Qualifier, TemplateKeyword, TN: Template);
10529
10530 void *InsertPos = nullptr;
10531 QualifiedTemplateName *QTN =
10532 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10533 if (!QTN) {
10534 QTN = new (*this, alignof(QualifiedTemplateName))
10535 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10536 QualifiedTemplateNames.InsertNode(N: QTN, InsertPos);
10537 }
10538
10539 return TemplateName(QTN);
10540}
10541
10542/// Retrieve the template name that represents a dependent
10543/// template name such as \c MetaFun::template operator+.
10544TemplateName
10545ASTContext::getDependentTemplateName(const DependentTemplateStorage &S) const {
10546 llvm::FoldingSetNodeID ID;
10547 S.Profile(ID);
10548
10549 void *InsertPos = nullptr;
10550 if (DependentTemplateName *QTN =
10551 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10552 return TemplateName(QTN);
10553
10554 DependentTemplateName *QTN =
10555 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10556 DependentTemplateNames.InsertNode(N: QTN, InsertPos);
10557 return TemplateName(QTN);
10558}
10559
10560TemplateName ASTContext::getSubstTemplateTemplateParm(TemplateName Replacement,
10561 Decl *AssociatedDecl,
10562 unsigned Index,
10563 UnsignedOrNone PackIndex,
10564 bool Final) const {
10565 llvm::FoldingSetNodeID ID;
10566 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10567 Index, PackIndex, Final);
10568
10569 void *insertPos = nullptr;
10570 SubstTemplateTemplateParmStorage *subst
10571 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos&: insertPos);
10572
10573 if (!subst) {
10574 subst = new (*this) SubstTemplateTemplateParmStorage(
10575 Replacement, AssociatedDecl, Index, PackIndex, Final);
10576 SubstTemplateTemplateParms.InsertNode(N: subst, InsertPos: insertPos);
10577 }
10578
10579 return TemplateName(subst);
10580}
10581
10582TemplateName
10583ASTContext::getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
10584 Decl *AssociatedDecl,
10585 unsigned Index, bool Final) const {
10586 auto &Self = const_cast<ASTContext &>(*this);
10587 llvm::FoldingSetNodeID ID;
10588 SubstTemplateTemplateParmPackStorage::Profile(ID, Context&: Self, ArgPack,
10589 AssociatedDecl, Index, Final);
10590
10591 void *InsertPos = nullptr;
10592 SubstTemplateTemplateParmPackStorage *Subst
10593 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10594
10595 if (!Subst) {
10596 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10597 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10598 SubstTemplateTemplateParmPacks.InsertNode(N: Subst, InsertPos);
10599 }
10600
10601 return TemplateName(Subst);
10602}
10603
10604/// Retrieve the template name that represents a template name
10605/// deduced from a specialization.
10606TemplateName
10607ASTContext::getDeducedTemplateName(TemplateName Underlying,
10608 DefaultArguments DefaultArgs) const {
10609 if (!DefaultArgs)
10610 return Underlying;
10611
10612 llvm::FoldingSetNodeID ID;
10613 DeducedTemplateStorage::Profile(ID, Context: *this, Underlying, DefArgs: DefaultArgs);
10614
10615 void *InsertPos = nullptr;
10616 DeducedTemplateStorage *DTS =
10617 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10618 if (!DTS) {
10619 void *Mem = Allocate(Size: sizeof(DeducedTemplateStorage) +
10620 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10621 Align: alignof(DeducedTemplateStorage));
10622 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10623 DeducedTemplates.InsertNode(N: DTS, InsertPos);
10624 }
10625 return TemplateName(DTS);
10626}
10627
10628/// getFromTargetType - Given one of the integer types provided by
10629/// TargetInfo, produce the corresponding type. The unsigned @p Type
10630/// is actually a value of type @c TargetInfo::IntType.
10631CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10632 switch (Type) {
10633 case TargetInfo::NoInt: return {};
10634 case TargetInfo::SignedChar: return SignedCharTy;
10635 case TargetInfo::UnsignedChar: return UnsignedCharTy;
10636 case TargetInfo::SignedShort: return ShortTy;
10637 case TargetInfo::UnsignedShort: return UnsignedShortTy;
10638 case TargetInfo::SignedInt: return IntTy;
10639 case TargetInfo::UnsignedInt: return UnsignedIntTy;
10640 case TargetInfo::SignedLong: return LongTy;
10641 case TargetInfo::UnsignedLong: return UnsignedLongTy;
10642 case TargetInfo::SignedLongLong: return LongLongTy;
10643 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
10644 }
10645
10646 llvm_unreachable("Unhandled TargetInfo::IntType value");
10647}
10648
10649//===----------------------------------------------------------------------===//
10650// Type Predicates.
10651//===----------------------------------------------------------------------===//
10652
10653/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10654/// garbage collection attribute.
10655///
10656Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
10657 if (getLangOpts().getGC() == LangOptions::NonGC)
10658 return Qualifiers::GCNone;
10659
10660 assert(getLangOpts().ObjC);
10661 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10662
10663 // Default behaviour under objective-C's gc is for ObjC pointers
10664 // (or pointers to them) be treated as though they were declared
10665 // as __strong.
10666 if (GCAttrs == Qualifiers::GCNone) {
10667 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
10668 return Qualifiers::Strong;
10669 else if (Ty->isPointerType())
10670 return getObjCGCAttrKind(Ty: Ty->castAs<PointerType>()->getPointeeType());
10671 } else {
10672 // It's not valid to set GC attributes on anything that isn't a
10673 // pointer.
10674#ifndef NDEBUG
10675 QualType CT = Ty->getCanonicalTypeInternal();
10676 while (const auto *AT = dyn_cast<ArrayType>(CT))
10677 CT = AT->getElementType();
10678 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10679#endif
10680 }
10681 return GCAttrs;
10682}
10683
10684//===----------------------------------------------------------------------===//
10685// Type Compatibility Testing
10686//===----------------------------------------------------------------------===//
10687
10688/// areCompatVectorTypes - Return true if the two specified vector types are
10689/// compatible.
10690static bool areCompatVectorTypes(const VectorType *LHS,
10691 const VectorType *RHS) {
10692 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10693 return LHS->getElementType() == RHS->getElementType() &&
10694 LHS->getNumElements() == RHS->getNumElements();
10695}
10696
10697/// areCompatMatrixTypes - Return true if the two specified matrix types are
10698/// compatible.
10699static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
10700 const ConstantMatrixType *RHS) {
10701 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10702 return LHS->getElementType() == RHS->getElementType() &&
10703 LHS->getNumRows() == RHS->getNumRows() &&
10704 LHS->getNumColumns() == RHS->getNumColumns();
10705}
10706
10707bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
10708 QualType SecondVec) {
10709 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10710 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10711
10712 if (hasSameUnqualifiedType(T1: FirstVec, T2: SecondVec))
10713 return true;
10714
10715 // Treat Neon vector types and most AltiVec vector types as if they are the
10716 // equivalent GCC vector types.
10717 const auto *First = FirstVec->castAs<VectorType>();
10718 const auto *Second = SecondVec->castAs<VectorType>();
10719 if (First->getNumElements() == Second->getNumElements() &&
10720 hasSameType(T1: First->getElementType(), T2: Second->getElementType()) &&
10721 First->getVectorKind() != VectorKind::AltiVecPixel &&
10722 First->getVectorKind() != VectorKind::AltiVecBool &&
10723 Second->getVectorKind() != VectorKind::AltiVecPixel &&
10724 Second->getVectorKind() != VectorKind::AltiVecBool &&
10725 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10726 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10727 Second->getVectorKind() != VectorKind::SveFixedLengthData &&
10728 Second->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10729 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10730 Second->getVectorKind() != VectorKind::RVVFixedLengthData &&
10731 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10732 Second->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10733 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10734 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10735 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10736 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10737 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10738 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_4)
10739 return true;
10740
10741 // In OpenCL, treat half and _Float16 vector types as compatible.
10742 if (getLangOpts().OpenCL &&
10743 First->getNumElements() == Second->getNumElements()) {
10744 QualType FirstElt = First->getElementType();
10745 QualType SecondElt = Second->getElementType();
10746
10747 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10748 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10749 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10750 First->getVectorKind() != VectorKind::AltiVecBool &&
10751 Second->getVectorKind() != VectorKind::AltiVecPixel &&
10752 Second->getVectorKind() != VectorKind::AltiVecBool)
10753 return true;
10754 }
10755 }
10756 return false;
10757}
10758
10759bool ASTContext::areCompatibleOverflowBehaviorTypes(QualType LHS,
10760 QualType RHS) {
10761 auto Result = checkOBTAssignmentCompatibility(LHS, RHS);
10762 return Result != OBTAssignResult::IncompatibleKinds;
10763}
10764
10765ASTContext::OBTAssignResult
10766ASTContext::checkOBTAssignmentCompatibility(QualType LHS, QualType RHS) {
10767 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10768 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10769
10770 if (!LHSOBT && !RHSOBT)
10771 return OBTAssignResult::Compatible;
10772
10773 if (LHSOBT && RHSOBT) {
10774 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10775 return OBTAssignResult::IncompatibleKinds;
10776 return OBTAssignResult::Compatible;
10777 }
10778
10779 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10780 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10781
10782 if (RHSOBT && !LHSOBT) {
10783 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10784 return OBTAssignResult::Discards;
10785 }
10786
10787 return OBTAssignResult::NotApplicable;
10788}
10789
10790/// getRVVTypeSize - Return RVV vector register size.
10791static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10792 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10793 auto VScale = Context.getTargetInfo().getVScaleRange(
10794 LangOpts: Context.getLangOpts(), Mode: TargetInfo::ArmStreamingKind::NotStreaming);
10795 if (!VScale)
10796 return 0;
10797
10798 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10799
10800 uint64_t EltSize = Context.getTypeSize(T: Info.ElementType);
10801 if (Info.ElementType == Context.BoolTy)
10802 EltSize = 1;
10803
10804 uint64_t MinElts = Info.EC.getKnownMinValue();
10805 return VScale->first * MinElts * EltSize;
10806}
10807
10808bool ASTContext::areCompatibleRVVTypes(QualType FirstType,
10809 QualType SecondType) {
10810 assert(
10811 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10812 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10813 "Expected RVV builtin type and vector type!");
10814
10815 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10816 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10817 if (const auto *VT = SecondType->getAs<VectorType>()) {
10818 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10819 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10820 return FirstType->isRVVVLSBuiltinType() &&
10821 Info.ElementType == BoolTy &&
10822 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)));
10823 }
10824 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10825 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10826 return FirstType->isRVVVLSBuiltinType() &&
10827 Info.ElementType == BoolTy &&
10828 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT) * 8));
10829 }
10830 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10831 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10832 return FirstType->isRVVVLSBuiltinType() &&
10833 Info.ElementType == BoolTy &&
10834 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)) * 4);
10835 }
10836 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10837 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10838 return FirstType->isRVVVLSBuiltinType() &&
10839 Info.ElementType == BoolTy &&
10840 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)) * 2);
10841 }
10842 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10843 VT->getVectorKind() == VectorKind::Generic)
10844 return FirstType->isRVVVLSBuiltinType() &&
10845 getTypeSize(T: SecondType) == getRVVTypeSize(Context&: *this, Ty: BT) &&
10846 hasSameType(T1: VT->getElementType(),
10847 T2: getBuiltinVectorTypeInfo(Ty: BT).ElementType);
10848 }
10849 }
10850 return false;
10851 };
10852
10853 return IsValidCast(FirstType, SecondType) ||
10854 IsValidCast(SecondType, FirstType);
10855}
10856
10857bool ASTContext::areLaxCompatibleRVVTypes(QualType FirstType,
10858 QualType SecondType) {
10859 assert(
10860 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10861 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10862 "Expected RVV builtin type and vector type!");
10863
10864 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10865 const auto *BT = FirstType->getAs<BuiltinType>();
10866 if (!BT)
10867 return false;
10868
10869 if (!BT->isRVVVLSBuiltinType())
10870 return false;
10871
10872 const auto *VecTy = SecondType->getAs<VectorType>();
10873 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10874 const LangOptions::LaxVectorConversionKind LVCKind =
10875 getLangOpts().getLaxVectorConversions();
10876
10877 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10878 if (getTypeSize(T: SecondType) != getRVVTypeSize(Context&: *this, Ty: BT))
10879 return false;
10880
10881 // If -flax-vector-conversions=all is specified, the types are
10882 // certainly compatible.
10883 if (LVCKind == LangOptions::LaxVectorConversionKind::All)
10884 return true;
10885
10886 // If -flax-vector-conversions=integer is specified, the types are
10887 // compatible if the elements are integer types.
10888 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
10889 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10890 FirstType->getRVVEltType(Ctx: *this)->isIntegerType();
10891 }
10892
10893 return false;
10894 };
10895
10896 return IsLaxCompatible(FirstType, SecondType) ||
10897 IsLaxCompatible(SecondType, FirstType);
10898}
10899
10900bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
10901 while (true) {
10902 // __strong id
10903 if (const AttributedType *Attr = dyn_cast<AttributedType>(Val&: Ty)) {
10904 if (Attr->getAttrKind() == attr::ObjCOwnership)
10905 return true;
10906
10907 Ty = Attr->getModifiedType();
10908
10909 // X *__strong (...)
10910 } else if (const ParenType *Paren = dyn_cast<ParenType>(Val&: Ty)) {
10911 Ty = Paren->getInnerType();
10912
10913 // We do not want to look through typedefs, typeof(expr),
10914 // typeof(type), or any other way that the type is somehow
10915 // abstracted.
10916 } else {
10917 return false;
10918 }
10919 }
10920}
10921
10922//===----------------------------------------------------------------------===//
10923// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10924//===----------------------------------------------------------------------===//
10925
10926/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10927/// inheritance hierarchy of 'rProto'.
10928bool
10929ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
10930 ObjCProtocolDecl *rProto) const {
10931 if (declaresSameEntity(D1: lProto, D2: rProto))
10932 return true;
10933 for (auto *PI : rProto->protocols())
10934 if (ProtocolCompatibleWithProtocol(lProto, rProto: PI))
10935 return true;
10936 return false;
10937}
10938
10939/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10940/// Class<pr1, ...>.
10941bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
10942 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10943 for (auto *lhsProto : lhs->quals()) {
10944 bool match = false;
10945 for (auto *rhsProto : rhs->quals()) {
10946 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto)) {
10947 match = true;
10948 break;
10949 }
10950 }
10951 if (!match)
10952 return false;
10953 }
10954 return true;
10955}
10956
10957/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10958/// ObjCQualifiedIDType.
10959bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
10960 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10961 bool compare) {
10962 // Allow id<P..> and an 'id' in all cases.
10963 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10964 return true;
10965
10966 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10967 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10968 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
10969 return false;
10970
10971 if (lhs->isObjCQualifiedIdType()) {
10972 if (rhs->qual_empty()) {
10973 // If the RHS is a unqualified interface pointer "NSString*",
10974 // make sure we check the class hierarchy.
10975 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10976 for (auto *I : lhs->quals()) {
10977 // when comparing an id<P> on lhs with a static type on rhs,
10978 // see if static class implements all of id's protocols, directly or
10979 // through its super class and categories.
10980 if (!rhsID->ClassImplementsProtocol(lProto: I, lookupCategory: true))
10981 return false;
10982 }
10983 }
10984 // If there are no qualifiers and no interface, we have an 'id'.
10985 return true;
10986 }
10987 // Both the right and left sides have qualifiers.
10988 for (auto *lhsProto : lhs->quals()) {
10989 bool match = false;
10990
10991 // when comparing an id<P> on lhs with a static type on rhs,
10992 // see if static class implements all of id's protocols, directly or
10993 // through its super class and categories.
10994 for (auto *rhsProto : rhs->quals()) {
10995 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
10996 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
10997 match = true;
10998 break;
10999 }
11000 }
11001 // If the RHS is a qualified interface pointer "NSString<P>*",
11002 // make sure we check the class hierarchy.
11003 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11004 for (auto *I : lhs->quals()) {
11005 // when comparing an id<P> on lhs with a static type on rhs,
11006 // see if static class implements all of id's protocols, directly or
11007 // through its super class and categories.
11008 if (rhsID->ClassImplementsProtocol(lProto: I, lookupCategory: true)) {
11009 match = true;
11010 break;
11011 }
11012 }
11013 }
11014 if (!match)
11015 return false;
11016 }
11017
11018 return true;
11019 }
11020
11021 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
11022
11023 if (lhs->getInterfaceType()) {
11024 // If both the right and left sides have qualifiers.
11025 for (auto *lhsProto : lhs->quals()) {
11026 bool match = false;
11027
11028 // when comparing an id<P> on rhs with a static type on lhs,
11029 // see if static class implements all of id's protocols, directly or
11030 // through its super class and categories.
11031 // First, lhs protocols in the qualifier list must be found, direct
11032 // or indirect in rhs's qualifier list or it is a mismatch.
11033 for (auto *rhsProto : rhs->quals()) {
11034 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11035 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11036 match = true;
11037 break;
11038 }
11039 }
11040 if (!match)
11041 return false;
11042 }
11043
11044 // Static class's protocols, or its super class or category protocols
11045 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
11046 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
11047 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
11048 CollectInheritedProtocols(CDecl: lhsID, Protocols&: LHSInheritedProtocols);
11049 // This is rather dubious but matches gcc's behavior. If lhs has
11050 // no type qualifier and its class has no static protocol(s)
11051 // assume that it is mismatch.
11052 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
11053 return false;
11054 for (auto *lhsProto : LHSInheritedProtocols) {
11055 bool match = false;
11056 for (auto *rhsProto : rhs->quals()) {
11057 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11058 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11059 match = true;
11060 break;
11061 }
11062 }
11063 if (!match)
11064 return false;
11065 }
11066 }
11067 return true;
11068 }
11069 return false;
11070}
11071
11072/// canAssignObjCInterfaces - Return true if the two interface types are
11073/// compatible for assignment from RHS to LHS. This handles validation of any
11074/// protocol qualifiers on the LHS or RHS.
11075bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
11076 const ObjCObjectPointerType *RHSOPT) {
11077 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11078 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11079
11080 // If either type represents the built-in 'id' type, return true.
11081 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
11082 return true;
11083
11084 // Function object that propagates a successful result or handles
11085 // __kindof types.
11086 auto finish = [&](bool succeeded) -> bool {
11087 if (succeeded)
11088 return true;
11089
11090 if (!RHS->isKindOfType())
11091 return false;
11092
11093 // Strip off __kindof and protocol qualifiers, then check whether
11094 // we can assign the other way.
11095 return canAssignObjCInterfaces(LHSOPT: RHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11096 RHSOPT: LHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this));
11097 };
11098
11099 // Casts from or to id<P> are allowed when the other side has compatible
11100 // protocols.
11101 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11102 return finish(ObjCQualifiedIdTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT, compare: false));
11103 }
11104
11105 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11106 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11107 return finish(ObjCQualifiedClassTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT));
11108 }
11109
11110 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11111 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11112 return true;
11113 }
11114
11115 // If we have 2 user-defined types, fall into that path.
11116 if (LHS->getInterface() && RHS->getInterface()) {
11117 return finish(canAssignObjCInterfaces(LHS, RHS));
11118 }
11119
11120 return false;
11121}
11122
11123/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11124/// for providing type-safety for objective-c pointers used to pass/return
11125/// arguments in block literals. When passed as arguments, passing 'A*' where
11126/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11127/// not OK. For the return type, the opposite is not OK.
11128bool ASTContext::canAssignObjCInterfacesInBlockPointer(
11129 const ObjCObjectPointerType *LHSOPT,
11130 const ObjCObjectPointerType *RHSOPT,
11131 bool BlockReturnType) {
11132
11133 // Function object that propagates a successful result or handles
11134 // __kindof types.
11135 auto finish = [&](bool succeeded) -> bool {
11136 if (succeeded)
11137 return true;
11138
11139 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11140 if (!Expected->isKindOfType())
11141 return false;
11142
11143 // Strip off __kindof and protocol qualifiers, then check whether
11144 // we can assign the other way.
11145 return canAssignObjCInterfacesInBlockPointer(
11146 LHSOPT: RHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11147 RHSOPT: LHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11148 BlockReturnType);
11149 };
11150
11151 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11152 return true;
11153
11154 if (LHSOPT->isObjCBuiltinType()) {
11155 return finish(RHSOPT->isObjCBuiltinType() ||
11156 RHSOPT->isObjCQualifiedIdType());
11157 }
11158
11159 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11160 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11161 // Use for block parameters previous type checking for compatibility.
11162 return finish(ObjCQualifiedIdTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT, compare: false) ||
11163 // Or corrected type checking as in non-compat mode.
11164 (!BlockReturnType &&
11165 ObjCQualifiedIdTypesAreCompatible(lhs: RHSOPT, rhs: LHSOPT, compare: false)));
11166 else
11167 return finish(ObjCQualifiedIdTypesAreCompatible(
11168 lhs: (BlockReturnType ? LHSOPT : RHSOPT),
11169 rhs: (BlockReturnType ? RHSOPT : LHSOPT), compare: false));
11170 }
11171
11172 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11173 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11174 if (LHS && RHS) { // We have 2 user-defined types.
11175 if (LHS != RHS) {
11176 if (LHS->getDecl()->isSuperClassOf(I: RHS->getDecl()))
11177 return finish(BlockReturnType);
11178 if (RHS->getDecl()->isSuperClassOf(I: LHS->getDecl()))
11179 return finish(!BlockReturnType);
11180 }
11181 else
11182 return true;
11183 }
11184 return false;
11185}
11186
11187/// Comparison routine for Objective-C protocols to be used with
11188/// llvm::array_pod_sort.
11189static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
11190 ObjCProtocolDecl * const *rhs) {
11191 return (*lhs)->getName().compare(RHS: (*rhs)->getName());
11192}
11193
11194/// getIntersectionOfProtocols - This routine finds the intersection of set
11195/// of protocols inherited from two distinct objective-c pointer objects with
11196/// the given common base.
11197/// It is used to build composite qualifier list of the composite type of
11198/// the conditional expression involving two objective-c pointer objects.
11199static
11200void getIntersectionOfProtocols(ASTContext &Context,
11201 const ObjCInterfaceDecl *CommonBase,
11202 const ObjCObjectPointerType *LHSOPT,
11203 const ObjCObjectPointerType *RHSOPT,
11204 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11205
11206 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11207 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11208 assert(LHS->getInterface() && "LHS must have an interface base");
11209 assert(RHS->getInterface() && "RHS must have an interface base");
11210
11211 // Add all of the protocols for the LHS.
11212 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
11213
11214 // Start with the protocol qualifiers.
11215 for (auto *proto : LHS->quals()) {
11216 Context.CollectInheritedProtocols(CDecl: proto, Protocols&: LHSProtocolSet);
11217 }
11218
11219 // Also add the protocols associated with the LHS interface.
11220 Context.CollectInheritedProtocols(CDecl: LHS->getInterface(), Protocols&: LHSProtocolSet);
11221
11222 // Add all of the protocols for the RHS.
11223 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
11224
11225 // Start with the protocol qualifiers.
11226 for (auto *proto : RHS->quals()) {
11227 Context.CollectInheritedProtocols(CDecl: proto, Protocols&: RHSProtocolSet);
11228 }
11229
11230 // Also add the protocols associated with the RHS interface.
11231 Context.CollectInheritedProtocols(CDecl: RHS->getInterface(), Protocols&: RHSProtocolSet);
11232
11233 // Compute the intersection of the collected protocol sets.
11234 for (auto *proto : LHSProtocolSet) {
11235 if (RHSProtocolSet.count(Ptr: proto))
11236 IntersectionSet.push_back(Elt: proto);
11237 }
11238
11239 // Compute the set of protocols that is implied by either the common type or
11240 // the protocols within the intersection.
11241 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
11242 Context.CollectInheritedProtocols(CDecl: CommonBase, Protocols&: ImpliedProtocols);
11243
11244 // Remove any implied protocols from the list of inherited protocols.
11245 if (!ImpliedProtocols.empty()) {
11246 llvm::erase_if(C&: IntersectionSet, P: [&](ObjCProtocolDecl *proto) -> bool {
11247 return ImpliedProtocols.contains(Ptr: proto);
11248 });
11249 }
11250
11251 // Sort the remaining protocols by name.
11252 llvm::array_pod_sort(Start: IntersectionSet.begin(), End: IntersectionSet.end(),
11253 Compare: compareObjCProtocolsByName);
11254}
11255
11256/// Determine whether the first type is a subtype of the second.
11257static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
11258 QualType rhs) {
11259 // Common case: two object pointers.
11260 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11261 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11262 if (lhsOPT && rhsOPT)
11263 return ctx.canAssignObjCInterfaces(LHSOPT: lhsOPT, RHSOPT: rhsOPT);
11264
11265 // Two block pointers.
11266 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11267 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11268 if (lhsBlock && rhsBlock)
11269 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11270
11271 // If either is an unqualified 'id' and the other is a block, it's
11272 // acceptable.
11273 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11274 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11275 return true;
11276
11277 return false;
11278}
11279
11280// Check that the given Objective-C type argument lists are equivalent.
11281static bool sameObjCTypeArgs(ASTContext &ctx,
11282 const ObjCInterfaceDecl *iface,
11283 ArrayRef<QualType> lhsArgs,
11284 ArrayRef<QualType> rhsArgs,
11285 bool stripKindOf) {
11286 if (lhsArgs.size() != rhsArgs.size())
11287 return false;
11288
11289 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11290 if (!typeParams)
11291 return false;
11292
11293 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11294 if (ctx.hasSameType(T1: lhsArgs[i], T2: rhsArgs[i]))
11295 continue;
11296
11297 switch (typeParams->begin()[i]->getVariance()) {
11298 case ObjCTypeParamVariance::Invariant:
11299 if (!stripKindOf ||
11300 !ctx.hasSameType(T1: lhsArgs[i].stripObjCKindOfType(ctx),
11301 T2: rhsArgs[i].stripObjCKindOfType(ctx))) {
11302 return false;
11303 }
11304 break;
11305
11306 case ObjCTypeParamVariance::Covariant:
11307 if (!canAssignObjCObjectTypes(ctx, lhs: lhsArgs[i], rhs: rhsArgs[i]))
11308 return false;
11309 break;
11310
11311 case ObjCTypeParamVariance::Contravariant:
11312 if (!canAssignObjCObjectTypes(ctx, lhs: rhsArgs[i], rhs: lhsArgs[i]))
11313 return false;
11314 break;
11315 }
11316 }
11317
11318 return true;
11319}
11320
11321QualType ASTContext::areCommonBaseCompatible(
11322 const ObjCObjectPointerType *Lptr,
11323 const ObjCObjectPointerType *Rptr) {
11324 const ObjCObjectType *LHS = Lptr->getObjectType();
11325 const ObjCObjectType *RHS = Rptr->getObjectType();
11326 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11327 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11328
11329 if (!LDecl || !RDecl)
11330 return {};
11331
11332 // When either LHS or RHS is a kindof type, we should return a kindof type.
11333 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11334 // kindof(A).
11335 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11336
11337 // Follow the left-hand side up the class hierarchy until we either hit a
11338 // root or find the RHS. Record the ancestors in case we don't find it.
11339 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11340 LHSAncestors;
11341 while (true) {
11342 // Record this ancestor. We'll need this if the common type isn't in the
11343 // path from the LHS to the root.
11344 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11345
11346 if (declaresSameEntity(D1: LHS->getInterface(), D2: RDecl)) {
11347 // Get the type arguments.
11348 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11349 bool anyChanges = false;
11350 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11351 // Both have type arguments, compare them.
11352 if (!sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11353 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHS->getTypeArgs(),
11354 /*stripKindOf=*/true))
11355 return {};
11356 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11357 // If only one has type arguments, the result will not have type
11358 // arguments.
11359 LHSTypeArgs = {};
11360 anyChanges = true;
11361 }
11362
11363 // Compute the intersection of protocols.
11364 SmallVector<ObjCProtocolDecl *, 8> Protocols;
11365 getIntersectionOfProtocols(Context&: *this, CommonBase: LHS->getInterface(), LHSOPT: Lptr, RHSOPT: Rptr,
11366 IntersectionSet&: Protocols);
11367 if (!Protocols.empty())
11368 anyChanges = true;
11369
11370 // If anything in the LHS will have changed, build a new result type.
11371 // If we need to return a kindof type but LHS is not a kindof type, we
11372 // build a new result type.
11373 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11374 QualType Result = getObjCInterfaceType(Decl: LHS->getInterface());
11375 Result = getObjCObjectType(baseType: Result, typeArgs: LHSTypeArgs, protocols: Protocols,
11376 isKindOf: anyKindOf || LHS->isKindOfType());
11377 return getObjCObjectPointerType(ObjectT: Result);
11378 }
11379
11380 return getObjCObjectPointerType(ObjectT: QualType(LHS, 0));
11381 }
11382
11383 // Find the superclass.
11384 QualType LHSSuperType = LHS->getSuperClassType();
11385 if (LHSSuperType.isNull())
11386 break;
11387
11388 LHS = LHSSuperType->castAs<ObjCObjectType>();
11389 }
11390
11391 // We didn't find anything by following the LHS to its root; now check
11392 // the RHS against the cached set of ancestors.
11393 while (true) {
11394 auto KnownLHS = LHSAncestors.find(Val: RHS->getInterface()->getCanonicalDecl());
11395 if (KnownLHS != LHSAncestors.end()) {
11396 LHS = KnownLHS->second;
11397
11398 // Get the type arguments.
11399 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11400 bool anyChanges = false;
11401 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11402 // Both have type arguments, compare them.
11403 if (!sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11404 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHS->getTypeArgs(),
11405 /*stripKindOf=*/true))
11406 return {};
11407 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11408 // If only one has type arguments, the result will not have type
11409 // arguments.
11410 RHSTypeArgs = {};
11411 anyChanges = true;
11412 }
11413
11414 // Compute the intersection of protocols.
11415 SmallVector<ObjCProtocolDecl *, 8> Protocols;
11416 getIntersectionOfProtocols(Context&: *this, CommonBase: RHS->getInterface(), LHSOPT: Lptr, RHSOPT: Rptr,
11417 IntersectionSet&: Protocols);
11418 if (!Protocols.empty())
11419 anyChanges = true;
11420
11421 // If we need to return a kindof type but RHS is not a kindof type, we
11422 // build a new result type.
11423 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11424 QualType Result = getObjCInterfaceType(Decl: RHS->getInterface());
11425 Result = getObjCObjectType(baseType: Result, typeArgs: RHSTypeArgs, protocols: Protocols,
11426 isKindOf: anyKindOf || RHS->isKindOfType());
11427 return getObjCObjectPointerType(ObjectT: Result);
11428 }
11429
11430 return getObjCObjectPointerType(ObjectT: QualType(RHS, 0));
11431 }
11432
11433 // Find the superclass of the RHS.
11434 QualType RHSSuperType = RHS->getSuperClassType();
11435 if (RHSSuperType.isNull())
11436 break;
11437
11438 RHS = RHSSuperType->castAs<ObjCObjectType>();
11439 }
11440
11441 return {};
11442}
11443
11444bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
11445 const ObjCObjectType *RHS) {
11446 assert(LHS->getInterface() && "LHS is not an interface type");
11447 assert(RHS->getInterface() && "RHS is not an interface type");
11448
11449 // Verify that the base decls are compatible: the RHS must be a subclass of
11450 // the LHS.
11451 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11452 bool IsSuperClass = LHSInterface->isSuperClassOf(I: RHS->getInterface());
11453 if (!IsSuperClass)
11454 return false;
11455
11456 // If the LHS has protocol qualifiers, determine whether all of them are
11457 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11458 // LHS).
11459 if (LHS->getNumProtocols() > 0) {
11460 // OK if conversion of LHS to SuperClass results in narrowing of types
11461 // ; i.e., SuperClass may implement at least one of the protocols
11462 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11463 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11464 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11465 CollectInheritedProtocols(CDecl: RHS->getInterface(), Protocols&: SuperClassInheritedProtocols);
11466 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11467 // qualifiers.
11468 for (auto *RHSPI : RHS->quals())
11469 CollectInheritedProtocols(CDecl: RHSPI, Protocols&: SuperClassInheritedProtocols);
11470 // If there is no protocols associated with RHS, it is not a match.
11471 if (SuperClassInheritedProtocols.empty())
11472 return false;
11473
11474 for (const auto *LHSProto : LHS->quals()) {
11475 bool SuperImplementsProtocol = false;
11476 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11477 if (SuperClassProto->lookupProtocolNamed(PName: LHSProto->getIdentifier())) {
11478 SuperImplementsProtocol = true;
11479 break;
11480 }
11481 if (!SuperImplementsProtocol)
11482 return false;
11483 }
11484 }
11485
11486 // If the LHS is specialized, we may need to check type arguments.
11487 if (LHS->isSpecialized()) {
11488 // Follow the superclass chain until we've matched the LHS class in the
11489 // hierarchy. This substitutes type arguments through.
11490 const ObjCObjectType *RHSSuper = RHS;
11491 while (!declaresSameEntity(D1: RHSSuper->getInterface(), D2: LHSInterface))
11492 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11493
11494 // If the RHS is specializd, compare type arguments.
11495 if (RHSSuper->isSpecialized() &&
11496 !sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11497 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHSSuper->getTypeArgs(),
11498 /*stripKindOf=*/true)) {
11499 return false;
11500 }
11501 }
11502
11503 return true;
11504}
11505
11506bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
11507 // get the "pointed to" types
11508 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11509 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11510
11511 if (!LHSOPT || !RHSOPT)
11512 return false;
11513
11514 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11515 canAssignObjCInterfaces(LHSOPT: RHSOPT, RHSOPT: LHSOPT);
11516}
11517
11518bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
11519 return canAssignObjCInterfaces(
11520 LHSOPT: getObjCObjectPointerType(ObjectT: To)->castAs<ObjCObjectPointerType>(),
11521 RHSOPT: getObjCObjectPointerType(ObjectT: From)->castAs<ObjCObjectPointerType>());
11522}
11523
11524/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11525/// both shall have the identically qualified version of a compatible type.
11526/// C99 6.2.7p1: Two types have compatible types if their types are the
11527/// same. See 6.7.[2,3,5] for additional rules.
11528bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
11529 bool CompareUnqualified) {
11530 if (getLangOpts().CPlusPlus)
11531 return hasSameType(T1: LHS, T2: RHS);
11532
11533 return !mergeTypes(LHS, RHS, OfBlockPointer: false, Unqualified: CompareUnqualified).isNull();
11534}
11535
11536bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
11537 return typesAreCompatible(LHS, RHS);
11538}
11539
11540bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
11541 return !mergeTypes(LHS, RHS, OfBlockPointer: true).isNull();
11542}
11543
11544/// mergeTransparentUnionType - if T is a transparent union type and a member
11545/// of T is compatible with SubType, return the merged type, else return
11546/// QualType()
11547QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
11548 bool OfBlockPointer,
11549 bool Unqualified) {
11550 if (const RecordType *UT = T->getAsUnionType()) {
11551 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11552 if (UD->hasAttr<TransparentUnionAttr>()) {
11553 for (const auto *I : UD->fields()) {
11554 QualType ET = I->getType().getUnqualifiedType();
11555 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11556 if (!MT.isNull())
11557 return MT;
11558 }
11559 }
11560 }
11561
11562 return {};
11563}
11564
11565/// mergeFunctionParameterTypes - merge two types which appear as function
11566/// parameter types
11567QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
11568 bool OfBlockPointer,
11569 bool Unqualified) {
11570 // GNU extension: two types are compatible if they appear as a function
11571 // argument, one of the types is a transparent union type and the other
11572 // type is compatible with a union member
11573 QualType lmerge = mergeTransparentUnionType(T: lhs, SubType: rhs, OfBlockPointer,
11574 Unqualified);
11575 if (!lmerge.isNull())
11576 return lmerge;
11577
11578 QualType rmerge = mergeTransparentUnionType(T: rhs, SubType: lhs, OfBlockPointer,
11579 Unqualified);
11580 if (!rmerge.isNull())
11581 return rmerge;
11582
11583 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11584}
11585
11586QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
11587 bool OfBlockPointer, bool Unqualified,
11588 bool AllowCXX,
11589 bool IsConditionalOperator) {
11590 const auto *lbase = lhs->castAs<FunctionType>();
11591 const auto *rbase = rhs->castAs<FunctionType>();
11592 const auto *lproto = dyn_cast<FunctionProtoType>(Val: lbase);
11593 const auto *rproto = dyn_cast<FunctionProtoType>(Val: rbase);
11594 bool allLTypes = true;
11595 bool allRTypes = true;
11596
11597 // Check return type
11598 QualType retType;
11599 if (OfBlockPointer) {
11600 QualType RHS = rbase->getReturnType();
11601 QualType LHS = lbase->getReturnType();
11602 bool UnqualifiedResult = Unqualified;
11603 if (!UnqualifiedResult)
11604 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11605 retType = mergeTypes(LHS, RHS, OfBlockPointer: true, Unqualified: UnqualifiedResult, BlockReturnType: true);
11606 }
11607 else
11608 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), OfBlockPointer: false,
11609 Unqualified);
11610 if (retType.isNull())
11611 return {};
11612
11613 if (Unqualified)
11614 retType = retType.getUnqualifiedType();
11615
11616 CanQualType LRetType = getCanonicalType(T: lbase->getReturnType());
11617 CanQualType RRetType = getCanonicalType(T: rbase->getReturnType());
11618 if (Unqualified) {
11619 LRetType = LRetType.getUnqualifiedType();
11620 RRetType = RRetType.getUnqualifiedType();
11621 }
11622
11623 if (getCanonicalType(T: retType) != LRetType)
11624 allLTypes = false;
11625 if (getCanonicalType(T: retType) != RRetType)
11626 allRTypes = false;
11627
11628 // FIXME: double check this
11629 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11630 // rbase->getRegParmAttr() != 0 &&
11631 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11632 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11633 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11634
11635 // Compatible functions must have compatible calling conventions
11636 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11637 return {};
11638
11639 // Regparm is part of the calling convention.
11640 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11641 return {};
11642 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11643 return {};
11644
11645 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11646 return {};
11647 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11648 return {};
11649 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11650 return {};
11651
11652 // When merging declarations, it's common for supplemental information like
11653 // attributes to only be present in one of the declarations, and we generally
11654 // want type merging to preserve the union of information. So a merged
11655 // function type should be noreturn if it was noreturn in *either* operand
11656 // type.
11657 //
11658 // But for the conditional operator, this is backwards. The result of the
11659 // operator could be either operand, and its type should conservatively
11660 // reflect that. So a function type in a composite type is noreturn only
11661 // if it's noreturn in *both* operand types.
11662 //
11663 // Arguably, noreturn is a kind of subtype, and the conditional operator
11664 // ought to produce the most specific common supertype of its operand types.
11665 // That would differ from this rule in contravariant positions. However,
11666 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11667 // as a practical matter, it would only affect C code that does abstraction of
11668 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11669 // say the least. So we use the simpler rule.
11670 bool NoReturn = IsConditionalOperator
11671 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11672 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11673 if (lbaseInfo.getNoReturn() != NoReturn)
11674 allLTypes = false;
11675 if (rbaseInfo.getNoReturn() != NoReturn)
11676 allRTypes = false;
11677
11678 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(noReturn: NoReturn);
11679
11680 std::optional<FunctionEffectSet> MergedFX;
11681
11682 if (lproto && rproto) { // two C99 style function prototypes
11683 assert((AllowCXX ||
11684 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11685 "C++ shouldn't be here");
11686 // Compatible functions must have the same number of parameters
11687 if (lproto->getNumParams() != rproto->getNumParams())
11688 return {};
11689
11690 // Variadic and non-variadic functions aren't compatible
11691 if (lproto->isVariadic() != rproto->isVariadic())
11692 return {};
11693
11694 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11695 return {};
11696
11697 // Function protos with different 'cfi_salt' values aren't compatible.
11698 if (lproto->getExtraAttributeInfo().CFISalt !=
11699 rproto->getExtraAttributeInfo().CFISalt)
11700 return {};
11701
11702 // Function effects are handled similarly to noreturn, see above.
11703 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11704 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11705 if (LHSFX != RHSFX) {
11706 if (IsConditionalOperator)
11707 MergedFX = FunctionEffectSet::getIntersection(LHS: LHSFX, RHS: RHSFX);
11708 else {
11709 FunctionEffectSet::Conflicts Errs;
11710 MergedFX = FunctionEffectSet::getUnion(LHS: LHSFX, RHS: RHSFX, Errs);
11711 // Here we're discarding a possible error due to conflicts in the effect
11712 // sets. But we're not in a context where we can report it. The
11713 // operation does however guarantee maintenance of invariants.
11714 }
11715 if (*MergedFX != LHSFX)
11716 allLTypes = false;
11717 if (*MergedFX != RHSFX)
11718 allRTypes = false;
11719 }
11720
11721 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
11722 bool canUseLeft, canUseRight;
11723 if (!mergeExtParameterInfo(FirstFnType: lproto, SecondFnType: rproto, CanUseFirst&: canUseLeft, CanUseSecond&: canUseRight,
11724 NewParamInfos&: newParamInfos))
11725 return {};
11726
11727 if (!canUseLeft)
11728 allLTypes = false;
11729 if (!canUseRight)
11730 allRTypes = false;
11731
11732 // Check parameter type compatibility
11733 SmallVector<QualType, 10> types;
11734 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11735 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11736 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11737 QualType paramType = mergeFunctionParameterTypes(
11738 lhs: lParamType, rhs: rParamType, OfBlockPointer, Unqualified);
11739 if (paramType.isNull())
11740 return {};
11741
11742 if (Unqualified)
11743 paramType = paramType.getUnqualifiedType();
11744
11745 types.push_back(Elt: paramType);
11746 if (Unqualified) {
11747 lParamType = lParamType.getUnqualifiedType();
11748 rParamType = rParamType.getUnqualifiedType();
11749 }
11750
11751 if (getCanonicalType(T: paramType) != getCanonicalType(T: lParamType))
11752 allLTypes = false;
11753 if (getCanonicalType(T: paramType) != getCanonicalType(T: rParamType))
11754 allRTypes = false;
11755 }
11756
11757 if (allLTypes) return lhs;
11758 if (allRTypes) return rhs;
11759
11760 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11761 EPI.ExtInfo = einfo;
11762 EPI.ExtParameterInfos =
11763 newParamInfos.empty() ? nullptr : newParamInfos.data();
11764 if (MergedFX)
11765 EPI.FunctionEffects = *MergedFX;
11766 return getFunctionType(ResultTy: retType, Args: types, EPI);
11767 }
11768
11769 if (lproto) allRTypes = false;
11770 if (rproto) allLTypes = false;
11771
11772 const FunctionProtoType *proto = lproto ? lproto : rproto;
11773 if (proto) {
11774 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11775 if (proto->isVariadic())
11776 return {};
11777 // Check that the types are compatible with the types that
11778 // would result from default argument promotions (C99 6.7.5.3p15).
11779 // The only types actually affected are promotable integer
11780 // types and floats, which would be passed as a different
11781 // type depending on whether the prototype is visible.
11782 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11783 QualType paramTy = proto->getParamType(i);
11784
11785 // Look at the converted type of enum types, since that is the type used
11786 // to pass enum values.
11787 if (const auto *ED = paramTy->getAsEnumDecl()) {
11788 paramTy = ED->getIntegerType();
11789 if (paramTy.isNull())
11790 return {};
11791 }
11792
11793 if (isPromotableIntegerType(T: paramTy) ||
11794 getCanonicalType(T: paramTy).getUnqualifiedType() == FloatTy)
11795 return {};
11796 }
11797
11798 if (allLTypes) return lhs;
11799 if (allRTypes) return rhs;
11800
11801 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
11802 EPI.ExtInfo = einfo;
11803 if (MergedFX)
11804 EPI.FunctionEffects = *MergedFX;
11805 return getFunctionType(ResultTy: retType, Args: proto->getParamTypes(), EPI);
11806 }
11807
11808 if (allLTypes) return lhs;
11809 if (allRTypes) return rhs;
11810 return getFunctionNoProtoType(ResultTy: retType, Info: einfo);
11811}
11812
11813/// Given that we have an enum type and a non-enum type, try to merge them.
11814static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11815 QualType other, bool isBlockReturnType) {
11816 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11817 // a signed integer type, or an unsigned integer type.
11818 // Compatibility is based on the underlying type, not the promotion
11819 // type.
11820 QualType underlyingType =
11821 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11822 if (underlyingType.isNull())
11823 return {};
11824 if (Context.hasSameType(T1: underlyingType, T2: other))
11825 return other;
11826
11827 // In block return types, we're more permissive and accept any
11828 // integral type of the same size.
11829 if (isBlockReturnType && other->isIntegerType() &&
11830 Context.getTypeSize(T: underlyingType) == Context.getTypeSize(T: other))
11831 return other;
11832
11833 return {};
11834}
11835
11836QualType ASTContext::mergeTagDefinitions(QualType LHS, QualType RHS) {
11837 // C17 and earlier and C++ disallow two tag definitions within the same TU
11838 // from being compatible.
11839 if (LangOpts.CPlusPlus || !LangOpts.C23)
11840 return {};
11841
11842 // Nameless tags are comparable only within outer definitions. At the top
11843 // level they are not comparable.
11844 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11845 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11846 return {};
11847
11848 // C23, on the other hand, requires the members to be "the same enough", so
11849 // we use a structural equivalence check.
11850 StructuralEquivalenceContext::NonEquivalentDeclSet NonEquivalentDecls;
11851 StructuralEquivalenceContext Ctx(
11852 getLangOpts(), *this, *this, NonEquivalentDecls,
11853 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11854 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11855 return Ctx.IsEquivalent(T1: LHS, T2: RHS) ? LHS : QualType{};
11856}
11857
11858std::optional<QualType> ASTContext::tryMergeOverflowBehaviorTypes(
11859 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11860 bool BlockReturnType, bool IsConditionalOperator) {
11861 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11862 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11863
11864 if (!LHSOBT && !RHSOBT)
11865 return std::nullopt;
11866
11867 if (LHSOBT) {
11868 if (RHSOBT) {
11869 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11870 return QualType();
11871
11872 QualType MergedUnderlying = mergeTypes(
11873 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11874 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11875
11876 if (MergedUnderlying.isNull())
11877 return QualType();
11878
11879 if (getCanonicalType(T: LHSOBT) == getCanonicalType(T: RHSOBT)) {
11880 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11881 return getCommonSugaredType(X: LHS, Y: RHS);
11882 return getOverflowBehaviorType(
11883 Kind: LHSOBT->getBehaviorKind(),
11884 Underlying: getCanonicalType(T: LHSOBT->getUnderlyingType()));
11885 }
11886
11887 // For different underlying types that successfully merge, wrap the
11888 // merged underlying type with the common overflow behavior
11889 return getOverflowBehaviorType(Kind: LHSOBT->getBehaviorKind(),
11890 Underlying: MergedUnderlying);
11891 }
11892 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11893 Unqualified, BlockReturnType, IsConditionalOperator);
11894 }
11895
11896 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11897 Unqualified, BlockReturnType, IsConditionalOperator);
11898}
11899
11900QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11901 bool Unqualified, bool BlockReturnType,
11902 bool IsConditionalOperator) {
11903 // For C++ we will not reach this code with reference types (see below),
11904 // for OpenMP variant call overloading we might.
11905 //
11906 // C++ [expr]: If an expression initially has the type "reference to T", the
11907 // type is adjusted to "T" prior to any further analysis, the expression
11908 // designates the object or function denoted by the reference, and the
11909 // expression is an lvalue unless the reference is an rvalue reference and
11910 // the expression is a function call (possibly inside parentheses).
11911 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11912 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11913 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11914 LHS->getTypeClass() == RHS->getTypeClass())
11915 return mergeTypes(LHS: LHSRefTy->getPointeeType(), RHS: RHSRefTy->getPointeeType(),
11916 OfBlockPointer, Unqualified, BlockReturnType);
11917 if (LHSRefTy || RHSRefTy)
11918 return {};
11919
11920 if (std::optional<QualType> MergedOBT =
11921 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11922 BlockReturnType, IsConditionalOperator))
11923 return *MergedOBT;
11924
11925 if (Unqualified) {
11926 LHS = LHS.getUnqualifiedType();
11927 RHS = RHS.getUnqualifiedType();
11928 }
11929
11930 QualType LHSCan = getCanonicalType(T: LHS),
11931 RHSCan = getCanonicalType(T: RHS);
11932
11933 // If two types are identical, they are compatible.
11934 if (LHSCan == RHSCan)
11935 return LHS;
11936
11937 // If the qualifiers are different, the types aren't compatible... mostly.
11938 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11939 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11940 if (LQuals != RQuals) {
11941 // If any of these qualifiers are different, we have a type
11942 // mismatch.
11943 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11944 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11945 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11946 !LQuals.getPointerAuth().isEquivalent(Other: RQuals.getPointerAuth()) ||
11947 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11948 return {};
11949
11950 // Exactly one GC qualifier difference is allowed: __strong is
11951 // okay if the other type has no GC qualifier but is an Objective
11952 // C object pointer (i.e. implicitly strong by default). We fix
11953 // this by pretending that the unqualified type was actually
11954 // qualified __strong.
11955 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11956 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11957 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11958
11959 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11960 return {};
11961
11962 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11963 return mergeTypes(LHS, RHS: getObjCGCQualType(T: RHS, GCAttr: Qualifiers::Strong));
11964 }
11965 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11966 return mergeTypes(LHS: getObjCGCQualType(T: LHS, GCAttr: Qualifiers::Strong), RHS);
11967 }
11968 return {};
11969 }
11970
11971 // Okay, qualifiers are equal.
11972
11973 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11974 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11975
11976 // We want to consider the two function types to be the same for these
11977 // comparisons, just force one to the other.
11978 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11979 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11980
11981 // Same as above for arrays
11982 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11983 LHSClass = Type::ConstantArray;
11984 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11985 RHSClass = Type::ConstantArray;
11986
11987 // ObjCInterfaces are just specialized ObjCObjects.
11988 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11989 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11990
11991 // Canonicalize ExtVector -> Vector.
11992 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11993 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11994
11995 // If the canonical type classes don't match.
11996 if (LHSClass != RHSClass) {
11997 // Note that we only have special rules for turning block enum
11998 // returns into block int returns, not vice-versa.
11999 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
12000 return mergeEnumWithInteger(Context&: *this, ET: ETy, other: RHS, isBlockReturnType: false);
12001 }
12002 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
12003 return mergeEnumWithInteger(Context&: *this, ET: ETy, other: LHS, isBlockReturnType: BlockReturnType);
12004 }
12005 // allow block pointer type to match an 'id' type.
12006 if (OfBlockPointer && !BlockReturnType) {
12007 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
12008 return LHS;
12009 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
12010 return RHS;
12011 }
12012 // Allow __auto_type to match anything; it merges to the type with more
12013 // information.
12014 if (const auto *AT = LHS->getAs<AutoType>()) {
12015 if (!AT->isDeduced() && AT->isGNUAutoType())
12016 return RHS;
12017 }
12018 if (const auto *AT = RHS->getAs<AutoType>()) {
12019 if (!AT->isDeduced() && AT->isGNUAutoType())
12020 return LHS;
12021 }
12022 return {};
12023 }
12024
12025 // The canonical type classes match.
12026 switch (LHSClass) {
12027#define TYPE(Class, Base)
12028#define ABSTRACT_TYPE(Class, Base)
12029#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
12030#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
12031#define DEPENDENT_TYPE(Class, Base) case Type::Class:
12032#include "clang/AST/TypeNodes.inc"
12033 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
12034
12035 case Type::Auto:
12036 case Type::DeducedTemplateSpecialization:
12037 case Type::LValueReference:
12038 case Type::RValueReference:
12039 case Type::MemberPointer:
12040 llvm_unreachable("C++ should never be in mergeTypes");
12041
12042 case Type::ObjCInterface:
12043 case Type::IncompleteArray:
12044 case Type::VariableArray:
12045 case Type::FunctionProto:
12046 case Type::ExtVector:
12047 case Type::OverflowBehavior:
12048 llvm_unreachable("Types are eliminated above");
12049
12050 case Type::Pointer:
12051 {
12052 // Merge two pointer types, while trying to preserve typedef info
12053 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
12054 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
12055 if (Unqualified) {
12056 LHSPointee = LHSPointee.getUnqualifiedType();
12057 RHSPointee = RHSPointee.getUnqualifiedType();
12058 }
12059 QualType ResultType = mergeTypes(LHS: LHSPointee, RHS: RHSPointee, OfBlockPointer: false,
12060 Unqualified);
12061 if (ResultType.isNull())
12062 return {};
12063 if (getCanonicalType(T: LHSPointee) == getCanonicalType(T: ResultType))
12064 return LHS;
12065 if (getCanonicalType(T: RHSPointee) == getCanonicalType(T: ResultType))
12066 return RHS;
12067 return getPointerType(T: ResultType);
12068 }
12069 case Type::BlockPointer:
12070 {
12071 // Merge two block pointer types, while trying to preserve typedef info
12072 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
12073 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
12074 if (Unqualified) {
12075 LHSPointee = LHSPointee.getUnqualifiedType();
12076 RHSPointee = RHSPointee.getUnqualifiedType();
12077 }
12078 if (getLangOpts().OpenCL) {
12079 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
12080 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
12081 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
12082 // 6.12.5) thus the following check is asymmetric.
12083 if (!LHSPteeQual.isAddressSpaceSupersetOf(other: RHSPteeQual, Ctx: *this))
12084 return {};
12085 LHSPteeQual.removeAddressSpace();
12086 RHSPteeQual.removeAddressSpace();
12087 LHSPointee =
12088 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12089 RHSPointee =
12090 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12091 }
12092 QualType ResultType = mergeTypes(LHS: LHSPointee, RHS: RHSPointee, OfBlockPointer,
12093 Unqualified);
12094 if (ResultType.isNull())
12095 return {};
12096 if (getCanonicalType(T: LHSPointee) == getCanonicalType(T: ResultType))
12097 return LHS;
12098 if (getCanonicalType(T: RHSPointee) == getCanonicalType(T: ResultType))
12099 return RHS;
12100 return getBlockPointerType(T: ResultType);
12101 }
12102 case Type::Atomic:
12103 {
12104 // Merge two pointer types, while trying to preserve typedef info
12105 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12106 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12107 if (Unqualified) {
12108 LHSValue = LHSValue.getUnqualifiedType();
12109 RHSValue = RHSValue.getUnqualifiedType();
12110 }
12111 QualType ResultType = mergeTypes(LHS: LHSValue, RHS: RHSValue, OfBlockPointer: false,
12112 Unqualified);
12113 if (ResultType.isNull())
12114 return {};
12115 if (getCanonicalType(T: LHSValue) == getCanonicalType(T: ResultType))
12116 return LHS;
12117 if (getCanonicalType(T: RHSValue) == getCanonicalType(T: ResultType))
12118 return RHS;
12119 return getAtomicType(T: ResultType);
12120 }
12121 case Type::ConstantArray:
12122 {
12123 const ConstantArrayType* LCAT = getAsConstantArrayType(T: LHS);
12124 const ConstantArrayType* RCAT = getAsConstantArrayType(T: RHS);
12125 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12126 return {};
12127
12128 QualType LHSElem = getAsArrayType(T: LHS)->getElementType();
12129 QualType RHSElem = getAsArrayType(T: RHS)->getElementType();
12130 if (Unqualified) {
12131 LHSElem = LHSElem.getUnqualifiedType();
12132 RHSElem = RHSElem.getUnqualifiedType();
12133 }
12134
12135 QualType ResultType = mergeTypes(LHS: LHSElem, RHS: RHSElem, OfBlockPointer: false, Unqualified);
12136 if (ResultType.isNull())
12137 return {};
12138
12139 const VariableArrayType* LVAT = getAsVariableArrayType(T: LHS);
12140 const VariableArrayType* RVAT = getAsVariableArrayType(T: RHS);
12141
12142 // If either side is a variable array, and both are complete, check whether
12143 // the current dimension is definite.
12144 if (LVAT || RVAT) {
12145 auto SizeFetch = [this](const VariableArrayType* VAT,
12146 const ConstantArrayType* CAT)
12147 -> std::pair<bool,llvm::APInt> {
12148 if (VAT) {
12149 std::optional<llvm::APSInt> TheInt;
12150 Expr *E = VAT->getSizeExpr();
12151 if (E && (TheInt = E->getIntegerConstantExpr(Ctx: *this)))
12152 return std::make_pair(x: true, y&: *TheInt);
12153 return std::make_pair(x: false, y: llvm::APSInt());
12154 }
12155 if (CAT)
12156 return std::make_pair(x: true, y: CAT->getSize());
12157 return std::make_pair(x: false, y: llvm::APInt());
12158 };
12159
12160 bool HaveLSize, HaveRSize;
12161 llvm::APInt LSize, RSize;
12162 std::tie(args&: HaveLSize, args&: LSize) = SizeFetch(LVAT, LCAT);
12163 std::tie(args&: HaveRSize, args&: RSize) = SizeFetch(RVAT, RCAT);
12164 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(I1: LSize, I2: RSize))
12165 return {}; // Definite, but unequal, array dimension
12166 }
12167
12168 if (LCAT && getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType))
12169 return LHS;
12170 if (RCAT && getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType))
12171 return RHS;
12172 if (LCAT)
12173 return getConstantArrayType(EltTy: ResultType, ArySizeIn: LCAT->getSize(),
12174 SizeExpr: LCAT->getSizeExpr(), ASM: ArraySizeModifier(), IndexTypeQuals: 0);
12175 if (RCAT)
12176 return getConstantArrayType(EltTy: ResultType, ArySizeIn: RCAT->getSize(),
12177 SizeExpr: RCAT->getSizeExpr(), ASM: ArraySizeModifier(), IndexTypeQuals: 0);
12178 if (LVAT && getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType))
12179 return LHS;
12180 if (RVAT && getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType))
12181 return RHS;
12182 if (LVAT) {
12183 // FIXME: This isn't correct! But tricky to implement because
12184 // the array's size has to be the size of LHS, but the type
12185 // has to be different.
12186 return LHS;
12187 }
12188 if (RVAT) {
12189 // FIXME: This isn't correct! But tricky to implement because
12190 // the array's size has to be the size of RHS, but the type
12191 // has to be different.
12192 return RHS;
12193 }
12194 if (getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType)) return LHS;
12195 if (getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType)) return RHS;
12196 return getIncompleteArrayType(elementType: ResultType, ASM: ArraySizeModifier(), elementTypeQuals: 0);
12197 }
12198 case Type::FunctionNoProto:
12199 return mergeFunctionTypes(lhs: LHS, rhs: RHS, OfBlockPointer, Unqualified,
12200 /*AllowCXX=*/false, IsConditionalOperator);
12201 case Type::Record:
12202 case Type::Enum:
12203 return mergeTagDefinitions(LHS, RHS);
12204 case Type::Builtin:
12205 // Only exactly equal builtin types are compatible, which is tested above.
12206 return {};
12207 case Type::Complex:
12208 // Distinct complex types are incompatible.
12209 return {};
12210 case Type::Vector:
12211 // FIXME: The merged type should be an ExtVector!
12212 if (areCompatVectorTypes(LHS: LHSCan->castAs<VectorType>(),
12213 RHS: RHSCan->castAs<VectorType>()))
12214 return LHS;
12215 return {};
12216 case Type::ConstantMatrix:
12217 if (areCompatMatrixTypes(LHS: LHSCan->castAs<ConstantMatrixType>(),
12218 RHS: RHSCan->castAs<ConstantMatrixType>()))
12219 return LHS;
12220 return {};
12221 case Type::ObjCObject: {
12222 // Check if the types are assignment compatible.
12223 // FIXME: This should be type compatibility, e.g. whether
12224 // "LHS x; RHS x;" at global scope is legal.
12225 if (canAssignObjCInterfaces(LHS: LHS->castAs<ObjCObjectType>(),
12226 RHS: RHS->castAs<ObjCObjectType>()))
12227 return LHS;
12228 return {};
12229 }
12230 case Type::ObjCObjectPointer:
12231 if (OfBlockPointer) {
12232 if (canAssignObjCInterfacesInBlockPointer(
12233 LHSOPT: LHS->castAs<ObjCObjectPointerType>(),
12234 RHSOPT: RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12235 return LHS;
12236 return {};
12237 }
12238 if (canAssignObjCInterfaces(LHSOPT: LHS->castAs<ObjCObjectPointerType>(),
12239 RHSOPT: RHS->castAs<ObjCObjectPointerType>()))
12240 return LHS;
12241 return {};
12242 case Type::Pipe:
12243 assert(LHS != RHS &&
12244 "Equivalent pipe types should have already been handled!");
12245 return {};
12246 case Type::ArrayParameter:
12247 assert(LHS != RHS &&
12248 "Equivalent ArrayParameter types should have already been handled!");
12249 return {};
12250 case Type::BitInt: {
12251 // Merge two bit-precise int types, while trying to preserve typedef info.
12252 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12253 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12254 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12255 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12256
12257 // Like unsigned/int, shouldn't have a type if they don't match.
12258 if (LHSUnsigned != RHSUnsigned)
12259 return {};
12260
12261 if (LHSBits != RHSBits)
12262 return {};
12263 return LHS;
12264 }
12265 case Type::HLSLAttributedResource: {
12266 const HLSLAttributedResourceType *LHSTy =
12267 LHS->castAs<HLSLAttributedResourceType>();
12268 const HLSLAttributedResourceType *RHSTy =
12269 RHS->castAs<HLSLAttributedResourceType>();
12270 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12271 LHSTy->getWrappedType()->isHLSLResourceType() &&
12272 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12273
12274 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12275 LHSTy->getContainedType() == RHSTy->getContainedType())
12276 return LHS;
12277 return {};
12278 }
12279 case Type::HLSLInlineSpirv:
12280 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12281 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12282
12283 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12284 LHSTy->getSize() == RHSTy->getSize() &&
12285 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12286 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12287 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12288 return {};
12289
12290 return LHS;
12291 }
12292 return {};
12293 }
12294
12295 llvm_unreachable("Invalid Type::Class!");
12296}
12297
12298bool ASTContext::mergeExtParameterInfo(
12299 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12300 bool &CanUseFirst, bool &CanUseSecond,
12301 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
12302 assert(NewParamInfos.empty() && "param info list not empty");
12303 CanUseFirst = CanUseSecond = true;
12304 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12305 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12306
12307 // Fast path: if the first type doesn't have ext parameter infos,
12308 // we match if and only if the second type also doesn't have them.
12309 if (!FirstHasInfo && !SecondHasInfo)
12310 return true;
12311
12312 bool NeedParamInfo = false;
12313 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12314 : SecondFnType->getExtParameterInfos().size();
12315
12316 for (size_t I = 0; I < E; ++I) {
12317 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12318 if (FirstHasInfo)
12319 FirstParam = FirstFnType->getExtParameterInfo(I);
12320 if (SecondHasInfo)
12321 SecondParam = SecondFnType->getExtParameterInfo(I);
12322
12323 // Cannot merge unless everything except the noescape flag matches.
12324 if (FirstParam.withIsNoEscape(NoEscape: false) != SecondParam.withIsNoEscape(NoEscape: false))
12325 return false;
12326
12327 bool FirstNoEscape = FirstParam.isNoEscape();
12328 bool SecondNoEscape = SecondParam.isNoEscape();
12329 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12330 NewParamInfos.push_back(Elt: FirstParam.withIsNoEscape(NoEscape: IsNoEscape));
12331 if (NewParamInfos.back().getOpaqueValue())
12332 NeedParamInfo = true;
12333 if (FirstNoEscape != IsNoEscape)
12334 CanUseFirst = false;
12335 if (SecondNoEscape != IsNoEscape)
12336 CanUseSecond = false;
12337 }
12338
12339 if (!NeedParamInfo)
12340 NewParamInfos.clear();
12341
12342 return true;
12343}
12344
12345void ASTContext::ResetObjCLayout(const ObjCInterfaceDecl *D) {
12346 if (auto It = ObjCLayouts.find(Val: D); It != ObjCLayouts.end()) {
12347 It->second = nullptr;
12348 for (auto *SubClass : ObjCSubClasses.lookup(Val: D))
12349 ResetObjCLayout(D: SubClass);
12350 }
12351}
12352
12353/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12354/// 'RHS' attributes and returns the merged version; including for function
12355/// return types.
12356QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
12357 QualType LHSCan = getCanonicalType(T: LHS),
12358 RHSCan = getCanonicalType(T: RHS);
12359 // If two types are identical, they are compatible.
12360 if (LHSCan == RHSCan)
12361 return LHS;
12362 if (RHSCan->isFunctionType()) {
12363 if (!LHSCan->isFunctionType())
12364 return {};
12365 QualType OldReturnType =
12366 cast<FunctionType>(Val: RHSCan.getTypePtr())->getReturnType();
12367 QualType NewReturnType =
12368 cast<FunctionType>(Val: LHSCan.getTypePtr())->getReturnType();
12369 QualType ResReturnType =
12370 mergeObjCGCQualifiers(LHS: NewReturnType, RHS: OldReturnType);
12371 if (ResReturnType.isNull())
12372 return {};
12373 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12374 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12375 // In either case, use OldReturnType to build the new function type.
12376 const auto *F = LHS->castAs<FunctionType>();
12377 if (const auto *FPT = cast<FunctionProtoType>(Val: F)) {
12378 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12379 EPI.ExtInfo = getFunctionExtInfo(t: LHS);
12380 QualType ResultType =
12381 getFunctionType(ResultTy: OldReturnType, Args: FPT->getParamTypes(), EPI);
12382 return ResultType;
12383 }
12384 }
12385 return {};
12386 }
12387
12388 // If the qualifiers are different, the types can still be merged.
12389 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12390 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12391 if (LQuals != RQuals) {
12392 // If any of these qualifiers are different, we have a type mismatch.
12393 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12394 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12395 return {};
12396
12397 // Exactly one GC qualifier difference is allowed: __strong is
12398 // okay if the other type has no GC qualifier but is an Objective
12399 // C object pointer (i.e. implicitly strong by default). We fix
12400 // this by pretending that the unqualified type was actually
12401 // qualified __strong.
12402 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12403 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12404 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12405
12406 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12407 return {};
12408
12409 if (GC_L == Qualifiers::Strong)
12410 return LHS;
12411 if (GC_R == Qualifiers::Strong)
12412 return RHS;
12413 return {};
12414 }
12415
12416 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12417 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12418 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12419 QualType ResQT = mergeObjCGCQualifiers(LHS: LHSBaseQT, RHS: RHSBaseQT);
12420 if (ResQT == LHSBaseQT)
12421 return LHS;
12422 if (ResQT == RHSBaseQT)
12423 return RHS;
12424 }
12425 return {};
12426}
12427
12428//===----------------------------------------------------------------------===//
12429// Integer Predicates
12430//===----------------------------------------------------------------------===//
12431
12432unsigned ASTContext::getIntWidth(QualType T) const {
12433 if (const auto *ED = T->getAsEnumDecl())
12434 T = ED->getIntegerType();
12435 if (T->isBooleanType())
12436 return 1;
12437 if (const auto *EIT = T->getAs<BitIntType>())
12438 return EIT->getNumBits();
12439 // For builtin types, just use the standard type sizing method
12440 return (unsigned)getTypeSize(T);
12441}
12442
12443QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
12444 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12445 T->isFixedPointType()) &&
12446 "Unexpected type");
12447
12448 // Turn <4 x signed int> -> <4 x unsigned int>
12449 if (const auto *VTy = T->getAs<VectorType>())
12450 return getVectorType(vecType: getCorrespondingUnsignedType(T: VTy->getElementType()),
12451 NumElts: VTy->getNumElements(), VecKind: VTy->getVectorKind());
12452
12453 // For _BitInt, return an unsigned _BitInt with same width.
12454 if (const auto *EITy = T->getAs<BitIntType>())
12455 return getBitIntType(/*Unsigned=*/IsUnsigned: true, NumBits: EITy->getNumBits());
12456
12457 // For the overflow behavior types, construct a new unsigned variant
12458 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12459 return getOverflowBehaviorType(
12460 Kind: OBT->getBehaviorKind(),
12461 Underlying: getCorrespondingUnsignedType(T: OBT->getUnderlyingType()));
12462
12463 // For enums, get the underlying integer type of the enum, and let the general
12464 // integer type signchanging code handle it.
12465 if (const auto *ED = T->getAsEnumDecl())
12466 T = ED->getIntegerType();
12467
12468 switch (T->castAs<BuiltinType>()->getKind()) {
12469 case BuiltinType::Char_U:
12470 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12471 case BuiltinType::Char_S:
12472 case BuiltinType::SChar:
12473 case BuiltinType::Char8:
12474 return UnsignedCharTy;
12475 case BuiltinType::Short:
12476 return UnsignedShortTy;
12477 case BuiltinType::Int:
12478 return UnsignedIntTy;
12479 case BuiltinType::Long:
12480 return UnsignedLongTy;
12481 case BuiltinType::LongLong:
12482 return UnsignedLongLongTy;
12483 case BuiltinType::Int128:
12484 return UnsignedInt128Ty;
12485 // wchar_t is special. It is either signed or not, but when it's signed,
12486 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12487 // version of its underlying type instead.
12488 case BuiltinType::WChar_S:
12489 return getUnsignedWCharType();
12490
12491 case BuiltinType::ShortAccum:
12492 return UnsignedShortAccumTy;
12493 case BuiltinType::Accum:
12494 return UnsignedAccumTy;
12495 case BuiltinType::LongAccum:
12496 return UnsignedLongAccumTy;
12497 case BuiltinType::SatShortAccum:
12498 return SatUnsignedShortAccumTy;
12499 case BuiltinType::SatAccum:
12500 return SatUnsignedAccumTy;
12501 case BuiltinType::SatLongAccum:
12502 return SatUnsignedLongAccumTy;
12503 case BuiltinType::ShortFract:
12504 return UnsignedShortFractTy;
12505 case BuiltinType::Fract:
12506 return UnsignedFractTy;
12507 case BuiltinType::LongFract:
12508 return UnsignedLongFractTy;
12509 case BuiltinType::SatShortFract:
12510 return SatUnsignedShortFractTy;
12511 case BuiltinType::SatFract:
12512 return SatUnsignedFractTy;
12513 case BuiltinType::SatLongFract:
12514 return SatUnsignedLongFractTy;
12515 default:
12516 assert((T->hasUnsignedIntegerRepresentation() ||
12517 T->isUnsignedFixedPointType()) &&
12518 "Unexpected signed integer or fixed point type");
12519 return T;
12520 }
12521}
12522
12523QualType ASTContext::getCorrespondingSignedType(QualType T) const {
12524 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12525 T->isFixedPointType()) &&
12526 "Unexpected type");
12527
12528 // Turn <4 x unsigned int> -> <4 x signed int>
12529 if (const auto *VTy = T->getAs<VectorType>())
12530 return getVectorType(vecType: getCorrespondingSignedType(T: VTy->getElementType()),
12531 NumElts: VTy->getNumElements(), VecKind: VTy->getVectorKind());
12532
12533 // For _BitInt, return a signed _BitInt with same width.
12534 if (const auto *EITy = T->getAs<BitIntType>())
12535 return getBitIntType(/*Unsigned=*/IsUnsigned: false, NumBits: EITy->getNumBits());
12536
12537 // For enums, get the underlying integer type of the enum, and let the general
12538 // integer type signchanging code handle it.
12539 if (const auto *ED = T->getAsEnumDecl())
12540 T = ED->getIntegerType();
12541
12542 switch (T->castAs<BuiltinType>()->getKind()) {
12543 case BuiltinType::Char_S:
12544 // Plain `char` is mapped to `signed char` even if it's already signed
12545 case BuiltinType::Char_U:
12546 case BuiltinType::UChar:
12547 case BuiltinType::Char8:
12548 return SignedCharTy;
12549 case BuiltinType::UShort:
12550 return ShortTy;
12551 case BuiltinType::UInt:
12552 return IntTy;
12553 case BuiltinType::ULong:
12554 return LongTy;
12555 case BuiltinType::ULongLong:
12556 return LongLongTy;
12557 case BuiltinType::UInt128:
12558 return Int128Ty;
12559 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12560 // there's no matching "signed wchar_t". Therefore we return the signed
12561 // version of its underlying type instead.
12562 case BuiltinType::WChar_U:
12563 return getSignedWCharType();
12564
12565 case BuiltinType::UShortAccum:
12566 return ShortAccumTy;
12567 case BuiltinType::UAccum:
12568 return AccumTy;
12569 case BuiltinType::ULongAccum:
12570 return LongAccumTy;
12571 case BuiltinType::SatUShortAccum:
12572 return SatShortAccumTy;
12573 case BuiltinType::SatUAccum:
12574 return SatAccumTy;
12575 case BuiltinType::SatULongAccum:
12576 return SatLongAccumTy;
12577 case BuiltinType::UShortFract:
12578 return ShortFractTy;
12579 case BuiltinType::UFract:
12580 return FractTy;
12581 case BuiltinType::ULongFract:
12582 return LongFractTy;
12583 case BuiltinType::SatUShortFract:
12584 return SatShortFractTy;
12585 case BuiltinType::SatUFract:
12586 return SatFractTy;
12587 case BuiltinType::SatULongFract:
12588 return SatLongFractTy;
12589 default:
12590 assert(
12591 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12592 "Unexpected signed integer or fixed point type");
12593 return T;
12594 }
12595}
12596
12597ASTMutationListener::~ASTMutationListener() = default;
12598
12599void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
12600 QualType ReturnType) {}
12601
12602//===----------------------------------------------------------------------===//
12603// Builtin Type Computation
12604//===----------------------------------------------------------------------===//
12605
12606/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12607/// pointer over the consumed characters. This returns the resultant type. If
12608/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12609/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12610/// a vector of "i*".
12611///
12612/// RequiresICE is filled in on return to indicate whether the value is required
12613/// to be an Integer Constant Expression.
12614static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12615 ASTContext::GetBuiltinTypeError &Error,
12616 bool &RequiresICE,
12617 bool AllowTypeModifiers) {
12618 // Modifiers.
12619 int HowLong = 0;
12620 bool Signed = false, Unsigned = false;
12621 bool IsChar = false, IsShort = false;
12622 RequiresICE = false;
12623
12624 // Read the prefixed modifiers first.
12625 bool Done = false;
12626 #ifndef NDEBUG
12627 bool IsSpecial = false;
12628 #endif
12629 while (!Done) {
12630 switch (*Str++) {
12631 default: Done = true; --Str; break;
12632 case 'I':
12633 RequiresICE = true;
12634 break;
12635 case 'S':
12636 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12637 assert(!Signed && "Can't use 'S' modifier multiple times!");
12638 Signed = true;
12639 break;
12640 case 'U':
12641 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12642 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12643 Unsigned = true;
12644 break;
12645 case 'B':
12646 // This modifier represents int8 type (byte-width).
12647 assert(!IsSpecial &&
12648 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12649 assert(HowLong == 0 && "Can't use both 'L' and 'B' modifiers!");
12650#ifndef NDEBUG
12651 IsSpecial = true;
12652#endif
12653 IsChar = true;
12654 break;
12655 case 'T':
12656 // This modifier represents int16 type (short-width).
12657 assert(!IsSpecial &&
12658 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12659 assert(HowLong == 0 && "Can't use both 'L' and 'T' modifiers!");
12660#ifndef NDEBUG
12661 IsSpecial = true;
12662#endif
12663 IsShort = true;
12664 break;
12665 case 'L':
12666 assert(!IsSpecial &&
12667 "Can't use 'L' with 'W', 'N', 'Z', 'O', 'B', or 'T' modifiers");
12668 assert(HowLong <= 2 && "Can't have LLLL modifier");
12669 ++HowLong;
12670 break;
12671 case 'N':
12672 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12673 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12674 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12675 #ifndef NDEBUG
12676 IsSpecial = true;
12677 #endif
12678 if (Context.getTargetInfo().getLongWidth() == 32)
12679 ++HowLong;
12680 break;
12681 case 'W':
12682 // This modifier represents int64 type.
12683 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12684 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12685 #ifndef NDEBUG
12686 IsSpecial = true;
12687 #endif
12688 switch (Context.getTargetInfo().getInt64Type()) {
12689 default:
12690 llvm_unreachable("Unexpected integer type");
12691 case TargetInfo::SignedLong:
12692 HowLong = 1;
12693 break;
12694 case TargetInfo::SignedLongLong:
12695 HowLong = 2;
12696 break;
12697 }
12698 break;
12699 case 'Z':
12700 // This modifier represents int32 type.
12701 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12702 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12703 #ifndef NDEBUG
12704 IsSpecial = true;
12705 #endif
12706 switch (Context.getTargetInfo().getIntTypeByWidth(BitWidth: 32, IsSigned: true)) {
12707 default:
12708 llvm_unreachable("Unexpected integer type");
12709 case TargetInfo::SignedInt:
12710 HowLong = 0;
12711 break;
12712 case TargetInfo::SignedLong:
12713 HowLong = 1;
12714 break;
12715 case TargetInfo::SignedLongLong:
12716 HowLong = 2;
12717 break;
12718 }
12719 break;
12720 case 'O':
12721 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12722 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12723 #ifndef NDEBUG
12724 IsSpecial = true;
12725 #endif
12726 if (Context.getLangOpts().OpenCL)
12727 HowLong = 1;
12728 else
12729 HowLong = 2;
12730 break;
12731 }
12732 }
12733
12734 QualType Type;
12735
12736 // Read the base type.
12737 switch (*Str++) {
12738 default:
12739 llvm_unreachable("Unknown builtin type letter!");
12740 case 'x':
12741 assert(HowLong == 0 && !Signed && !Unsigned &&
12742 "Bad modifiers used with 'x'!");
12743 Type = Context.Float16Ty;
12744 break;
12745 case 'y':
12746 assert(HowLong == 0 && !Signed && !Unsigned &&
12747 "Bad modifiers used with 'y'!");
12748 Type = Context.BFloat16Ty;
12749 break;
12750 case 'v':
12751 assert(HowLong == 0 && !Signed && !Unsigned &&
12752 "Bad modifiers used with 'v'!");
12753 Type = Context.VoidTy;
12754 break;
12755 case 'h':
12756 assert(HowLong == 0 && !Signed && !Unsigned &&
12757 "Bad modifiers used with 'h'!");
12758 Type = Context.HalfTy;
12759 break;
12760 case 'f':
12761 assert(HowLong == 0 && !Signed && !Unsigned &&
12762 "Bad modifiers used with 'f'!");
12763 Type = Context.FloatTy;
12764 break;
12765 case 'd':
12766 assert(HowLong < 3 && !Signed && !Unsigned &&
12767 "Bad modifiers used with 'd'!");
12768 if (HowLong == 1)
12769 Type = Context.LongDoubleTy;
12770 else if (HowLong == 2)
12771 Type = Context.Float128Ty;
12772 else
12773 Type = Context.DoubleTy;
12774 break;
12775 case 's':
12776 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12777 if (Unsigned)
12778 Type = Context.UnsignedShortTy;
12779 else
12780 Type = Context.ShortTy;
12781 break;
12782 case 'i':
12783 if (IsChar)
12784 Type = Unsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
12785 else if (IsShort)
12786 Type = Unsigned ? Context.UnsignedShortTy : Context.ShortTy;
12787 else if (HowLong == 3)
12788 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12789 else if (HowLong == 2)
12790 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12791 else if (HowLong == 1)
12792 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12793 else
12794 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12795 break;
12796 case 'c':
12797 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12798 if (Signed)
12799 Type = Context.SignedCharTy;
12800 else if (Unsigned)
12801 Type = Context.UnsignedCharTy;
12802 else
12803 Type = Context.CharTy;
12804 break;
12805 case 'b': // boolean
12806 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12807 Type = Context.BoolTy;
12808 break;
12809 case 'z': // size_t.
12810 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12811 Type = Context.getSizeType();
12812 break;
12813 case 'w': // wchar_t.
12814 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12815 Type = Context.getWideCharType();
12816 break;
12817 case 'F':
12818 Type = Context.getCFConstantStringType();
12819 break;
12820 case 'G':
12821 Type = Context.getObjCIdType();
12822 break;
12823 case 'H':
12824 Type = Context.getObjCSelType();
12825 break;
12826 case 'M':
12827 Type = Context.getObjCSuperType();
12828 break;
12829 case 'a':
12830 Type = Context.getBuiltinVaListType();
12831 assert(!Type.isNull() && "builtin va list type not initialized!");
12832 break;
12833 case 'A':
12834 // This is a "reference" to a va_list; however, what exactly
12835 // this means depends on how va_list is defined. There are two
12836 // different kinds of va_list: ones passed by value, and ones
12837 // passed by reference. An example of a by-value va_list is
12838 // x86, where va_list is a char*. An example of by-ref va_list
12839 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12840 // we want this argument to be a char*&; for x86-64, we want
12841 // it to be a __va_list_tag*.
12842 Type = Context.getBuiltinVaListType();
12843 assert(!Type.isNull() && "builtin va list type not initialized!");
12844 if (Type->isArrayType())
12845 Type = Context.getArrayDecayedType(Ty: Type);
12846 else
12847 Type = Context.getLValueReferenceType(T: Type);
12848 break;
12849 case 'q': {
12850 char *End;
12851 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12852 assert(End != Str && "Missing vector size");
12853 Str = End;
12854
12855 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12856 RequiresICE, AllowTypeModifiers: false);
12857 assert(!RequiresICE && "Can't require vector ICE");
12858
12859 Type = Context.getScalableVectorType(EltTy: ElementType, NumElts: NumElements);
12860 break;
12861 }
12862 case 'Q': {
12863 switch (*Str++) {
12864 case 'a': {
12865 Type = Context.SveCountTy;
12866 break;
12867 }
12868 case 'b': {
12869 Type = Context.AMDGPUBufferRsrcTy;
12870 break;
12871 }
12872 case 'c': {
12873 Type = Context.AMDGPUFeaturePredicateTy;
12874 break;
12875 }
12876 case 't': {
12877 Type = Context.AMDGPUTextureTy;
12878 break;
12879 }
12880 case 'r': {
12881 Type = Context.HLSLResourceTy;
12882 break;
12883 }
12884 default:
12885 llvm_unreachable("Unexpected target builtin type");
12886 }
12887 break;
12888 }
12889 case 'V': {
12890 char *End;
12891 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12892 assert(End != Str && "Missing vector size");
12893 Str = End;
12894
12895 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12896 RequiresICE, AllowTypeModifiers: false);
12897 assert(!RequiresICE && "Can't require vector ICE");
12898
12899 // TODO: No way to make AltiVec vectors in builtins yet.
12900 Type = Context.getVectorType(vecType: ElementType, NumElts: NumElements, VecKind: VectorKind::Generic);
12901 break;
12902 }
12903 case 'E': {
12904 char *End;
12905
12906 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12907 assert(End != Str && "Missing vector size");
12908
12909 Str = End;
12910
12911 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12912 AllowTypeModifiers: false);
12913 Type = Context.getExtVectorType(vecType: ElementType, NumElts: NumElements);
12914 break;
12915 }
12916 case 'X': {
12917 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12918 AllowTypeModifiers: false);
12919 assert(!RequiresICE && "Can't require complex ICE");
12920 Type = Context.getComplexType(T: ElementType);
12921 break;
12922 }
12923 case 'Y':
12924 Type = Context.getPointerDiffType();
12925 break;
12926 case 'P':
12927 Type = Context.getFILEType();
12928 if (Type.isNull()) {
12929 Error = ASTContext::GE_Missing_stdio;
12930 return {};
12931 }
12932 break;
12933 case 'J':
12934 if (Signed)
12935 Type = Context.getsigjmp_bufType();
12936 else
12937 Type = Context.getjmp_bufType();
12938
12939 if (Type.isNull()) {
12940 Error = ASTContext::GE_Missing_setjmp;
12941 return {};
12942 }
12943 break;
12944 case 'K':
12945 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12946 Type = Context.getucontext_tType();
12947
12948 if (Type.isNull()) {
12949 Error = ASTContext::GE_Missing_ucontext;
12950 return {};
12951 }
12952 break;
12953 case 'p':
12954 Type = Context.getProcessIDType();
12955 break;
12956 case 'm':
12957 Type = Context.MFloat8Ty;
12958 break;
12959 }
12960
12961 // If there are modifiers and if we're allowed to parse them, go for it.
12962 Done = !AllowTypeModifiers;
12963 while (!Done) {
12964 switch (char c = *Str++) {
12965 default: Done = true; --Str; break;
12966 case '*':
12967 case '&': {
12968 // Both pointers and references can have their pointee types
12969 // qualified with an address space.
12970 char *End;
12971 unsigned AddrSpace = strtoul(nptr: Str, endptr: &End, base: 10);
12972 if (End != Str) {
12973 // Note AddrSpace == 0 is not the same as an unspecified address space.
12974 Type = Context.getAddrSpaceQualType(
12975 T: Type,
12976 AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: AddrSpace));
12977 Str = End;
12978 }
12979 if (c == '*')
12980 Type = Context.getPointerType(T: Type);
12981 else
12982 Type = Context.getLValueReferenceType(T: Type);
12983 break;
12984 }
12985 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12986 case 'C':
12987 Type = Type.withConst();
12988 break;
12989 case 'D':
12990 Type = Context.getVolatileType(T: Type);
12991 break;
12992 case 'R':
12993 Type = Type.withRestrict();
12994 break;
12995 }
12996 }
12997
12998 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12999 "Integer constant 'I' type must be an integer");
13000
13001 return Type;
13002}
13003
13004// On some targets such as PowerPC, some of the builtins are defined with custom
13005// type descriptors for target-dependent types. These descriptors are decoded in
13006// other functions, but it may be useful to be able to fall back to default
13007// descriptor decoding to define builtins mixing target-dependent and target-
13008// independent types. This function allows decoding one type descriptor with
13009// default decoding.
13010QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
13011 GetBuiltinTypeError &Error, bool &RequireICE,
13012 bool AllowTypeModifiers) const {
13013 return DecodeTypeFromStr(Str, Context, Error, RequiresICE&: RequireICE, AllowTypeModifiers);
13014}
13015
13016/// GetBuiltinType - Return the type for the specified builtin.
13017QualType ASTContext::GetBuiltinType(unsigned Id,
13018 GetBuiltinTypeError &Error,
13019 unsigned *IntegerConstantArgs) const {
13020 const char *TypeStr = BuiltinInfo.getTypeString(ID: Id);
13021 if (TypeStr[0] == '\0') {
13022 Error = GE_Missing_type;
13023 return {};
13024 }
13025
13026 SmallVector<QualType, 8> ArgTypes;
13027
13028 bool RequiresICE = false;
13029 Error = GE_None;
13030 QualType ResType = DecodeTypeFromStr(Str&: TypeStr, Context: *this, Error,
13031 RequiresICE, AllowTypeModifiers: true);
13032 if (Error != GE_None)
13033 return {};
13034
13035 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
13036
13037 while (TypeStr[0] && TypeStr[0] != '.') {
13038 QualType Ty = DecodeTypeFromStr(Str&: TypeStr, Context: *this, Error, RequiresICE, AllowTypeModifiers: true);
13039 if (Error != GE_None)
13040 return {};
13041
13042 // If this argument is required to be an IntegerConstantExpression and the
13043 // caller cares, fill in the bitmask we return.
13044 if (RequiresICE && IntegerConstantArgs)
13045 *IntegerConstantArgs |= 1 << ArgTypes.size();
13046
13047 // Do array -> pointer decay. The builtin should use the decayed type.
13048 if (Ty->isArrayType())
13049 Ty = getArrayDecayedType(Ty);
13050
13051 ArgTypes.push_back(Elt: Ty);
13052 }
13053
13054 if (Id == Builtin::BI__GetExceptionInfo)
13055 return {};
13056
13057 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
13058 "'.' should only occur at end of builtin type list!");
13059
13060 bool Variadic = (TypeStr[0] == '.');
13061
13062 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
13063 if (BuiltinInfo.isNoReturn(ID: Id))
13064 EI = EI.withNoReturn(noReturn: true);
13065
13066 // We really shouldn't be making a no-proto type here.
13067 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
13068 return getFunctionNoProtoType(ResultTy: ResType, Info: EI);
13069
13070 FunctionProtoType::ExtProtoInfo EPI;
13071 EPI.ExtInfo = EI;
13072 EPI.Variadic = Variadic;
13073 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(ID: Id))
13074 EPI.ExceptionSpec.Type =
13075 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
13076
13077 return getFunctionType(ResultTy: ResType, Args: ArgTypes, EPI);
13078}
13079
13080static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
13081 const FunctionDecl *FD) {
13082 if (!FD->isExternallyVisible())
13083 return GVA_Internal;
13084
13085 // Non-user-provided functions get emitted as weak definitions with every
13086 // use, no matter whether they've been explicitly instantiated etc.
13087 if (!FD->isUserProvided())
13088 return GVA_DiscardableODR;
13089
13090 GVALinkage External;
13091 switch (FD->getTemplateSpecializationKind()) {
13092 case TSK_Undeclared:
13093 case TSK_ExplicitSpecialization:
13094 External = GVA_StrongExternal;
13095 break;
13096
13097 case TSK_ExplicitInstantiationDefinition:
13098 return GVA_StrongODR;
13099
13100 // C++11 [temp.explicit]p10:
13101 // [ Note: The intent is that an inline function that is the subject of
13102 // an explicit instantiation declaration will still be implicitly
13103 // instantiated when used so that the body can be considered for
13104 // inlining, but that no out-of-line copy of the inline function would be
13105 // generated in the translation unit. -- end note ]
13106 case TSK_ExplicitInstantiationDeclaration:
13107 return GVA_AvailableExternally;
13108
13109 case TSK_ImplicitInstantiation:
13110 External = GVA_DiscardableODR;
13111 break;
13112 }
13113
13114 if (!FD->isInlined())
13115 return External;
13116
13117 if ((!Context.getLangOpts().CPlusPlus &&
13118 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13119 !FD->hasAttr<DLLExportAttr>()) ||
13120 FD->hasAttr<GNUInlineAttr>()) {
13121 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13122
13123 // GNU or C99 inline semantics. Determine whether this symbol should be
13124 // externally visible.
13125 if (auto *Def = FD->getDefinition();
13126 Def && Def->isInlineDefinitionExternallyVisible())
13127 return External;
13128
13129 // C99 inline semantics, where the symbol is not externally visible.
13130 return GVA_AvailableExternally;
13131 }
13132
13133 // Functions specified with extern and inline in -fms-compatibility mode
13134 // forcibly get emitted. While the body of the function cannot be later
13135 // replaced, the function definition cannot be discarded.
13136 if (FD->isMSExternInline())
13137 return GVA_StrongODR;
13138
13139 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13140 isa<CXXConstructorDecl>(Val: FD) &&
13141 cast<CXXConstructorDecl>(Val: FD)->isInheritingConstructor() &&
13142 !FD->hasAttr<DLLExportAttr>()) {
13143 // Both Clang and MSVC implement inherited constructors as forwarding
13144 // thunks that delegate to the base constructor. Keep non-dllexport
13145 // inheriting constructor thunks internal since they are not needed
13146 // outside the translation unit.
13147 //
13148 // dllexport inherited constructors are exempted so they are externally
13149 // visible, matching MSVC's export behavior. Inherited constructors
13150 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13151 // cleanup types) are excluded from export in Sema to avoid silent
13152 // runtime mismatches.
13153 return GVA_Internal;
13154 }
13155
13156 return GVA_DiscardableODR;
13157}
13158
13159static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
13160 const Decl *D, GVALinkage L) {
13161 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13162 // dllexport/dllimport on inline functions.
13163 if (D->hasAttr<DLLImportAttr>()) {
13164 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13165 return GVA_AvailableExternally;
13166 } else if (D->hasAttr<DLLExportAttr>()) {
13167 if (L == GVA_DiscardableODR)
13168 return GVA_StrongODR;
13169 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13170 // Device-side functions with __global__ attribute must always be
13171 // visible externally so they can be launched from host.
13172 if (D->hasAttr<CUDAGlobalAttr>() &&
13173 (L == GVA_DiscardableODR || L == GVA_Internal))
13174 return GVA_StrongODR;
13175 // Single source offloading languages like CUDA/HIP need to be able to
13176 // access static device variables from host code of the same compilation
13177 // unit. This is done by externalizing the static variable with a shared
13178 // name between the host and device compilation which is the same for the
13179 // same compilation unit whereas different among different compilation
13180 // units.
13181 if (Context.shouldExternalize(D))
13182 return GVA_StrongExternal;
13183 }
13184 return L;
13185}
13186
13187/// Adjust the GVALinkage for a declaration based on what an external AST source
13188/// knows about whether there can be other definitions of this declaration.
13189static GVALinkage
13190adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
13191 GVALinkage L) {
13192 ExternalASTSource *Source = Ctx.getExternalSource();
13193 if (!Source)
13194 return L;
13195
13196 switch (Source->hasExternalDefinitions(D)) {
13197 case ExternalASTSource::EK_Never:
13198 // Other translation units rely on us to provide the definition.
13199 if (L == GVA_DiscardableODR)
13200 return GVA_StrongODR;
13201 break;
13202
13203 case ExternalASTSource::EK_Always:
13204 return GVA_AvailableExternally;
13205
13206 case ExternalASTSource::EK_ReplyHazy:
13207 break;
13208 }
13209 return L;
13210}
13211
13212GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
13213 return adjustGVALinkageForExternalDefinitionKind(Ctx: *this, D: FD,
13214 L: adjustGVALinkageForAttributes(Context: *this, D: FD,
13215 L: basicGVALinkageForFunction(Context: *this, FD)));
13216}
13217
13218static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
13219 const VarDecl *VD) {
13220 // As an extension for interactive REPLs, make sure constant variables are
13221 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13222 // marking them as internal.
13223 if (Context.getLangOpts().CPlusPlus &&
13224 Context.getLangOpts().IncrementalExtensions &&
13225 VD->getType().isConstQualified() &&
13226 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13227 !isa<VarTemplateSpecializationDecl>(Val: VD) && !VD->getDescribedVarTemplate())
13228 return GVA_DiscardableODR;
13229
13230 if (!VD->isExternallyVisible())
13231 return GVA_Internal;
13232
13233 if (VD->isStaticLocal()) {
13234 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13235 while (LexicalContext && !isa<FunctionDecl>(Val: LexicalContext))
13236 LexicalContext = LexicalContext->getLexicalParent();
13237
13238 // ObjC Blocks can create local variables that don't have a FunctionDecl
13239 // LexicalContext.
13240 if (!LexicalContext)
13241 return GVA_DiscardableODR;
13242
13243 // Otherwise, let the static local variable inherit its linkage from the
13244 // nearest enclosing function.
13245 auto StaticLocalLinkage =
13246 Context.GetGVALinkageForFunction(FD: cast<FunctionDecl>(Val: LexicalContext));
13247
13248 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13249 // be emitted in any object with references to the symbol for the object it
13250 // contains, whether inline or out-of-line."
13251 // Similar behavior is observed with MSVC. An alternative ABI could use
13252 // StrongODR/AvailableExternally to match the function, but none are
13253 // known/supported currently.
13254 if (StaticLocalLinkage == GVA_StrongODR ||
13255 StaticLocalLinkage == GVA_AvailableExternally)
13256 return GVA_DiscardableODR;
13257 return StaticLocalLinkage;
13258 }
13259
13260 // MSVC treats in-class initialized static data members as definitions.
13261 // By giving them non-strong linkage, out-of-line definitions won't
13262 // cause link errors.
13263 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13264 return GVA_DiscardableODR;
13265
13266 // Most non-template variables have strong linkage; inline variables are
13267 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13268 GVALinkage StrongLinkage;
13269 switch (Context.getInlineVariableDefinitionKind(VD)) {
13270 case ASTContext::InlineVariableDefinitionKind::None:
13271 StrongLinkage = GVA_StrongExternal;
13272 break;
13273 case ASTContext::InlineVariableDefinitionKind::Weak:
13274 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
13275 StrongLinkage = GVA_DiscardableODR;
13276 break;
13277 case ASTContext::InlineVariableDefinitionKind::Strong:
13278 StrongLinkage = GVA_StrongODR;
13279 break;
13280 }
13281
13282 switch (VD->getTemplateSpecializationKind()) {
13283 case TSK_Undeclared:
13284 return StrongLinkage;
13285
13286 case TSK_ExplicitSpecialization:
13287 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13288 VD->isStaticDataMember()
13289 ? GVA_StrongODR
13290 : StrongLinkage;
13291
13292 case TSK_ExplicitInstantiationDefinition:
13293 return GVA_StrongODR;
13294
13295 case TSK_ExplicitInstantiationDeclaration:
13296 return GVA_AvailableExternally;
13297
13298 case TSK_ImplicitInstantiation:
13299 return GVA_DiscardableODR;
13300 }
13301
13302 llvm_unreachable("Invalid Linkage!");
13303}
13304
13305GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) const {
13306 return adjustGVALinkageForExternalDefinitionKind(Ctx: *this, D: VD,
13307 L: adjustGVALinkageForAttributes(Context: *this, D: VD,
13308 L: basicGVALinkageForVariable(Context: *this, VD)));
13309}
13310
13311bool ASTContext::DeclMustBeEmitted(const Decl *D) {
13312 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
13313 if (!VD->isFileVarDecl())
13314 return false;
13315 // Global named register variables (GNU extension) are never emitted.
13316 if (VD->getStorageClass() == SC_Register)
13317 return false;
13318 if (VD->getDescribedVarTemplate() ||
13319 isa<VarTemplatePartialSpecializationDecl>(Val: VD))
13320 return false;
13321 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
13322 // We never need to emit an uninstantiated function template.
13323 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13324 return false;
13325 } else if (isa<PragmaCommentDecl>(Val: D))
13326 return true;
13327 else if (isa<PragmaDetectMismatchDecl>(Val: D))
13328 return true;
13329 else if (isa<OMPRequiresDecl>(Val: D))
13330 return true;
13331 else if (isa<OMPThreadPrivateDecl>(Val: D))
13332 return !D->getDeclContext()->isDependentContext();
13333 else if (isa<OMPAllocateDecl>(Val: D))
13334 return !D->getDeclContext()->isDependentContext();
13335 else if (isa<OMPDeclareReductionDecl>(Val: D) || isa<OMPDeclareMapperDecl>(Val: D))
13336 return !D->getDeclContext()->isDependentContext();
13337 else if (isa<ImportDecl>(Val: D))
13338 return true;
13339 else
13340 return false;
13341
13342 // If this is a member of a class template, we do not need to emit it.
13343 if (D->getDeclContext()->isDependentContext())
13344 return false;
13345
13346 // Weak references don't produce any output by themselves.
13347 if (D->hasAttr<WeakRefAttr>())
13348 return false;
13349
13350 // SYCL device compilation requires that functions defined with the
13351 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13352 // other entities are emitted only if they are used by a function
13353 // defined with one of those attributes.
13354 if (LangOpts.SYCLIsDevice)
13355 return isa<FunctionDecl>(Val: D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13356 D->hasAttr<SYCLExternalAttr>());
13357
13358 // Aliases and used decls are required.
13359 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13360 return true;
13361
13362 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
13363 // Forward declarations aren't required.
13364 if (!FD->doesThisDeclarationHaveABody())
13365 return FD->doesDeclarationForceExternallyVisibleDefinition();
13366
13367 // Constructors and destructors are required.
13368 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13369 return true;
13370
13371 // The key function for a class is required. This rule only comes
13372 // into play when inline functions can be key functions, though.
13373 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13374 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
13375 const CXXRecordDecl *RD = MD->getParent();
13376 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13377 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13378 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13379 return true;
13380 }
13381 }
13382 }
13383
13384 GVALinkage Linkage = GetGVALinkageForFunction(FD);
13385
13386 // static, static inline, always_inline, and extern inline functions can
13387 // always be deferred. Normal inline functions can be deferred in C99/C++.
13388 // Implicit template instantiations can also be deferred in C++.
13389 return !isDiscardableGVALinkage(L: Linkage);
13390 }
13391
13392 const auto *VD = cast<VarDecl>(Val: D);
13393 assert(VD->isFileVarDecl() && "Expected file scoped var");
13394
13395 // If the decl is marked as `declare target to`, it should be emitted for the
13396 // host and for the device.
13397 if (LangOpts.OpenMP &&
13398 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13399 return true;
13400
13401 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13402 !isMSStaticDataMemberInlineDefinition(VD))
13403 return false;
13404
13405 if (VD->shouldEmitInExternalSource())
13406 return false;
13407
13408 // Variables that can be needed in other TUs are required.
13409 auto Linkage = GetGVALinkageForVariable(VD);
13410 if (!isDiscardableGVALinkage(L: Linkage))
13411 return true;
13412
13413 // We never need to emit a variable that is available in another TU.
13414 if (Linkage == GVA_AvailableExternally)
13415 return false;
13416
13417 // Variables that have destruction with side-effects are required.
13418 if (VD->needsDestruction(Ctx: *this))
13419 return true;
13420
13421 // Variables that have initialization with side-effects are required.
13422 if (VD->hasInitWithSideEffects())
13423 return true;
13424
13425 // Likewise, variables with tuple-like bindings are required if their
13426 // bindings have side-effects.
13427 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: VD)) {
13428 for (const auto *BD : DD->flat_bindings())
13429 if (const auto *BindingVD = BD->getHoldingVar())
13430 if (DeclMustBeEmitted(D: BindingVD))
13431 return true;
13432 }
13433
13434 return false;
13435}
13436
13437void ASTContext::forEachMultiversionedFunctionVersion(
13438 const FunctionDecl *FD,
13439 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13440 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13441 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13442 FD = FD->getMostRecentDecl();
13443 // FIXME: The order of traversal here matters and depends on the order of
13444 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13445 // shouldn't rely on that.
13446 for (auto *CurDecl :
13447 FD->getDeclContext()->getRedeclContext()->lookup(Name: FD->getDeclName())) {
13448 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13449 if (CurFD && hasSameType(T1: CurFD->getType(), T2: FD->getType()) &&
13450 SeenDecls.insert(V: CurFD).second) {
13451 Pred(CurFD);
13452 }
13453 }
13454}
13455
13456CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
13457 bool IsCXXMethod) const {
13458 // Pass through to the C++ ABI object
13459 if (IsCXXMethod)
13460 return ABI->getDefaultMethodCallConv(isVariadic: IsVariadic);
13461
13462 switch (LangOpts.getDefaultCallingConv()) {
13463 case LangOptions::DCC_None:
13464 break;
13465 case LangOptions::DCC_CDecl:
13466 return CC_C;
13467 case LangOptions::DCC_FastCall:
13468 if (getTargetInfo().hasFeature(Feature: "sse2") && !IsVariadic)
13469 return CC_X86FastCall;
13470 break;
13471 case LangOptions::DCC_StdCall:
13472 if (!IsVariadic)
13473 return CC_X86StdCall;
13474 break;
13475 case LangOptions::DCC_VectorCall:
13476 // __vectorcall cannot be applied to variadic functions.
13477 if (!IsVariadic)
13478 return CC_X86VectorCall;
13479 break;
13480 case LangOptions::DCC_RegCall:
13481 // __regcall cannot be applied to variadic functions.
13482 if (!IsVariadic)
13483 return CC_X86RegCall;
13484 break;
13485 case LangOptions::DCC_RtdCall:
13486 if (!IsVariadic)
13487 return CC_M68kRTD;
13488 break;
13489 }
13490 return Target->getDefaultCallingConv();
13491}
13492
13493bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
13494 // Pass through to the C++ ABI object
13495 return ABI->isNearlyEmpty(RD);
13496}
13497
13498VTableContextBase *ASTContext::getVTableContext() {
13499 if (!VTContext) {
13500 auto ABI = Target->getCXXABI();
13501 if (ABI.isMicrosoft())
13502 VTContext.reset(p: new MicrosoftVTableContext(*this));
13503 else {
13504 VTContext.reset(p: new ItaniumVTableContext(*this));
13505 }
13506 }
13507 return VTContext.get();
13508}
13509
13510MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
13511 if (!T)
13512 T = Target;
13513 switch (T->getCXXABI().getKind()) {
13514 case TargetCXXABI::AppleARM64:
13515 case TargetCXXABI::Fuchsia:
13516 case TargetCXXABI::GenericAArch64:
13517 case TargetCXXABI::GenericItanium:
13518 case TargetCXXABI::GenericARM:
13519 case TargetCXXABI::GenericMIPS:
13520 case TargetCXXABI::iOS:
13521 case TargetCXXABI::WebAssembly:
13522 case TargetCXXABI::WatchOS:
13523 case TargetCXXABI::XL:
13524 return ItaniumMangleContext::create(Context&: *this, Diags&: getDiagnostics());
13525 case TargetCXXABI::Microsoft:
13526 return MicrosoftMangleContext::create(Context&: *this, Diags&: getDiagnostics());
13527 }
13528 llvm_unreachable("Unsupported ABI");
13529}
13530
13531MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) {
13532 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13533 "Device mangle context does not support Microsoft mangling.");
13534 switch (T.getCXXABI().getKind()) {
13535 case TargetCXXABI::AppleARM64:
13536 case TargetCXXABI::Fuchsia:
13537 case TargetCXXABI::GenericAArch64:
13538 case TargetCXXABI::GenericItanium:
13539 case TargetCXXABI::GenericARM:
13540 case TargetCXXABI::GenericMIPS:
13541 case TargetCXXABI::iOS:
13542 case TargetCXXABI::WebAssembly:
13543 case TargetCXXABI::WatchOS:
13544 case TargetCXXABI::XL:
13545 return ItaniumMangleContext::create(
13546 Context&: *this, Diags&: getDiagnostics(),
13547 Discriminator: [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13548 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
13549 return RD->getDeviceLambdaManglingNumber();
13550 return std::nullopt;
13551 },
13552 /*IsAux=*/true);
13553 case TargetCXXABI::Microsoft:
13554 return MicrosoftMangleContext::create(Context&: *this, Diags&: getDiagnostics(),
13555 /*IsAux=*/true);
13556 }
13557 llvm_unreachable("Unsupported ABI");
13558}
13559
13560MangleContext *ASTContext::cudaNVInitDeviceMC() {
13561 // If the host and device have different C++ ABIs, mark it as the device
13562 // mangle context so that the mangling needs to retrieve the additional
13563 // device lambda mangling number instead of the regular host one.
13564 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13565 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13566 return createDeviceMangleContext(T: *getAuxTargetInfo());
13567 }
13568
13569 return createMangleContext(T: getAuxTargetInfo());
13570}
13571
13572CXXABI::~CXXABI() = default;
13573
13574size_t ASTContext::getSideTableAllocatedMemory() const {
13575 return ASTRecordLayouts.getMemorySize() +
13576 llvm::capacity_in_bytes(X: ObjCLayouts) +
13577 llvm::capacity_in_bytes(X: KeyFunctions) +
13578 llvm::capacity_in_bytes(X: ObjCImpls) +
13579 llvm::capacity_in_bytes(X: BlockVarCopyInits) +
13580 llvm::capacity_in_bytes(X: DeclAttrs) +
13581 llvm::capacity_in_bytes(X: TemplateOrInstantiation) +
13582 llvm::capacity_in_bytes(X: InstantiatedFromUsingDecl) +
13583 llvm::capacity_in_bytes(X: InstantiatedFromUsingShadowDecl) +
13584 llvm::capacity_in_bytes(X: InstantiatedFromUnnamedFieldDecl) +
13585 llvm::capacity_in_bytes(X: OverriddenMethods) +
13586 llvm::capacity_in_bytes(X: Types) +
13587 llvm::capacity_in_bytes(x: VariableArrayTypes);
13588}
13589
13590/// getIntTypeForBitwidth -
13591/// sets integer QualTy according to specified details:
13592/// bitwidth, signed/unsigned.
13593/// Returns empty type if there is no appropriate target types.
13594QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
13595 unsigned Signed) const {
13596 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(BitWidth: DestWidth, IsSigned: Signed);
13597 CanQualType QualTy = getFromTargetType(Type: Ty);
13598 if (!QualTy && DestWidth == 128)
13599 return Signed ? Int128Ty : UnsignedInt128Ty;
13600 return QualTy;
13601}
13602
13603QualType ASTContext::getLeastIntTypeForBitwidth(unsigned DestWidth,
13604 unsigned Signed) const {
13605 return getFromTargetType(
13606 Type: getTargetInfo().getLeastIntTypeByWidth(BitWidth: DestWidth, IsSigned: Signed));
13607}
13608
13609/// getRealTypeForBitwidth -
13610/// sets floating point QualTy according to specified bitwidth.
13611/// Returns empty type if there is no appropriate target types.
13612QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
13613 FloatModeKind ExplicitType) const {
13614 FloatModeKind Ty =
13615 getTargetInfo().getRealTypeByWidth(BitWidth: DestWidth, ExplicitType);
13616 switch (Ty) {
13617 case FloatModeKind::Half:
13618 return HalfTy;
13619 case FloatModeKind::Float:
13620 return FloatTy;
13621 case FloatModeKind::Double:
13622 return DoubleTy;
13623 case FloatModeKind::LongDouble:
13624 return LongDoubleTy;
13625 case FloatModeKind::Float128:
13626 return Float128Ty;
13627 case FloatModeKind::Ibm128:
13628 return Ibm128Ty;
13629 case FloatModeKind::NoFloat:
13630 return {};
13631 }
13632
13633 llvm_unreachable("Unhandled TargetInfo::RealType value");
13634}
13635
13636void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13637 if (Number <= 1)
13638 return;
13639
13640 MangleNumbers[ND] = Number;
13641
13642 if (Listener)
13643 Listener->AddedManglingNumber(D: ND, Number);
13644}
13645
13646unsigned ASTContext::getManglingNumber(const NamedDecl *ND,
13647 bool ForAuxTarget) const {
13648 auto I = MangleNumbers.find(Key: ND);
13649 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13650 // CUDA/HIP host compilation encodes host and device mangling numbers
13651 // as lower and upper half of 32 bit integer.
13652 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13653 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13654 } else {
13655 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13656 "number for aux target");
13657 }
13658 return Res > 1 ? Res : 1;
13659}
13660
13661void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13662 if (Number <= 1)
13663 return;
13664
13665 StaticLocalNumbers[VD] = Number;
13666
13667 if (Listener)
13668 Listener->AddedStaticLocalNumbers(D: VD, Number);
13669}
13670
13671unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
13672 auto I = StaticLocalNumbers.find(Key: VD);
13673 return I != StaticLocalNumbers.end() ? I->second : 1;
13674}
13675
13676void ASTContext::setIsDestroyingOperatorDelete(const FunctionDecl *FD,
13677 bool IsDestroying) {
13678 if (!IsDestroying) {
13679 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13680 return;
13681 }
13682 DestroyingOperatorDeletes.insert(V: FD->getCanonicalDecl());
13683}
13684
13685bool ASTContext::isDestroyingOperatorDelete(const FunctionDecl *FD) const {
13686 return DestroyingOperatorDeletes.contains(V: FD->getCanonicalDecl());
13687}
13688
13689void ASTContext::setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD,
13690 bool IsTypeAware) {
13691 if (!IsTypeAware) {
13692 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13693 return;
13694 }
13695 TypeAwareOperatorNewAndDeletes.insert(V: FD->getCanonicalDecl());
13696}
13697
13698bool ASTContext::isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const {
13699 return TypeAwareOperatorNewAndDeletes.contains(V: FD->getCanonicalDecl());
13700}
13701
13702void ASTContext::addOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor,
13703 FunctionDecl *OperatorDelete,
13704 OperatorDeleteKind K) const {
13705 switch (K) {
13706 case OperatorDeleteKind::Regular:
13707 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13708 break;
13709 case OperatorDeleteKind::GlobalRegular:
13710 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13711 OperatorDelete;
13712 break;
13713 case OperatorDeleteKind::Array:
13714 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13715 OperatorDelete;
13716 break;
13717 case OperatorDeleteKind::ArrayGlobal:
13718 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13719 OperatorDelete;
13720 break;
13721 }
13722}
13723
13724bool ASTContext::dtorHasOperatorDelete(const CXXDestructorDecl *Dtor,
13725 OperatorDeleteKind K) const {
13726 switch (K) {
13727 case OperatorDeleteKind::Regular:
13728 return OperatorDeletesForVirtualDtor.contains(Val: Dtor->getCanonicalDecl());
13729 case OperatorDeleteKind::GlobalRegular:
13730 return GlobalOperatorDeletesForVirtualDtor.contains(
13731 Val: Dtor->getCanonicalDecl());
13732 case OperatorDeleteKind::Array:
13733 return ArrayOperatorDeletesForVirtualDtor.contains(
13734 Val: Dtor->getCanonicalDecl());
13735 case OperatorDeleteKind::ArrayGlobal:
13736 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13737 Val: Dtor->getCanonicalDecl());
13738 }
13739 return false;
13740}
13741
13742FunctionDecl *
13743ASTContext::getOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor,
13744 OperatorDeleteKind K) const {
13745 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13746 switch (K) {
13747 case OperatorDeleteKind::Regular:
13748 if (OperatorDeletesForVirtualDtor.contains(Val: Canon))
13749 return OperatorDeletesForVirtualDtor[Canon];
13750 return nullptr;
13751 case OperatorDeleteKind::GlobalRegular:
13752 if (GlobalOperatorDeletesForVirtualDtor.contains(Val: Canon))
13753 return GlobalOperatorDeletesForVirtualDtor[Canon];
13754 return nullptr;
13755 case OperatorDeleteKind::Array:
13756 if (ArrayOperatorDeletesForVirtualDtor.contains(Val: Canon))
13757 return ArrayOperatorDeletesForVirtualDtor[Canon];
13758 return nullptr;
13759 case OperatorDeleteKind::ArrayGlobal:
13760 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Val: Canon))
13761 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13762 return nullptr;
13763 }
13764 return nullptr;
13765}
13766
13767bool ASTContext::classMaybeNeedsVectorDeletingDestructor(
13768 const CXXRecordDecl *RD) {
13769 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13770 return false;
13771
13772 return MaybeRequireVectorDeletingDtor.count(V: RD);
13773}
13774
13775void ASTContext::setClassMaybeNeedsVectorDeletingDestructor(
13776 const CXXRecordDecl *RD) {
13777 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13778 return;
13779
13780 MaybeRequireVectorDeletingDtor.insert(V: RD);
13781}
13782
13783MangleNumberingContext &
13784ASTContext::getManglingNumberContext(const DeclContext *DC) {
13785 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13786 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13787 if (!MCtx)
13788 MCtx = createMangleNumberingContext();
13789 return *MCtx;
13790}
13791
13792MangleNumberingContext &
13793ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
13794 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13795 std::unique_ptr<MangleNumberingContext> &MCtx =
13796 ExtraMangleNumberingContexts[D];
13797 if (!MCtx)
13798 MCtx = createMangleNumberingContext();
13799 return *MCtx;
13800}
13801
13802std::unique_ptr<MangleNumberingContext>
13803ASTContext::createMangleNumberingContext() const {
13804 return ABI->createMangleNumberingContext();
13805}
13806
13807const CXXConstructorDecl *
13808ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
13809 return ABI->getCopyConstructorForExceptionObject(
13810 cast<CXXRecordDecl>(Val: RD->getFirstDecl()));
13811}
13812
13813void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
13814 CXXConstructorDecl *CD) {
13815 return ABI->addCopyConstructorForExceptionObject(
13816 cast<CXXRecordDecl>(Val: RD->getFirstDecl()),
13817 cast<CXXConstructorDecl>(Val: CD->getFirstDecl()));
13818}
13819
13820void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
13821 TypedefNameDecl *DD) {
13822 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13823}
13824
13825TypedefNameDecl *
13826ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
13827 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13828}
13829
13830void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
13831 DeclaratorDecl *DD) {
13832 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13833}
13834
13835DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
13836 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13837}
13838
13839void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
13840 ParamIndices[D] = index;
13841}
13842
13843unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
13844 ParameterIndexTable::const_iterator I = ParamIndices.find(Val: D);
13845 assert(I != ParamIndices.end() &&
13846 "ParmIndices lacks entry set by ParmVarDecl");
13847 return I->second;
13848}
13849
13850QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
13851 unsigned Length) const {
13852 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13853 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13854 EltTy = EltTy.withConst();
13855
13856 EltTy = adjustStringLiteralBaseType(Ty: EltTy);
13857
13858 // Get an array type for the string, according to C99 6.4.5. This includes
13859 // the null terminator character.
13860 return getConstantArrayType(EltTy, ArySizeIn: llvm::APInt(32, Length + 1), SizeExpr: nullptr,
13861 ASM: ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13862}
13863
13864StringLiteral *
13865ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
13866 StringLiteral *&Result = StringLiteralCache[Key];
13867 if (!Result)
13868 Result = StringLiteral::Create(
13869 Ctx: *this, Str: Key, Kind: StringLiteralKind::Ordinary,
13870 /*Pascal*/ false, Ty: getStringLiteralArrayType(EltTy: CharTy, Length: Key.size()),
13871 Locs: SourceLocation());
13872 return Result;
13873}
13874
13875MSGuidDecl *
13876ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
13877 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13878
13879 llvm::FoldingSetNodeID ID;
13880 MSGuidDecl::Profile(ID, P: Parts);
13881
13882 void *InsertPos;
13883 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13884 return Existing;
13885
13886 QualType GUIDType = getMSGuidType().withConst();
13887 MSGuidDecl *New = MSGuidDecl::Create(C: *this, T: GUIDType, P: Parts);
13888 MSGuidDecls.InsertNode(N: New, InsertPos);
13889 return New;
13890}
13891
13892UnnamedGlobalConstantDecl *
13893ASTContext::getUnnamedGlobalConstantDecl(QualType Ty,
13894 const APValue &APVal) const {
13895 llvm::FoldingSetNodeID ID;
13896 UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal);
13897
13898 void *InsertPos;
13899 if (UnnamedGlobalConstantDecl *Existing =
13900 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13901 return Existing;
13902
13903 UnnamedGlobalConstantDecl *New =
13904 UnnamedGlobalConstantDecl::Create(C: *this, T: Ty, APVal);
13905 UnnamedGlobalConstantDecls.InsertNode(N: New, InsertPos);
13906 return New;
13907}
13908
13909TemplateParamObjectDecl *
13910ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
13911 assert(T->isRecordType() && "template param object of unexpected type");
13912
13913 // C++ [temp.param]p8:
13914 // [...] a static storage duration object of type 'const T' [...]
13915 T.addConst();
13916
13917 llvm::FoldingSetNodeID ID;
13918 TemplateParamObjectDecl::Profile(ID, T, V);
13919
13920 void *InsertPos;
13921 if (TemplateParamObjectDecl *Existing =
13922 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13923 return Existing;
13924
13925 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(C: *this, T, V);
13926 TemplateParamObjectDecls.InsertNode(N: New, InsertPos);
13927 return New;
13928}
13929
13930bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
13931 const llvm::Triple &T = getTargetInfo().getTriple();
13932 if (!T.isOSDarwin())
13933 return false;
13934
13935 if (!(T.isiOS() && T.isOSVersionLT(Major: 7)) &&
13936 !(T.isMacOSX() && T.isOSVersionLT(Major: 10, Minor: 9)))
13937 return false;
13938
13939 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13940 CharUnits sizeChars = getTypeSizeInChars(T: AtomicTy);
13941 uint64_t Size = sizeChars.getQuantity();
13942 CharUnits alignChars = getTypeAlignInChars(T: AtomicTy);
13943 unsigned Align = alignChars.getQuantity();
13944 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13945 return (Size != Align || toBits(CharSize: sizeChars) > MaxInlineWidthInBits);
13946}
13947
13948bool
13949ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
13950 const ObjCMethodDecl *MethodImpl) {
13951 // No point trying to match an unavailable/deprecated mothod.
13952 if (MethodDecl->hasAttr<UnavailableAttr>()
13953 || MethodDecl->hasAttr<DeprecatedAttr>())
13954 return false;
13955 if (MethodDecl->getObjCDeclQualifier() !=
13956 MethodImpl->getObjCDeclQualifier())
13957 return false;
13958 if (!hasSameType(T1: MethodDecl->getReturnType(), T2: MethodImpl->getReturnType()))
13959 return false;
13960
13961 if (MethodDecl->param_size() != MethodImpl->param_size())
13962 return false;
13963
13964 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13965 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13966 EF = MethodDecl->param_end();
13967 IM != EM && IF != EF; ++IM, ++IF) {
13968 const ParmVarDecl *DeclVar = (*IF);
13969 const ParmVarDecl *ImplVar = (*IM);
13970 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13971 return false;
13972 if (!hasSameType(T1: DeclVar->getType(), T2: ImplVar->getType()))
13973 return false;
13974 }
13975
13976 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13977}
13978
13979uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
13980 LangAS AS;
13981 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
13982 AS = LangAS::Default;
13983 else
13984 AS = QT->getPointeeType().getAddressSpace();
13985
13986 return getTargetInfo().getNullPointerValue(AddrSpace: AS);
13987}
13988
13989unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
13990 return getTargetInfo().getTargetAddressSpace(AS);
13991}
13992
13993bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13994 if (X == Y)
13995 return true;
13996 if (!X || !Y)
13997 return false;
13998 llvm::FoldingSetNodeID IDX, IDY;
13999 X->Profile(ID&: IDX, Context: *this, /*Canonical=*/true);
14000 Y->Profile(ID&: IDY, Context: *this, /*Canonical=*/true);
14001 return IDX == IDY;
14002}
14003
14004// The getCommon* helpers return, for given 'same' X and Y entities given as
14005// inputs, another entity which is also the 'same' as the inputs, but which
14006// is closer to the canonical form of the inputs, each according to a given
14007// criteria.
14008// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
14009// the regular ones.
14010
14011static Decl *getCommonDecl(Decl *X, Decl *Y) {
14012 if (!declaresSameEntity(D1: X, D2: Y))
14013 return nullptr;
14014 for (const Decl *DX : X->redecls()) {
14015 // If we reach Y before reaching the first decl, that means X is older.
14016 if (DX == Y)
14017 return X;
14018 // If we reach the first decl, then Y is older.
14019 if (DX->isFirstDecl())
14020 return Y;
14021 }
14022 llvm_unreachable("Corrupt redecls chain");
14023}
14024
14025template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14026static T *getCommonDecl(T *X, T *Y) {
14027 return cast_or_null<T>(
14028 getCommonDecl(X: const_cast<Decl *>(cast_or_null<Decl>(X)),
14029 Y: const_cast<Decl *>(cast_or_null<Decl>(Y))));
14030}
14031
14032template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14033static T *getCommonDeclChecked(T *X, T *Y) {
14034 return cast<T>(getCommonDecl(X: const_cast<Decl *>(cast<Decl>(X)),
14035 Y: const_cast<Decl *>(cast<Decl>(Y))));
14036}
14037
14038static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X,
14039 TemplateName Y,
14040 bool IgnoreDeduced = false) {
14041 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
14042 return X;
14043 // FIXME: There are cases here where we could find a common template name
14044 // with more sugar. For example one could be a SubstTemplateTemplate*
14045 // replacing the other.
14046 TemplateName CX = Ctx.getCanonicalTemplateName(Name: X, IgnoreDeduced);
14047 if (CX.getAsVoidPointer() !=
14048 Ctx.getCanonicalTemplateName(Name: Y).getAsVoidPointer())
14049 return TemplateName();
14050 return CX;
14051}
14052
14053static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx,
14054 TemplateName X, TemplateName Y,
14055 bool IgnoreDeduced) {
14056 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
14057 assert(R.getAsVoidPointer() != nullptr);
14058 return R;
14059}
14060
14061static auto getCommonTypes(const ASTContext &Ctx, ArrayRef<QualType> Xs,
14062 ArrayRef<QualType> Ys, bool Unqualified = false) {
14063 assert(Xs.size() == Ys.size());
14064 SmallVector<QualType, 8> Rs(Xs.size());
14065 for (size_t I = 0; I < Rs.size(); ++I)
14066 Rs[I] = Ctx.getCommonSugaredType(X: Xs[I], Y: Ys[I], Unqualified);
14067 return Rs;
14068}
14069
14070template <class T>
14071static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
14072 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
14073 : SourceLocation();
14074}
14075
14076static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx,
14077 const TemplateArgument &X,
14078 const TemplateArgument &Y) {
14079 if (X.getKind() != Y.getKind())
14080 return TemplateArgument();
14081
14082 switch (X.getKind()) {
14083 case TemplateArgument::ArgKind::Type:
14084 if (!Ctx.hasSameType(T1: X.getAsType(), T2: Y.getAsType()))
14085 return TemplateArgument();
14086 return TemplateArgument(
14087 Ctx.getCommonSugaredType(X: X.getAsType(), Y: Y.getAsType()));
14088 case TemplateArgument::ArgKind::NullPtr:
14089 if (!Ctx.hasSameType(T1: X.getNullPtrType(), T2: Y.getNullPtrType()))
14090 return TemplateArgument();
14091 return TemplateArgument(
14092 Ctx.getCommonSugaredType(X: X.getNullPtrType(), Y: Y.getNullPtrType()),
14093 /*Unqualified=*/true);
14094 case TemplateArgument::ArgKind::Expression:
14095 if (!Ctx.hasSameType(T1: X.getAsExpr()->getType(), T2: Y.getAsExpr()->getType()))
14096 return TemplateArgument();
14097 // FIXME: Try to keep the common sugar.
14098 return X;
14099 case TemplateArgument::ArgKind::Template: {
14100 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
14101 TemplateName CTN = ::getCommonTemplateName(Ctx, X: TX, Y: TY);
14102 if (!CTN.getAsVoidPointer())
14103 return TemplateArgument();
14104 return TemplateArgument(CTN);
14105 }
14106 case TemplateArgument::ArgKind::TemplateExpansion: {
14107 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
14108 TY = Y.getAsTemplateOrTemplatePattern();
14109 TemplateName CTN = ::getCommonTemplateName(Ctx, X: TX, Y: TY);
14110 if (!CTN.getAsVoidPointer())
14111 return TemplateName();
14112 auto NExpX = X.getNumTemplateExpansions();
14113 assert(NExpX == Y.getNumTemplateExpansions());
14114 return TemplateArgument(CTN, NExpX);
14115 }
14116 default:
14117 // FIXME: Handle the other argument kinds.
14118 return X;
14119 }
14120}
14121
14122static bool getCommonTemplateArguments(const ASTContext &Ctx,
14123 SmallVectorImpl<TemplateArgument> &R,
14124 ArrayRef<TemplateArgument> Xs,
14125 ArrayRef<TemplateArgument> Ys) {
14126 if (Xs.size() != Ys.size())
14127 return true;
14128 R.resize(N: Xs.size());
14129 for (size_t I = 0; I < R.size(); ++I) {
14130 R[I] = getCommonTemplateArgument(Ctx, X: Xs[I], Y: Ys[I]);
14131 if (R[I].isNull())
14132 return true;
14133 }
14134 return false;
14135}
14136
14137static auto getCommonTemplateArguments(const ASTContext &Ctx,
14138 ArrayRef<TemplateArgument> Xs,
14139 ArrayRef<TemplateArgument> Ys) {
14140 SmallVector<TemplateArgument, 8> R;
14141 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14142 assert(!Different);
14143 (void)Different;
14144 return R;
14145}
14146
14147template <class T>
14148static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y,
14149 bool IsSame) {
14150 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14151 if (KX == KY)
14152 return KX;
14153 KX = getCanonicalElaboratedTypeKeyword(Keyword: KX);
14154 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14155 return KX;
14156}
14157
14158/// Returns a NestedNameSpecifier which has only the common sugar
14159/// present in both NNS1 and NNS2.
14160static NestedNameSpecifier getCommonNNS(const ASTContext &Ctx,
14161 NestedNameSpecifier NNS1,
14162 NestedNameSpecifier NNS2, bool IsSame) {
14163 // If they are identical, all sugar is common.
14164 if (NNS1 == NNS2)
14165 return NNS1;
14166
14167 // IsSame implies both Qualifiers are equivalent.
14168 NestedNameSpecifier Canon = NNS1.getCanonical();
14169 if (Canon != NNS2.getCanonical()) {
14170 assert(!IsSame && "Should be the same NestedNameSpecifier");
14171 // If they are not the same, there is nothing to unify.
14172 return std::nullopt;
14173 }
14174
14175 NestedNameSpecifier R = std::nullopt;
14176 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14177 assert(Kind == NNS2.getKind());
14178 switch (Kind) {
14179 case NestedNameSpecifier::Kind::Namespace: {
14180 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14181 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14182 auto Kind = Namespace1->getKind();
14183 if (Kind != Namespace2->getKind() ||
14184 (Kind == Decl::NamespaceAlias &&
14185 !declaresSameEntity(D1: Namespace1, D2: Namespace2))) {
14186 R = NestedNameSpecifier(
14187 Ctx,
14188 ::getCommonDeclChecked(X: Namespace1->getNamespace(),
14189 Y: Namespace2->getNamespace()),
14190 /*Prefix=*/std::nullopt);
14191 break;
14192 }
14193 // The prefixes for namespaces are not significant, its declaration
14194 // identifies it uniquely.
14195 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, NNS1: Prefix1, NNS2: Prefix2,
14196 /*IsSame=*/false);
14197 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(X: Namespace1, Y: Namespace2),
14198 Prefix);
14199 break;
14200 }
14201 case NestedNameSpecifier::Kind::Type: {
14202 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14203 const Type *T = Ctx.getCommonSugaredType(X: QualType(T1, 0), Y: QualType(T2, 0),
14204 /*Unqualified=*/true)
14205 .getTypePtr();
14206 R = NestedNameSpecifier(T);
14207 break;
14208 }
14209 case NestedNameSpecifier::Kind::MicrosoftSuper: {
14210 // FIXME: Can __super even be used with data members?
14211 // If it's only usable in functions, we will never see it here,
14212 // unless we save the qualifiers used in function types.
14213 // In that case, it might be possible NNS2 is a type,
14214 // in which case we should degrade the result to
14215 // a CXXRecordType.
14216 R = NestedNameSpecifier(getCommonDeclChecked(X: NNS1.getAsMicrosoftSuper(),
14217 Y: NNS2.getAsMicrosoftSuper()));
14218 break;
14219 }
14220 case NestedNameSpecifier::Kind::Null:
14221 case NestedNameSpecifier::Kind::Global:
14222 // These are singletons.
14223 llvm_unreachable("singletons did not compare equal");
14224 }
14225 assert(R.getCanonical() == Canon);
14226 return R;
14227}
14228
14229template <class T>
14230static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X,
14231 const T *Y, bool IsSame) {
14232 return ::getCommonNNS(Ctx, NNS1: X->getQualifier(), NNS2: Y->getQualifier(), IsSame);
14233}
14234
14235template <class T>
14236static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14237 const T *Y) {
14238 return Ctx.getCommonSugaredType(X: X->getElementType(), Y: Y->getElementType());
14239}
14240
14241static QualType getCommonTypeWithQualifierLifting(const ASTContext &Ctx,
14242 QualType X, QualType Y,
14243 Qualifiers &QX,
14244 Qualifiers &QY) {
14245 QualType R = Ctx.getCommonSugaredType(X, Y,
14246 /*Unqualified=*/true);
14247 // Qualifiers common to both element types.
14248 Qualifiers RQ = R.getQualifiers();
14249 // For each side, move to the top level any qualifiers which are not common to
14250 // both element types. The caller must assume top level qualifiers might
14251 // be different, even if they are the same type, and can be treated as sugar.
14252 QX += X.getQualifiers() - RQ;
14253 QY += Y.getQualifiers() - RQ;
14254 return R;
14255}
14256
14257template <class T>
14258static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X,
14259 Qualifiers &QX, const T *Y,
14260 Qualifiers &QY) {
14261 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14262 Y->getElementType(), QX, QY);
14263}
14264
14265template <class T>
14266static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14267 const T *Y) {
14268 return Ctx.getCommonSugaredType(X: X->getPointeeType(), Y: Y->getPointeeType());
14269}
14270
14271template <class T>
14272static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14273 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14274 return X->getSizeExpr();
14275}
14276
14277static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14278 assert(X->getSizeModifier() == Y->getSizeModifier());
14279 return X->getSizeModifier();
14280}
14281
14282static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X,
14283 const ArrayType *Y) {
14284 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14285 return X->getIndexTypeCVRQualifiers();
14286}
14287
14288// Merges two type lists such that the resulting vector will contain
14289// each type (in a canonical sense) only once, in the order they appear
14290// from X to Y. If they occur in both X and Y, the result will contain
14291// the common sugared type between them.
14292static void mergeTypeLists(const ASTContext &Ctx,
14293 SmallVectorImpl<QualType> &Out, ArrayRef<QualType> X,
14294 ArrayRef<QualType> Y) {
14295 llvm::DenseMap<QualType, unsigned> Found;
14296 for (auto Ts : {X, Y}) {
14297 for (QualType T : Ts) {
14298 auto Res = Found.try_emplace(Key: Ctx.getCanonicalType(T), Args: Out.size());
14299 if (!Res.second) {
14300 QualType &U = Out[Res.first->second];
14301 U = Ctx.getCommonSugaredType(X: U, Y: T);
14302 } else {
14303 Out.emplace_back(Args&: T);
14304 }
14305 }
14306 }
14307}
14308
14309FunctionProtoType::ExceptionSpecInfo
14310ASTContext::mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1,
14311 FunctionProtoType::ExceptionSpecInfo ESI2,
14312 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14313 bool AcceptDependent) const {
14314 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14315
14316 // If either of them can throw anything, that is the result.
14317 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14318 if (EST1 == I)
14319 return ESI1;
14320 if (EST2 == I)
14321 return ESI2;
14322 }
14323
14324 // If either of them is non-throwing, the result is the other.
14325 for (auto I :
14326 {EST_NoThrow, EST_DynamicNone, EST_BasicNoexcept, EST_NoexceptTrue}) {
14327 if (EST1 == I)
14328 return ESI2;
14329 if (EST2 == I)
14330 return ESI1;
14331 }
14332
14333 // If we're left with value-dependent computed noexcept expressions, we're
14334 // stuck. Before C++17, we can just drop the exception specification entirely,
14335 // since it's not actually part of the canonical type. And this should never
14336 // happen in C++17, because it would mean we were computing the composite
14337 // pointer type of dependent types, which should never happen.
14338 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14339 assert(AcceptDependent &&
14340 "computing composite pointer type of dependent types");
14341 return FunctionProtoType::ExceptionSpecInfo();
14342 }
14343
14344 // Switch over the possibilities so that people adding new values know to
14345 // update this function.
14346 switch (EST1) {
14347 case EST_None:
14348 case EST_DynamicNone:
14349 case EST_MSAny:
14350 case EST_BasicNoexcept:
14351 case EST_DependentNoexcept:
14352 case EST_NoexceptFalse:
14353 case EST_NoexceptTrue:
14354 case EST_NoThrow:
14355 llvm_unreachable("These ESTs should be handled above");
14356
14357 case EST_Dynamic: {
14358 // This is the fun case: both exception specifications are dynamic. Form
14359 // the union of the two lists.
14360 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14361 mergeTypeLists(Ctx: *this, Out&: ExceptionTypeStorage, X: ESI1.Exceptions,
14362 Y: ESI2.Exceptions);
14363 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
14364 Result.Exceptions = ExceptionTypeStorage;
14365 return Result;
14366 }
14367
14368 case EST_Unevaluated:
14369 case EST_Uninstantiated:
14370 case EST_Unparsed:
14371 llvm_unreachable("shouldn't see unresolved exception specifications here");
14372 }
14373
14374 llvm_unreachable("invalid ExceptionSpecificationType");
14375}
14376
14377static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X,
14378 Qualifiers &QX, const Type *Y,
14379 Qualifiers &QY) {
14380 Type::TypeClass TC = X->getTypeClass();
14381 assert(TC == Y->getTypeClass());
14382 switch (TC) {
14383#define UNEXPECTED_TYPE(Class, Kind) \
14384 case Type::Class: \
14385 llvm_unreachable("Unexpected " Kind ": " #Class);
14386
14387#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14388#define TYPE(Class, Base)
14389#include "clang/AST/TypeNodes.inc"
14390
14391#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14392 SUGAR_FREE_TYPE(Builtin)
14393 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14394 SUGAR_FREE_TYPE(DependentBitInt)
14395 SUGAR_FREE_TYPE(BitInt)
14396 SUGAR_FREE_TYPE(ObjCInterface)
14397 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14398 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14399 SUGAR_FREE_TYPE(UnresolvedUsing)
14400 SUGAR_FREE_TYPE(HLSLAttributedResource)
14401 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14402#undef SUGAR_FREE_TYPE
14403#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14404 NON_UNIQUE_TYPE(TypeOfExpr)
14405 NON_UNIQUE_TYPE(VariableArray)
14406#undef NON_UNIQUE_TYPE
14407
14408 UNEXPECTED_TYPE(TypeOf, "sugar")
14409
14410#undef UNEXPECTED_TYPE
14411
14412 case Type::Auto: {
14413 const auto *AX = cast<AutoType>(Val: X), *AY = cast<AutoType>(Val: Y);
14414 assert(AX->getDeducedKind() == AY->getDeducedKind());
14415 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14416 assert(AX->getKeyword() == AY->getKeyword());
14417 TemplateDecl *CD = ::getCommonDecl(X: AX->getTypeConstraintConcept(),
14418 Y: AY->getTypeConstraintConcept());
14419 SmallVector<TemplateArgument, 8> As;
14420 if (CD &&
14421 getCommonTemplateArguments(Ctx, R&: As, Xs: AX->getTypeConstraintArguments(),
14422 Ys: AY->getTypeConstraintArguments())) {
14423 CD = nullptr; // The arguments differ, so make it unconstrained.
14424 As.clear();
14425 }
14426 return Ctx.getAutoType(DK: AX->getDeducedKind(), DeducedAsType: QualType(), Keyword: AX->getKeyword(),
14427 TypeConstraintConcept: CD, TypeConstraintArgs: As);
14428 }
14429 case Type::IncompleteArray: {
14430 const auto *AX = cast<IncompleteArrayType>(Val: X),
14431 *AY = cast<IncompleteArrayType>(Val: Y);
14432 return Ctx.getIncompleteArrayType(
14433 elementType: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY),
14434 ASM: getCommonSizeModifier(X: AX, Y: AY), elementTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14435 }
14436 case Type::DependentSizedArray: {
14437 const auto *AX = cast<DependentSizedArrayType>(Val: X),
14438 *AY = cast<DependentSizedArrayType>(Val: Y);
14439 return Ctx.getDependentSizedArrayType(
14440 elementType: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY),
14441 numElements: getCommonSizeExpr(Ctx, X: AX, Y: AY), ASM: getCommonSizeModifier(X: AX, Y: AY),
14442 elementTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14443 }
14444 case Type::ConstantArray: {
14445 const auto *AX = cast<ConstantArrayType>(Val: X),
14446 *AY = cast<ConstantArrayType>(Val: Y);
14447 assert(AX->getSize() == AY->getSize());
14448 const Expr *SizeExpr = Ctx.hasSameExpr(X: AX->getSizeExpr(), Y: AY->getSizeExpr())
14449 ? AX->getSizeExpr()
14450 : nullptr;
14451 return Ctx.getConstantArrayType(
14452 EltTy: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY), ArySizeIn: AX->getSize(), SizeExpr,
14453 ASM: getCommonSizeModifier(X: AX, Y: AY), IndexTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14454 }
14455 case Type::ArrayParameter: {
14456 const auto *AX = cast<ArrayParameterType>(Val: X),
14457 *AY = cast<ArrayParameterType>(Val: Y);
14458 assert(AX->getSize() == AY->getSize());
14459 const Expr *SizeExpr = Ctx.hasSameExpr(X: AX->getSizeExpr(), Y: AY->getSizeExpr())
14460 ? AX->getSizeExpr()
14461 : nullptr;
14462 auto ArrayTy = Ctx.getConstantArrayType(
14463 EltTy: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY), ArySizeIn: AX->getSize(), SizeExpr,
14464 ASM: getCommonSizeModifier(X: AX, Y: AY), IndexTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14465 return Ctx.getArrayParameterType(Ty: ArrayTy);
14466 }
14467 case Type::Atomic: {
14468 const auto *AX = cast<AtomicType>(Val: X), *AY = cast<AtomicType>(Val: Y);
14469 return Ctx.getAtomicType(
14470 T: Ctx.getCommonSugaredType(X: AX->getValueType(), Y: AY->getValueType()));
14471 }
14472 case Type::Complex: {
14473 const auto *CX = cast<ComplexType>(Val: X), *CY = cast<ComplexType>(Val: Y);
14474 return Ctx.getComplexType(T: getCommonArrayElementType(Ctx, X: CX, QX, Y: CY, QY));
14475 }
14476 case Type::Pointer: {
14477 const auto *PX = cast<PointerType>(Val: X), *PY = cast<PointerType>(Val: Y);
14478 return Ctx.getPointerType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14479 }
14480 case Type::BlockPointer: {
14481 const auto *PX = cast<BlockPointerType>(Val: X), *PY = cast<BlockPointerType>(Val: Y);
14482 return Ctx.getBlockPointerType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14483 }
14484 case Type::ObjCObjectPointer: {
14485 const auto *PX = cast<ObjCObjectPointerType>(Val: X),
14486 *PY = cast<ObjCObjectPointerType>(Val: Y);
14487 return Ctx.getObjCObjectPointerType(ObjectT: getCommonPointeeType(Ctx, X: PX, Y: PY));
14488 }
14489 case Type::MemberPointer: {
14490 const auto *PX = cast<MemberPointerType>(Val: X),
14491 *PY = cast<MemberPointerType>(Val: Y);
14492 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14493 PY->getMostRecentCXXRecordDecl()));
14494 return Ctx.getMemberPointerType(
14495 T: getCommonPointeeType(Ctx, X: PX, Y: PY),
14496 Qualifier: getCommonQualifier(Ctx, X: PX, Y: PY, /*IsSame=*/true),
14497 Cls: PX->getMostRecentCXXRecordDecl());
14498 }
14499 case Type::LValueReference: {
14500 const auto *PX = cast<LValueReferenceType>(Val: X),
14501 *PY = cast<LValueReferenceType>(Val: Y);
14502 // FIXME: Preserve PointeeTypeAsWritten.
14503 return Ctx.getLValueReferenceType(T: getCommonPointeeType(Ctx, X: PX, Y: PY),
14504 SpelledAsLValue: PX->isSpelledAsLValue() ||
14505 PY->isSpelledAsLValue());
14506 }
14507 case Type::RValueReference: {
14508 const auto *PX = cast<RValueReferenceType>(Val: X),
14509 *PY = cast<RValueReferenceType>(Val: Y);
14510 // FIXME: Preserve PointeeTypeAsWritten.
14511 return Ctx.getRValueReferenceType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14512 }
14513 case Type::DependentAddressSpace: {
14514 const auto *PX = cast<DependentAddressSpaceType>(Val: X),
14515 *PY = cast<DependentAddressSpaceType>(Val: Y);
14516 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14517 return Ctx.getDependentAddressSpaceType(PointeeType: getCommonPointeeType(Ctx, X: PX, Y: PY),
14518 AddrSpaceExpr: PX->getAddrSpaceExpr(),
14519 AttrLoc: getCommonAttrLoc(X: PX, Y: PY));
14520 }
14521 case Type::FunctionNoProto: {
14522 const auto *FX = cast<FunctionNoProtoType>(Val: X),
14523 *FY = cast<FunctionNoProtoType>(Val: Y);
14524 assert(FX->getExtInfo() == FY->getExtInfo());
14525 return Ctx.getFunctionNoProtoType(
14526 ResultTy: Ctx.getCommonSugaredType(X: FX->getReturnType(), Y: FY->getReturnType()),
14527 Info: FX->getExtInfo());
14528 }
14529 case Type::FunctionProto: {
14530 const auto *FX = cast<FunctionProtoType>(Val: X),
14531 *FY = cast<FunctionProtoType>(Val: Y);
14532 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14533 EPIY = FY->getExtProtoInfo();
14534 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14535 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14536 assert(!EPIX.ExtParameterInfos ||
14537 llvm::equal(
14538 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14539 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14540 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14541 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14542 assert(EPIX.Variadic == EPIY.Variadic);
14543
14544 // FIXME: Can we handle an empty EllipsisLoc?
14545 // Use emtpy EllipsisLoc if X and Y differ.
14546
14547 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14548
14549 QualType R =
14550 Ctx.getCommonSugaredType(X: FX->getReturnType(), Y: FY->getReturnType());
14551 auto P = getCommonTypes(Ctx, Xs: FX->param_types(), Ys: FY->param_types(),
14552 /*Unqualified=*/true);
14553
14554 SmallVector<QualType, 8> Exceptions;
14555 EPIX.ExceptionSpec = Ctx.mergeExceptionSpecs(
14556 ESI1: EPIX.ExceptionSpec, ESI2: EPIY.ExceptionSpec, ExceptionTypeStorage&: Exceptions, AcceptDependent: true);
14557 return Ctx.getFunctionType(ResultTy: R, Args: P, EPI: EPIX);
14558 }
14559 case Type::ObjCObject: {
14560 const auto *OX = cast<ObjCObjectType>(Val: X), *OY = cast<ObjCObjectType>(Val: Y);
14561 assert(
14562 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14563 OY->getProtocols().begin(), OY->getProtocols().end(),
14564 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14565 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14566 }) &&
14567 "protocol lists must be the same");
14568 auto TAs = getCommonTypes(Ctx, Xs: OX->getTypeArgsAsWritten(),
14569 Ys: OY->getTypeArgsAsWritten());
14570 return Ctx.getObjCObjectType(
14571 baseType: Ctx.getCommonSugaredType(X: OX->getBaseType(), Y: OY->getBaseType()), typeArgs: TAs,
14572 protocols: OX->getProtocols(),
14573 isKindOf: OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14574 }
14575 case Type::ConstantMatrix: {
14576 const auto *MX = cast<ConstantMatrixType>(Val: X),
14577 *MY = cast<ConstantMatrixType>(Val: Y);
14578 assert(MX->getNumRows() == MY->getNumRows());
14579 assert(MX->getNumColumns() == MY->getNumColumns());
14580 return Ctx.getConstantMatrixType(ElementTy: getCommonElementType(Ctx, X: MX, Y: MY),
14581 NumRows: MX->getNumRows(), NumColumns: MX->getNumColumns());
14582 }
14583 case Type::DependentSizedMatrix: {
14584 const auto *MX = cast<DependentSizedMatrixType>(Val: X),
14585 *MY = cast<DependentSizedMatrixType>(Val: Y);
14586 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14587 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14588 return Ctx.getDependentSizedMatrixType(
14589 ElementTy: getCommonElementType(Ctx, X: MX, Y: MY), RowExpr: MX->getRowExpr(),
14590 ColumnExpr: MX->getColumnExpr(), AttrLoc: getCommonAttrLoc(X: MX, Y: MY));
14591 }
14592 case Type::Vector: {
14593 const auto *VX = cast<VectorType>(Val: X), *VY = cast<VectorType>(Val: Y);
14594 assert(VX->getNumElements() == VY->getNumElements());
14595 assert(VX->getVectorKind() == VY->getVectorKind());
14596 return Ctx.getVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14597 NumElts: VX->getNumElements(), VecKind: VX->getVectorKind());
14598 }
14599 case Type::ExtVector: {
14600 const auto *VX = cast<ExtVectorType>(Val: X), *VY = cast<ExtVectorType>(Val: Y);
14601 assert(VX->getNumElements() == VY->getNumElements());
14602 return Ctx.getExtVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14603 NumElts: VX->getNumElements());
14604 }
14605 case Type::DependentSizedExtVector: {
14606 const auto *VX = cast<DependentSizedExtVectorType>(Val: X),
14607 *VY = cast<DependentSizedExtVectorType>(Val: Y);
14608 return Ctx.getDependentSizedExtVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14609 SizeExpr: getCommonSizeExpr(Ctx, X: VX, Y: VY),
14610 AttrLoc: getCommonAttrLoc(X: VX, Y: VY));
14611 }
14612 case Type::DependentVector: {
14613 const auto *VX = cast<DependentVectorType>(Val: X),
14614 *VY = cast<DependentVectorType>(Val: Y);
14615 assert(VX->getVectorKind() == VY->getVectorKind());
14616 return Ctx.getDependentVectorType(
14617 VecType: getCommonElementType(Ctx, X: VX, Y: VY), SizeExpr: getCommonSizeExpr(Ctx, X: VX, Y: VY),
14618 AttrLoc: getCommonAttrLoc(X: VX, Y: VY), VecKind: VX->getVectorKind());
14619 }
14620 case Type::Enum:
14621 case Type::Record:
14622 case Type::InjectedClassName: {
14623 const auto *TX = cast<TagType>(Val: X), *TY = cast<TagType>(Val: Y);
14624 return Ctx.getTagType(Keyword: ::getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14625 Qualifier: ::getCommonQualifier(Ctx, X: TX, Y: TY, /*IsSame=*/false),
14626 TD: ::getCommonDeclChecked(X: TX->getDecl(), Y: TY->getDecl()),
14627 /*OwnedTag=*/OwnsTag: false);
14628 }
14629 case Type::TemplateSpecialization: {
14630 const auto *TX = cast<TemplateSpecializationType>(Val: X),
14631 *TY = cast<TemplateSpecializationType>(Val: Y);
14632 auto As = getCommonTemplateArguments(Ctx, Xs: TX->template_arguments(),
14633 Ys: TY->template_arguments());
14634 return Ctx.getTemplateSpecializationType(
14635 Keyword: getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14636 Template: ::getCommonTemplateNameChecked(Ctx, X: TX->getTemplateName(),
14637 Y: TY->getTemplateName(),
14638 /*IgnoreDeduced=*/true),
14639 SpecifiedArgs: As, /*CanonicalArgs=*/{}, Underlying: X->getCanonicalTypeInternal());
14640 }
14641 case Type::Decltype: {
14642 const auto *DX = cast<DecltypeType>(Val: X);
14643 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Val: Y);
14644 assert(DX->isDependentType());
14645 assert(DY->isDependentType());
14646 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14647 // As Decltype is not uniqued, building a common type would be wasteful.
14648 return QualType(DX, 0);
14649 }
14650 case Type::PackIndexing: {
14651 const auto *DX = cast<PackIndexingType>(Val: X);
14652 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Val: Y);
14653 assert(DX->isDependentType());
14654 assert(DY->isDependentType());
14655 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14656 return QualType(DX, 0);
14657 }
14658 case Type::DependentName: {
14659 const auto *NX = cast<DependentNameType>(Val: X),
14660 *NY = cast<DependentNameType>(Val: Y);
14661 assert(NX->getIdentifier() == NY->getIdentifier());
14662 return Ctx.getDependentNameType(
14663 Keyword: getCommonTypeKeyword(X: NX, Y: NY, /*IsSame=*/true),
14664 NNS: getCommonQualifier(Ctx, X: NX, Y: NY, /*IsSame=*/true), Name: NX->getIdentifier());
14665 }
14666 case Type::OverflowBehavior: {
14667 const auto *NX = cast<OverflowBehaviorType>(Val: X),
14668 *NY = cast<OverflowBehaviorType>(Val: Y);
14669 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14670 return Ctx.getOverflowBehaviorType(
14671 Kind: NX->getBehaviorKind(),
14672 Underlying: getCommonTypeWithQualifierLifting(Ctx, X: NX->getUnderlyingType(),
14673 Y: NY->getUnderlyingType(), QX, QY));
14674 }
14675 case Type::UnaryTransform: {
14676 const auto *TX = cast<UnaryTransformType>(Val: X),
14677 *TY = cast<UnaryTransformType>(Val: Y);
14678 assert(TX->getUTTKind() == TY->getUTTKind());
14679 return Ctx.getUnaryTransformType(
14680 BaseType: Ctx.getCommonSugaredType(X: TX->getBaseType(), Y: TY->getBaseType()),
14681 UnderlyingType: Ctx.getCommonSugaredType(X: TX->getUnderlyingType(),
14682 Y: TY->getUnderlyingType()),
14683 Kind: TX->getUTTKind());
14684 }
14685 case Type::PackExpansion: {
14686 const auto *PX = cast<PackExpansionType>(Val: X),
14687 *PY = cast<PackExpansionType>(Val: Y);
14688 assert(PX->getNumExpansions() == PY->getNumExpansions());
14689 return Ctx.getPackExpansionType(
14690 Pattern: Ctx.getCommonSugaredType(X: PX->getPattern(), Y: PY->getPattern()),
14691 NumExpansions: PX->getNumExpansions(), ExpectPackInType: false);
14692 }
14693 case Type::Pipe: {
14694 const auto *PX = cast<PipeType>(Val: X), *PY = cast<PipeType>(Val: Y);
14695 assert(PX->isReadOnly() == PY->isReadOnly());
14696 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14697 : &ASTContext::getWritePipeType;
14698 return (Ctx.*MP)(getCommonElementType(Ctx, X: PX, Y: PY));
14699 }
14700 case Type::TemplateTypeParm: {
14701 const auto *TX = cast<TemplateTypeParmType>(Val: X),
14702 *TY = cast<TemplateTypeParmType>(Val: Y);
14703 assert(TX->getDepth() == TY->getDepth());
14704 assert(TX->getIndex() == TY->getIndex());
14705 assert(TX->isParameterPack() == TY->isParameterPack());
14706 return Ctx.getTemplateTypeParmType(
14707 Depth: TX->getDepth(), Index: TX->getIndex(), ParameterPack: TX->isParameterPack(),
14708 TTPDecl: getCommonDecl(X: TX->getDecl(), Y: TY->getDecl()));
14709 }
14710 }
14711 llvm_unreachable("Unknown Type Class");
14712}
14713
14714static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X,
14715 const Type *Y,
14716 SplitQualType Underlying) {
14717 Type::TypeClass TC = X->getTypeClass();
14718 if (TC != Y->getTypeClass())
14719 return QualType();
14720 switch (TC) {
14721#define UNEXPECTED_TYPE(Class, Kind) \
14722 case Type::Class: \
14723 llvm_unreachable("Unexpected " Kind ": " #Class);
14724#define TYPE(Class, Base)
14725#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14726#include "clang/AST/TypeNodes.inc"
14727
14728#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14729 CANONICAL_TYPE(Atomic)
14730 CANONICAL_TYPE(BitInt)
14731 CANONICAL_TYPE(BlockPointer)
14732 CANONICAL_TYPE(Builtin)
14733 CANONICAL_TYPE(Complex)
14734 CANONICAL_TYPE(ConstantArray)
14735 CANONICAL_TYPE(ArrayParameter)
14736 CANONICAL_TYPE(ConstantMatrix)
14737 CANONICAL_TYPE(Enum)
14738 CANONICAL_TYPE(ExtVector)
14739 CANONICAL_TYPE(FunctionNoProto)
14740 CANONICAL_TYPE(FunctionProto)
14741 CANONICAL_TYPE(IncompleteArray)
14742 CANONICAL_TYPE(HLSLAttributedResource)
14743 CANONICAL_TYPE(HLSLInlineSpirv)
14744 CANONICAL_TYPE(LValueReference)
14745 CANONICAL_TYPE(ObjCInterface)
14746 CANONICAL_TYPE(ObjCObject)
14747 CANONICAL_TYPE(ObjCObjectPointer)
14748 CANONICAL_TYPE(OverflowBehavior)
14749 CANONICAL_TYPE(Pipe)
14750 CANONICAL_TYPE(Pointer)
14751 CANONICAL_TYPE(Record)
14752 CANONICAL_TYPE(RValueReference)
14753 CANONICAL_TYPE(VariableArray)
14754 CANONICAL_TYPE(Vector)
14755#undef CANONICAL_TYPE
14756
14757#undef UNEXPECTED_TYPE
14758
14759 case Type::Adjusted: {
14760 const auto *AX = cast<AdjustedType>(Val: X), *AY = cast<AdjustedType>(Val: Y);
14761 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14762 if (!Ctx.hasSameType(T1: OX, T2: OY))
14763 return QualType();
14764 // FIXME: It's inefficient to have to unify the original types.
14765 return Ctx.getAdjustedType(Orig: Ctx.getCommonSugaredType(X: OX, Y: OY),
14766 New: Ctx.getQualifiedType(split: Underlying));
14767 }
14768 case Type::Decayed: {
14769 const auto *DX = cast<DecayedType>(Val: X), *DY = cast<DecayedType>(Val: Y);
14770 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14771 if (!Ctx.hasSameType(T1: OX, T2: OY))
14772 return QualType();
14773 // FIXME: It's inefficient to have to unify the original types.
14774 return Ctx.getDecayedType(Orig: Ctx.getCommonSugaredType(X: OX, Y: OY),
14775 Decayed: Ctx.getQualifiedType(split: Underlying));
14776 }
14777 case Type::Attributed: {
14778 const auto *AX = cast<AttributedType>(Val: X), *AY = cast<AttributedType>(Val: Y);
14779 AttributedType::Kind Kind = AX->getAttrKind();
14780 if (Kind != AY->getAttrKind())
14781 return QualType();
14782 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14783 if (!Ctx.hasSameType(T1: MX, T2: MY))
14784 return QualType();
14785 // FIXME: It's inefficient to have to unify the modified types.
14786 return Ctx.getAttributedType(attrKind: Kind, modifiedType: Ctx.getCommonSugaredType(X: MX, Y: MY),
14787 equivalentType: Ctx.getQualifiedType(split: Underlying),
14788 attr: AX->getAttr());
14789 }
14790 case Type::BTFTagAttributed: {
14791 const auto *BX = cast<BTFTagAttributedType>(Val: X);
14792 const BTFTypeTagAttr *AX = BX->getAttr();
14793 // The attribute is not uniqued, so just compare the tag.
14794 if (AX->getBTFTypeTag() !=
14795 cast<BTFTagAttributedType>(Val: Y)->getAttr()->getBTFTypeTag())
14796 return QualType();
14797 return Ctx.getBTFTagAttributedType(BTFAttr: AX, Wrapped: Ctx.getQualifiedType(split: Underlying));
14798 }
14799 case Type::Auto: {
14800 const auto *AX = cast<AutoType>(Val: X), *AY = cast<AutoType>(Val: Y);
14801 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14802 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14803
14804 AutoTypeKeyword KW = AX->getKeyword();
14805 if (KW != AY->getKeyword())
14806 return QualType();
14807
14808 TemplateDecl *CD = ::getCommonDecl(X: AX->getTypeConstraintConcept(),
14809 Y: AY->getTypeConstraintConcept());
14810 SmallVector<TemplateArgument, 8> As;
14811 if (CD &&
14812 getCommonTemplateArguments(Ctx, R&: As, Xs: AX->getTypeConstraintArguments(),
14813 Ys: AY->getTypeConstraintArguments())) {
14814 CD = nullptr; // The arguments differ, so make it unconstrained.
14815 As.clear();
14816 }
14817
14818 // Both auto types can't be dependent, otherwise they wouldn't have been
14819 // sugar. This implies they can't contain unexpanded packs either.
14820 return Ctx.getAutoType(DK: DeducedKind::Deduced,
14821 DeducedAsType: Ctx.getQualifiedType(split: Underlying), Keyword: AX->getKeyword(),
14822 TypeConstraintConcept: CD, TypeConstraintArgs: As);
14823 }
14824 case Type::PackIndexing:
14825 case Type::Decltype:
14826 return QualType();
14827 case Type::DeducedTemplateSpecialization:
14828 // FIXME: Try to merge these.
14829 return QualType();
14830 case Type::MacroQualified: {
14831 const auto *MX = cast<MacroQualifiedType>(Val: X),
14832 *MY = cast<MacroQualifiedType>(Val: Y);
14833 const IdentifierInfo *IX = MX->getMacroIdentifier();
14834 if (IX != MY->getMacroIdentifier())
14835 return QualType();
14836 return Ctx.getMacroQualifiedType(UnderlyingTy: Ctx.getQualifiedType(split: Underlying), MacroII: IX);
14837 }
14838 case Type::SubstTemplateTypeParm: {
14839 const auto *SX = cast<SubstTemplateTypeParmType>(Val: X),
14840 *SY = cast<SubstTemplateTypeParmType>(Val: Y);
14841 Decl *CD =
14842 ::getCommonDecl(X: SX->getAssociatedDecl(), Y: SY->getAssociatedDecl());
14843 if (!CD)
14844 return QualType();
14845 unsigned Index = SX->getIndex();
14846 if (Index != SY->getIndex())
14847 return QualType();
14848 auto PackIndex = SX->getPackIndex();
14849 if (PackIndex != SY->getPackIndex())
14850 return QualType();
14851 return Ctx.getSubstTemplateTypeParmType(Replacement: Ctx.getQualifiedType(split: Underlying),
14852 AssociatedDecl: CD, Index, PackIndex,
14853 Final: SX->getFinal() && SY->getFinal());
14854 }
14855 case Type::ObjCTypeParam:
14856 // FIXME: Try to merge these.
14857 return QualType();
14858 case Type::Paren:
14859 return Ctx.getParenType(InnerType: Ctx.getQualifiedType(split: Underlying));
14860
14861 case Type::TemplateSpecialization: {
14862 const auto *TX = cast<TemplateSpecializationType>(Val: X),
14863 *TY = cast<TemplateSpecializationType>(Val: Y);
14864 TemplateName CTN =
14865 ::getCommonTemplateName(Ctx, X: TX->getTemplateName(),
14866 Y: TY->getTemplateName(), /*IgnoreDeduced=*/true);
14867 if (!CTN.getAsVoidPointer())
14868 return QualType();
14869 SmallVector<TemplateArgument, 8> As;
14870 if (getCommonTemplateArguments(Ctx, R&: As, Xs: TX->template_arguments(),
14871 Ys: TY->template_arguments()))
14872 return QualType();
14873 return Ctx.getTemplateSpecializationType(
14874 Keyword: getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false), Template: CTN, SpecifiedArgs: As,
14875 /*CanonicalArgs=*/{}, Underlying: Ctx.getQualifiedType(split: Underlying));
14876 }
14877 case Type::Typedef: {
14878 const auto *TX = cast<TypedefType>(Val: X), *TY = cast<TypedefType>(Val: Y);
14879 const TypedefNameDecl *CD = ::getCommonDecl(X: TX->getDecl(), Y: TY->getDecl());
14880 if (!CD)
14881 return QualType();
14882 return Ctx.getTypedefType(
14883 Keyword: ::getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14884 Qualifier: ::getCommonQualifier(Ctx, X: TX, Y: TY, /*IsSame=*/false), Decl: CD,
14885 UnderlyingType: Ctx.getQualifiedType(split: Underlying));
14886 }
14887 case Type::TypeOf: {
14888 // The common sugar between two typeof expressions, where one is
14889 // potentially a typeof_unqual and the other is not, we unify to the
14890 // qualified type as that retains the most information along with the type.
14891 // We only return a typeof_unqual type when both types are unqual types.
14892 TypeOfKind Kind = TypeOfKind::Qualified;
14893 if (cast<TypeOfType>(Val: X)->getKind() == cast<TypeOfType>(Val: Y)->getKind() &&
14894 cast<TypeOfType>(Val: X)->getKind() == TypeOfKind::Unqualified)
14895 Kind = TypeOfKind::Unqualified;
14896 return Ctx.getTypeOfType(tofType: Ctx.getQualifiedType(split: Underlying), Kind);
14897 }
14898 case Type::TypeOfExpr:
14899 return QualType();
14900
14901 case Type::UnaryTransform: {
14902 const auto *UX = cast<UnaryTransformType>(Val: X),
14903 *UY = cast<UnaryTransformType>(Val: Y);
14904 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14905 if (KX != UY->getUTTKind())
14906 return QualType();
14907 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14908 if (!Ctx.hasSameType(T1: BX, T2: BY))
14909 return QualType();
14910 // FIXME: It's inefficient to have to unify the base types.
14911 return Ctx.getUnaryTransformType(BaseType: Ctx.getCommonSugaredType(X: BX, Y: BY),
14912 UnderlyingType: Ctx.getQualifiedType(split: Underlying), Kind: KX);
14913 }
14914 case Type::Using: {
14915 const auto *UX = cast<UsingType>(Val: X), *UY = cast<UsingType>(Val: Y);
14916 const UsingShadowDecl *CD = ::getCommonDecl(X: UX->getDecl(), Y: UY->getDecl());
14917 if (!CD)
14918 return QualType();
14919 return Ctx.getUsingType(Keyword: ::getCommonTypeKeyword(X: UX, Y: UY, /*IsSame=*/false),
14920 Qualifier: ::getCommonQualifier(Ctx, X: UX, Y: UY, /*IsSame=*/false),
14921 D: CD, UnderlyingType: Ctx.getQualifiedType(split: Underlying));
14922 }
14923 case Type::MemberPointer: {
14924 const auto *PX = cast<MemberPointerType>(Val: X),
14925 *PY = cast<MemberPointerType>(Val: Y);
14926 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14927 assert(Cls == PY->getMostRecentCXXRecordDecl());
14928 return Ctx.getMemberPointerType(
14929 T: ::getCommonPointeeType(Ctx, X: PX, Y: PY),
14930 Qualifier: ::getCommonQualifier(Ctx, X: PX, Y: PY, /*IsSame=*/false), Cls);
14931 }
14932 case Type::CountAttributed: {
14933 const auto *DX = cast<CountAttributedType>(Val: X),
14934 *DY = cast<CountAttributedType>(Val: Y);
14935 if (DX->isCountInBytes() != DY->isCountInBytes())
14936 return QualType();
14937 if (DX->isOrNull() != DY->isOrNull())
14938 return QualType();
14939 Expr *CEX = DX->getCountExpr();
14940 Expr *CEY = DY->getCountExpr();
14941 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14942 if (Ctx.hasSameExpr(X: CEX, Y: CEY))
14943 return Ctx.getCountAttributedType(WrappedTy: Ctx.getQualifiedType(split: Underlying), CountExpr: CEX,
14944 CountInBytes: DX->isCountInBytes(), OrNull: DX->isOrNull(),
14945 DependentDecls: CDX);
14946 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14947 return QualType();
14948 // Two declarations with the same integer constant may still differ in their
14949 // expression pointers, so we need to evaluate them.
14950 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14951 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14952 if (VX != VY)
14953 return QualType();
14954 return Ctx.getCountAttributedType(WrappedTy: Ctx.getQualifiedType(split: Underlying), CountExpr: CEX,
14955 CountInBytes: DX->isCountInBytes(), OrNull: DX->isOrNull(),
14956 DependentDecls: CDX);
14957 }
14958 case Type::PredefinedSugar:
14959 assert(cast<PredefinedSugarType>(X)->getKind() !=
14960 cast<PredefinedSugarType>(Y)->getKind());
14961 return QualType();
14962 }
14963 llvm_unreachable("Unhandled Type Class");
14964}
14965
14966static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14967 SmallVector<SplitQualType, 8> R;
14968 while (true) {
14969 QTotal.addConsistentQualifiers(qs: T.Quals);
14970 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
14971 if (NT == QualType(T.Ty, 0))
14972 break;
14973 R.push_back(Elt: T);
14974 T = NT.split();
14975 }
14976 return R;
14977}
14978
14979QualType ASTContext::getCommonSugaredType(QualType X, QualType Y,
14980 bool Unqualified) const {
14981 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14982 if (X == Y)
14983 return X;
14984 if (!Unqualified) {
14985 if (X.isCanonical())
14986 return X;
14987 if (Y.isCanonical())
14988 return Y;
14989 }
14990
14991 SplitQualType SX = X.split(), SY = Y.split();
14992 Qualifiers QX, QY;
14993 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14994 // until we reach their underlying "canonical nodes". Note these are not
14995 // necessarily canonical types, as they may still have sugared properties.
14996 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14997 auto Xs = ::unwrapSugar(T&: SX, QTotal&: QX), Ys = ::unwrapSugar(T&: SY, QTotal&: QY);
14998
14999 // If this is an ArrayType, the element qualifiers are interchangeable with
15000 // the top level qualifiers.
15001 // * In case the canonical nodes are the same, the elements types are already
15002 // the same.
15003 // * Otherwise, the element types will be made the same, and any different
15004 // element qualifiers will be moved up to the top level qualifiers, per
15005 // 'getCommonArrayElementType'.
15006 // In both cases, this means there may be top level qualifiers which differ
15007 // between X and Y. If so, these differing qualifiers are redundant with the
15008 // element qualifiers, and can be removed without changing the canonical type.
15009 // The desired behaviour is the same as for the 'Unqualified' case here:
15010 // treat the redundant qualifiers as sugar, remove the ones which are not
15011 // common to both sides.
15012 bool KeepCommonQualifiers =
15013 Unqualified || isa<ArrayType, OverflowBehaviorType>(Val: SX.Ty);
15014
15015 if (SX.Ty != SY.Ty) {
15016 // The canonical nodes differ. Build a common canonical node out of the two,
15017 // unifying their sugar. This may recurse back here.
15018 SX.Ty =
15019 ::getCommonNonSugarTypeNode(Ctx: *this, X: SX.Ty, QX, Y: SY.Ty, QY).getTypePtr();
15020 } else {
15021 // The canonical nodes were identical: We may have desugared too much.
15022 // Add any common sugar back in.
15023 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
15024 QX -= SX.Quals;
15025 QY -= SY.Quals;
15026 SX = Xs.pop_back_val();
15027 SY = Ys.pop_back_val();
15028 }
15029 }
15030 if (KeepCommonQualifiers)
15031 QX = Qualifiers::removeCommonQualifiers(L&: QX, R&: QY);
15032 else
15033 assert(QX == QY);
15034
15035 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
15036 // related. Walk up these nodes, unifying them and adding the result.
15037 while (!Xs.empty() && !Ys.empty()) {
15038 auto Underlying = SplitQualType(
15039 SX.Ty, Qualifiers::removeCommonQualifiers(L&: SX.Quals, R&: SY.Quals));
15040 SX = Xs.pop_back_val();
15041 SY = Ys.pop_back_val();
15042 SX.Ty = ::getCommonSugarTypeNode(Ctx: *this, X: SX.Ty, Y: SY.Ty, Underlying)
15043 .getTypePtrOrNull();
15044 // Stop at the first pair which is unrelated.
15045 if (!SX.Ty) {
15046 SX.Ty = Underlying.Ty;
15047 break;
15048 }
15049 QX -= Underlying.Quals;
15050 };
15051
15052 // Add back the missing accumulated qualifiers, which were stripped off
15053 // with the sugar nodes we could not unify.
15054 QualType R = getQualifiedType(T: SX.Ty, Qs: QX);
15055 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
15056 return R;
15057}
15058
15059QualType ASTContext::getCorrespondingUnsaturatedType(QualType Ty) const {
15060 assert(Ty->isFixedPointType());
15061
15062 if (Ty->isUnsaturatedFixedPointType())
15063 return Ty;
15064
15065 switch (Ty->castAs<BuiltinType>()->getKind()) {
15066 default:
15067 llvm_unreachable("Not a saturated fixed point type!");
15068 case BuiltinType::SatShortAccum:
15069 return ShortAccumTy;
15070 case BuiltinType::SatAccum:
15071 return AccumTy;
15072 case BuiltinType::SatLongAccum:
15073 return LongAccumTy;
15074 case BuiltinType::SatUShortAccum:
15075 return UnsignedShortAccumTy;
15076 case BuiltinType::SatUAccum:
15077 return UnsignedAccumTy;
15078 case BuiltinType::SatULongAccum:
15079 return UnsignedLongAccumTy;
15080 case BuiltinType::SatShortFract:
15081 return ShortFractTy;
15082 case BuiltinType::SatFract:
15083 return FractTy;
15084 case BuiltinType::SatLongFract:
15085 return LongFractTy;
15086 case BuiltinType::SatUShortFract:
15087 return UnsignedShortFractTy;
15088 case BuiltinType::SatUFract:
15089 return UnsignedFractTy;
15090 case BuiltinType::SatULongFract:
15091 return UnsignedLongFractTy;
15092 }
15093}
15094
15095QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
15096 assert(Ty->isFixedPointType());
15097
15098 if (Ty->isSaturatedFixedPointType()) return Ty;
15099
15100 switch (Ty->castAs<BuiltinType>()->getKind()) {
15101 default:
15102 llvm_unreachable("Not a fixed point type!");
15103 case BuiltinType::ShortAccum:
15104 return SatShortAccumTy;
15105 case BuiltinType::Accum:
15106 return SatAccumTy;
15107 case BuiltinType::LongAccum:
15108 return SatLongAccumTy;
15109 case BuiltinType::UShortAccum:
15110 return SatUnsignedShortAccumTy;
15111 case BuiltinType::UAccum:
15112 return SatUnsignedAccumTy;
15113 case BuiltinType::ULongAccum:
15114 return SatUnsignedLongAccumTy;
15115 case BuiltinType::ShortFract:
15116 return SatShortFractTy;
15117 case BuiltinType::Fract:
15118 return SatFractTy;
15119 case BuiltinType::LongFract:
15120 return SatLongFractTy;
15121 case BuiltinType::UShortFract:
15122 return SatUnsignedShortFractTy;
15123 case BuiltinType::UFract:
15124 return SatUnsignedFractTy;
15125 case BuiltinType::ULongFract:
15126 return SatUnsignedLongFractTy;
15127 }
15128}
15129
15130LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
15131 if (LangOpts.OpenCL)
15132 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
15133
15134 if (LangOpts.CUDA)
15135 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
15136
15137 return getLangASFromTargetAS(TargetAS: AS);
15138}
15139
15140// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
15141// doesn't include ASTContext.h
15142template
15143clang::LazyGenerationalUpdatePtr<
15144 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
15145clang::LazyGenerationalUpdatePtr<
15146 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
15147 const clang::ASTContext &Ctx, Decl *Value);
15148
15149unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
15150 assert(Ty->isFixedPointType());
15151
15152 const TargetInfo &Target = getTargetInfo();
15153 switch (Ty->castAs<BuiltinType>()->getKind()) {
15154 default:
15155 llvm_unreachable("Not a fixed point type!");
15156 case BuiltinType::ShortAccum:
15157 case BuiltinType::SatShortAccum:
15158 return Target.getShortAccumScale();
15159 case BuiltinType::Accum:
15160 case BuiltinType::SatAccum:
15161 return Target.getAccumScale();
15162 case BuiltinType::LongAccum:
15163 case BuiltinType::SatLongAccum:
15164 return Target.getLongAccumScale();
15165 case BuiltinType::UShortAccum:
15166 case BuiltinType::SatUShortAccum:
15167 return Target.getUnsignedShortAccumScale();
15168 case BuiltinType::UAccum:
15169 case BuiltinType::SatUAccum:
15170 return Target.getUnsignedAccumScale();
15171 case BuiltinType::ULongAccum:
15172 case BuiltinType::SatULongAccum:
15173 return Target.getUnsignedLongAccumScale();
15174 case BuiltinType::ShortFract:
15175 case BuiltinType::SatShortFract:
15176 return Target.getShortFractScale();
15177 case BuiltinType::Fract:
15178 case BuiltinType::SatFract:
15179 return Target.getFractScale();
15180 case BuiltinType::LongFract:
15181 case BuiltinType::SatLongFract:
15182 return Target.getLongFractScale();
15183 case BuiltinType::UShortFract:
15184 case BuiltinType::SatUShortFract:
15185 return Target.getUnsignedShortFractScale();
15186 case BuiltinType::UFract:
15187 case BuiltinType::SatUFract:
15188 return Target.getUnsignedFractScale();
15189 case BuiltinType::ULongFract:
15190 case BuiltinType::SatULongFract:
15191 return Target.getUnsignedLongFractScale();
15192 }
15193}
15194
15195unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
15196 assert(Ty->isFixedPointType());
15197
15198 const TargetInfo &Target = getTargetInfo();
15199 switch (Ty->castAs<BuiltinType>()->getKind()) {
15200 default:
15201 llvm_unreachable("Not a fixed point type!");
15202 case BuiltinType::ShortAccum:
15203 case BuiltinType::SatShortAccum:
15204 return Target.getShortAccumIBits();
15205 case BuiltinType::Accum:
15206 case BuiltinType::SatAccum:
15207 return Target.getAccumIBits();
15208 case BuiltinType::LongAccum:
15209 case BuiltinType::SatLongAccum:
15210 return Target.getLongAccumIBits();
15211 case BuiltinType::UShortAccum:
15212 case BuiltinType::SatUShortAccum:
15213 return Target.getUnsignedShortAccumIBits();
15214 case BuiltinType::UAccum:
15215 case BuiltinType::SatUAccum:
15216 return Target.getUnsignedAccumIBits();
15217 case BuiltinType::ULongAccum:
15218 case BuiltinType::SatULongAccum:
15219 return Target.getUnsignedLongAccumIBits();
15220 case BuiltinType::ShortFract:
15221 case BuiltinType::SatShortFract:
15222 case BuiltinType::Fract:
15223 case BuiltinType::SatFract:
15224 case BuiltinType::LongFract:
15225 case BuiltinType::SatLongFract:
15226 case BuiltinType::UShortFract:
15227 case BuiltinType::SatUShortFract:
15228 case BuiltinType::UFract:
15229 case BuiltinType::SatUFract:
15230 case BuiltinType::ULongFract:
15231 case BuiltinType::SatULongFract:
15232 return 0;
15233 }
15234}
15235
15236llvm::FixedPointSemantics
15237ASTContext::getFixedPointSemantics(QualType Ty) const {
15238 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15239 "Can only get the fixed point semantics for a "
15240 "fixed point or integer type.");
15241 if (Ty->isIntegerType())
15242 return llvm::FixedPointSemantics::GetIntegerSemantics(
15243 Width: getIntWidth(T: Ty), IsSigned: Ty->isSignedIntegerType());
15244
15245 bool isSigned = Ty->isSignedFixedPointType();
15246 return llvm::FixedPointSemantics(
15247 static_cast<unsigned>(getTypeSize(T: Ty)), getFixedPointScale(Ty), isSigned,
15248 Ty->isSaturatedFixedPointType(),
15249 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15250}
15251
15252llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15253 assert(Ty->isFixedPointType());
15254 return llvm::APFixedPoint::getMax(Sema: getFixedPointSemantics(Ty));
15255}
15256
15257llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15258 assert(Ty->isFixedPointType());
15259 return llvm::APFixedPoint::getMin(Sema: getFixedPointSemantics(Ty));
15260}
15261
15262QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
15263 assert(Ty->isUnsignedFixedPointType() &&
15264 "Expected unsigned fixed point type");
15265
15266 switch (Ty->castAs<BuiltinType>()->getKind()) {
15267 case BuiltinType::UShortAccum:
15268 return ShortAccumTy;
15269 case BuiltinType::UAccum:
15270 return AccumTy;
15271 case BuiltinType::ULongAccum:
15272 return LongAccumTy;
15273 case BuiltinType::SatUShortAccum:
15274 return SatShortAccumTy;
15275 case BuiltinType::SatUAccum:
15276 return SatAccumTy;
15277 case BuiltinType::SatULongAccum:
15278 return SatLongAccumTy;
15279 case BuiltinType::UShortFract:
15280 return ShortFractTy;
15281 case BuiltinType::UFract:
15282 return FractTy;
15283 case BuiltinType::ULongFract:
15284 return LongFractTy;
15285 case BuiltinType::SatUShortFract:
15286 return SatShortFractTy;
15287 case BuiltinType::SatUFract:
15288 return SatFractTy;
15289 case BuiltinType::SatULongFract:
15290 return SatLongFractTy;
15291 default:
15292 llvm_unreachable("Unexpected unsigned fixed point type");
15293 }
15294}
15295
15296// Given a list of FMV features, return a concatenated list of the
15297// corresponding backend features (which may contain duplicates).
15298static std::vector<std::string> getFMVBackendFeaturesFor(
15299 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15300 std::vector<std::string> BackendFeats;
15301 llvm::AArch64::ExtensionSet FeatureBits;
15302 for (StringRef F : FMVFeatStrings)
15303 if (auto FMVExt = llvm::AArch64::parseFMVExtension(Extension: F))
15304 if (FMVExt->ID)
15305 FeatureBits.enable(E: *FMVExt->ID);
15306 FeatureBits.toLLVMFeatureList(Features&: BackendFeats);
15307 return BackendFeats;
15308}
15309
15310ParsedTargetAttr
15311ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15312 assert(TD != nullptr);
15313 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: TD->getFeaturesStr());
15314
15315 llvm::erase_if(C&: ParsedAttr.Features, P: [&](const std::string &Feat) {
15316 return !Target->isValidFeatureName(Feature: StringRef{Feat}.substr(Start: 1));
15317 });
15318 return ParsedAttr;
15319}
15320
15321void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15322 const FunctionDecl *FD) const {
15323 if (FD)
15324 getFunctionFeatureMap(FeatureMap, GD: GlobalDecl().getWithDecl(D: FD));
15325 else
15326 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(),
15327 CPU: Target->getTargetOpts().CPU,
15328 FeatureVec: Target->getTargetOpts().Features);
15329}
15330
15331// Fills in the supplied string map with the set of target features for the
15332// passed in function.
15333void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15334 GlobalDecl GD) const {
15335 StringRef TargetCPU = Target->getTargetOpts().CPU;
15336 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15337 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15338 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
15339
15340 // Make a copy of the features as passed on the command line into the
15341 // beginning of the additional features from the function to override.
15342 // AArch64 handles command line option features in parseTargetAttr().
15343 if (!Target->getTriple().isAArch64())
15344 ParsedAttr.Features.insert(
15345 position: ParsedAttr.Features.begin(),
15346 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15347 last: Target->getTargetOpts().FeaturesAsWritten.end());
15348
15349 if (ParsedAttr.CPU != "" && Target->isValidCPUName(Name: ParsedAttr.CPU))
15350 TargetCPU = ParsedAttr.CPU;
15351
15352 // Now populate the feature map, first with the TargetCPU which is either
15353 // the default or a new one from the target attribute string. Then we'll use
15354 // the passed in features (FeaturesAsWritten) along with the new ones from
15355 // the attribute.
15356 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU,
15357 FeatureVec: ParsedAttr.Features);
15358 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15359 llvm::SmallVector<StringRef, 32> FeaturesTmp;
15360 Target->getCPUSpecificCPUDispatchFeatures(
15361 Name: SD->getCPUName(Index: GD.getMultiVersionIndex())->getName(), Features&: FeaturesTmp);
15362 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15363 Features.insert(position: Features.begin(),
15364 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15365 last: Target->getTargetOpts().FeaturesAsWritten.end());
15366 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15367 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15368 if (Target->getTriple().isAArch64()) {
15369 llvm::SmallVector<StringRef, 8> Feats;
15370 TC->getFeatures(Out&: Feats, Index: GD.getMultiVersionIndex());
15371 std::vector<std::string> Features = getFMVBackendFeaturesFor(FMVFeatStrings: Feats);
15372 Features.insert(position: Features.begin(),
15373 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15374 last: Target->getTargetOpts().FeaturesAsWritten.end());
15375 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15376 } else if (Target->getTriple().isRISCV()) {
15377 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15378 std::vector<std::string> Features;
15379 if (VersionStr != "default") {
15380 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: VersionStr);
15381 Features.insert(position: Features.begin(), first: ParsedAttr.Features.begin(),
15382 last: ParsedAttr.Features.end());
15383 }
15384 Features.insert(position: Features.begin(),
15385 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15386 last: Target->getTargetOpts().FeaturesAsWritten.end());
15387 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15388 } else if (Target->getTriple().isOSAIX()) {
15389 std::vector<std::string> Features;
15390 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15391 if (VersionStr.starts_with(Prefix: "cpu="))
15392 TargetCPU = VersionStr.drop_front(N: sizeof("cpu=") - 1);
15393 else
15394 assert(VersionStr == "default");
15395 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15396 } else {
15397 std::vector<std::string> Features;
15398 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15399 if (VersionStr.starts_with(Prefix: "arch="))
15400 TargetCPU = VersionStr.drop_front(N: sizeof("arch=") - 1);
15401 else if (VersionStr != "default")
15402 Features.push_back(x: (StringRef{"+"} + VersionStr).str());
15403 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15404 }
15405 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15406 std::vector<std::string> Features;
15407 if (Target->getTriple().isRISCV()) {
15408 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: TV->getName());
15409 Features.insert(position: Features.begin(), first: ParsedAttr.Features.begin(),
15410 last: ParsedAttr.Features.end());
15411 } else {
15412 assert(Target->getTriple().isAArch64());
15413 llvm::SmallVector<StringRef, 8> Feats;
15414 TV->getFeatures(Out&: Feats);
15415 Features = getFMVBackendFeaturesFor(FMVFeatStrings: Feats);
15416 }
15417 Features.insert(position: Features.begin(),
15418 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15419 last: Target->getTargetOpts().FeaturesAsWritten.end());
15420 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15421 } else {
15422 FeatureMap = Target->getTargetOpts().FeatureMap;
15423 }
15424}
15425
15426static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context,
15427 CanQualType KernelNameType,
15428 const FunctionDecl *FD) {
15429 // Host and device compilation may use different ABIs and different ABIs
15430 // may allocate name mangling discriminators differently. A discriminator
15431 // override is used to ensure consistent discriminator allocation across
15432 // host and device compilation.
15433 auto DeviceDiscriminatorOverrider =
15434 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15435 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
15436 if (RD->isLambda())
15437 return RD->getDeviceLambdaManglingNumber();
15438 return std::nullopt;
15439 };
15440 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15441 Context, Diags&: Context.getDiagnostics(), Discriminator: DeviceDiscriminatorOverrider)};
15442
15443 // Construct a mangled name for the SYCL kernel caller offload entry point.
15444 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15445 // name the SYCL kernel caller offload entry point function. This mangling
15446 // does not suffice to clearly identify symbols that correspond to SYCL
15447 // kernel caller functions, nor is this mangling natural for targets that
15448 // use a non-Itanium ABI.
15449 std::string Buffer;
15450 Buffer.reserve(res_arg: 128);
15451 llvm::raw_string_ostream Out(Buffer);
15452 MC->mangleCanonicalTypeName(T: KernelNameType, Out);
15453 std::string KernelName = Out.str();
15454
15455 return {KernelNameType, FD, KernelName};
15456}
15457
15458void ASTContext::registerSYCLEntryPointFunction(FunctionDecl *FD) {
15459 // If the function declaration to register is invalid or dependent, the
15460 // registration attempt is ignored.
15461 if (FD->isInvalidDecl() || FD->isTemplated())
15462 return;
15463
15464 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15465 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15466
15467 // Be tolerant of multiple registration attempts so long as each attempt
15468 // is for the same entity. Callers are obligated to detect and diagnose
15469 // conflicting kernel names prior to calling this function.
15470 CanQualType KernelNameType = getCanonicalType(T: SKEPAttr->getKernelName());
15471 auto IT = SYCLKernels.find(Val: KernelNameType);
15472 assert((IT == SYCLKernels.end() ||
15473 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15474 "SYCL kernel name conflict");
15475 (void)IT;
15476 SYCLKernels.insert(KV: std::make_pair(
15477 x&: KernelNameType, y: BuildSYCLKernelInfo(Context&: *this, KernelNameType, FD)));
15478}
15479
15480const SYCLKernelInfo &ASTContext::getSYCLKernelInfo(QualType T) const {
15481 CanQualType KernelNameType = getCanonicalType(T);
15482 return SYCLKernels.at(Val: KernelNameType);
15483}
15484
15485const SYCLKernelInfo *ASTContext::findSYCLKernelInfo(QualType T) const {
15486 CanQualType KernelNameType = getCanonicalType(T);
15487 auto IT = SYCLKernels.find(Val: KernelNameType);
15488 if (IT != SYCLKernels.end())
15489 return &IT->second;
15490 return nullptr;
15491}
15492
15493OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
15494 OMPTraitInfoVector.emplace_back(Args: new OMPTraitInfo());
15495 return *OMPTraitInfoVector.back();
15496}
15497
15498const StreamingDiagnostic &clang::
15499operator<<(const StreamingDiagnostic &DB,
15500 const ASTContext::SectionInfo &Section) {
15501 if (Section.Decl)
15502 return DB << Section.Decl;
15503 return DB << "a prior #pragma section";
15504}
15505
15506bool ASTContext::mayExternalize(const Decl *D) const {
15507 bool IsInternalVar =
15508 isa<VarDecl>(Val: D) &&
15509 basicGVALinkageForVariable(Context: *this, VD: cast<VarDecl>(Val: D)) == GVA_Internal;
15510 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15511 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15512 (D->hasAttr<CUDAConstantAttr>() &&
15513 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15514 // CUDA/HIP: managed variables need to be externalized since it is
15515 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15516 // anonymous name space needs to be externalized to avoid duplicate symbols.
15517 return (IsInternalVar &&
15518 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15519 (D->hasAttr<CUDAGlobalAttr>() &&
15520 basicGVALinkageForFunction(Context: *this, FD: cast<FunctionDecl>(Val: D)) ==
15521 GVA_Internal);
15522}
15523
15524bool ASTContext::shouldExternalize(const Decl *D) const {
15525 return mayExternalize(D) &&
15526 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15527 CUDADeviceVarODRUsedByHost.count(key: cast<VarDecl>(Val: D)));
15528}
15529
15530StringRef ASTContext::getCUIDHash() const {
15531 if (!CUIDHash.empty())
15532 return CUIDHash;
15533 if (LangOpts.CUID.empty())
15534 return StringRef();
15535 CUIDHash = llvm::utohexstr(X: llvm::MD5Hash(Str: LangOpts.CUID), /*LowerCase=*/true);
15536 return CUIDHash;
15537}
15538
15539const CXXRecordDecl *
15540ASTContext::baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const {
15541 assert(ThisClass);
15542 assert(ThisClass->isPolymorphic());
15543 const CXXRecordDecl *PrimaryBase = ThisClass;
15544 while (1) {
15545 assert(PrimaryBase);
15546 assert(PrimaryBase->isPolymorphic());
15547 auto &Layout = getASTRecordLayout(D: PrimaryBase);
15548 auto Base = Layout.getPrimaryBase();
15549 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15550 break;
15551 PrimaryBase = Base;
15552 }
15553 return PrimaryBase;
15554}
15555
15556bool ASTContext::useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl,
15557 StringRef MangledName) {
15558 auto *Method = cast<CXXMethodDecl>(Val: VirtualMethodDecl.getDecl());
15559 assert(Method->isVirtual());
15560 bool DefaultIncludesPointerAuth =
15561 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15562
15563 if (!DefaultIncludesPointerAuth)
15564 return true;
15565
15566 auto Existing = ThunksToBeAbbreviated.find(Val: VirtualMethodDecl);
15567 if (Existing != ThunksToBeAbbreviated.end())
15568 return Existing->second.contains(key: MangledName.str());
15569
15570 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15571 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15572 auto VtableContext = getVTableContext();
15573 if (const auto *ThunkInfos = VtableContext->getThunkInfo(GD: VirtualMethodDecl)) {
15574 auto *Destructor = dyn_cast<CXXDestructorDecl>(Val: Method);
15575 for (const auto &Thunk : *ThunkInfos) {
15576 SmallString<256> ElidedName;
15577 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15578 if (Destructor)
15579 Mangler->mangleCXXDtorThunk(DD: Destructor, Type: VirtualMethodDecl.getDtorType(),
15580 Thunk, /* elideOverrideInfo */ ElideOverrideInfo: true,
15581 ElidedNameStream);
15582 else
15583 Mangler->mangleThunk(MD: Method, Thunk, /* elideOverrideInfo */ ElideOverrideInfo: true,
15584 ElidedNameStream);
15585 SmallString<256> MangledName;
15586 llvm::raw_svector_ostream mangledNameStream(MangledName);
15587 if (Destructor)
15588 Mangler->mangleCXXDtorThunk(DD: Destructor, Type: VirtualMethodDecl.getDtorType(),
15589 Thunk, /* elideOverrideInfo */ ElideOverrideInfo: false,
15590 mangledNameStream);
15591 else
15592 Mangler->mangleThunk(MD: Method, Thunk, /* elideOverrideInfo */ ElideOverrideInfo: false,
15593 mangledNameStream);
15594
15595 Thunks[ElidedName].push_back(Elt: std::string(MangledName));
15596 }
15597 }
15598 llvm::StringSet<> SimplifiedThunkNames;
15599 for (auto &ThunkList : Thunks) {
15600 llvm::sort(C&: ThunkList.second);
15601 SimplifiedThunkNames.insert(key: ThunkList.second[0]);
15602 }
15603 bool Result = SimplifiedThunkNames.contains(key: MangledName);
15604 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15605 return Result;
15606}
15607
15608bool ASTContext::arePFPFieldsTriviallyCopyable(const RecordDecl *RD) const {
15609 // Check for trivially-destructible here because non-trivially-destructible
15610 // types will always cause the type and any types derived from it to be
15611 // considered non-trivially-copyable. The same cannot be said for
15612 // trivially-copyable because deleting special members of a type derived from
15613 // a non-trivially-copyable type can cause the derived type to be considered
15614 // trivially copyable.
15615 if (getLangOpts().PointerFieldProtectionTagged)
15616 return !isa<CXXRecordDecl>(Val: RD) ||
15617 cast<CXXRecordDecl>(Val: RD)->hasTrivialDestructor();
15618 return true;
15619}
15620
15621static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15622 std::vector<PFPField> &Fields, bool IncludeVBases) {
15623 if (auto *AT = Ctx.getAsConstantArrayType(T: Ty)) {
15624 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15625 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(D: ElemDecl);
15626 for (unsigned i = 0; i != AT->getSize(); ++i)
15627 findPFPFields(Ctx, Ty: AT->getElementType(), Offset: Offset + i * ElemRL.getSize(),
15628 Fields, IncludeVBases: true);
15629 }
15630 }
15631 auto *Decl = Ty->getAsCXXRecordDecl();
15632 // isPFPType() is inherited from bases and members (including via arrays), so
15633 // we can early exit if it is false. Unions are excluded per the API
15634 // documentation.
15635 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15636 return;
15637 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(D: Decl);
15638 for (FieldDecl *Field : Decl->fields()) {
15639 CharUnits FieldOffset =
15640 Offset +
15641 Ctx.toCharUnitsFromBits(BitSize: RL.getFieldOffset(FieldNo: Field->getFieldIndex()));
15642 if (Ctx.isPFPField(Field))
15643 Fields.push_back(x: {.Offset: FieldOffset, .Field: Field});
15644 findPFPFields(Ctx, Ty: Field->getType(), Offset: FieldOffset, Fields,
15645 /*IncludeVBases=*/true);
15646 }
15647 // Pass false for IncludeVBases below because vbases are only included in
15648 // layout for top-level types, i.e. not bases or vbases.
15649 for (CXXBaseSpecifier &Base : Decl->bases()) {
15650 if (Base.isVirtual())
15651 continue;
15652 CharUnits BaseOffset =
15653 Offset + RL.getBaseClassOffset(Base: Base.getType()->getAsCXXRecordDecl());
15654 findPFPFields(Ctx, Ty: Base.getType(), Offset: BaseOffset, Fields,
15655 /*IncludeVBases=*/false);
15656 }
15657 if (IncludeVBases) {
15658 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15659 CharUnits BaseOffset =
15660 Offset + RL.getVBaseClassOffset(VBase: Base.getType()->getAsCXXRecordDecl());
15661 findPFPFields(Ctx, Ty: Base.getType(), Offset: BaseOffset, Fields,
15662 /*IncludeVBases=*/false);
15663 }
15664 }
15665}
15666
15667std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15668 std::vector<PFPField> PFPFields;
15669 ::findPFPFields(Ctx: *this, Ty, Offset: CharUnits::Zero(), Fields&: PFPFields, IncludeVBases: true);
15670 return PFPFields;
15671}
15672
15673bool ASTContext::hasPFPFields(QualType Ty) const {
15674 return !findPFPFields(Ty).empty();
15675}
15676
15677bool ASTContext::isPFPField(const FieldDecl *FD) const {
15678 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: FD->getParent()))
15679 return RD->isPFPType() && FD->getType()->isPointerType() &&
15680 !FD->hasAttr<NoFieldProtectionAttr>();
15681 return false;
15682}
15683
15684void ASTContext::recordMemberDataPointerEvaluation(const ValueDecl *VD) {
15685 auto *FD = dyn_cast<FieldDecl>(Val: VD);
15686 if (!FD)
15687 FD = cast<FieldDecl>(Val: cast<IndirectFieldDecl>(Val: VD)->chain().back());
15688 if (isPFPField(FD))
15689 PFPFieldsWithEvaluatedOffset.insert(X: FD);
15690}
15691
15692void ASTContext::recordOffsetOfEvaluation(const OffsetOfExpr *E) {
15693 if (E->getNumComponents() == 0)
15694 return;
15695 OffsetOfNode Comp = E->getComponent(Idx: E->getNumComponents() - 1);
15696 if (Comp.getKind() != OffsetOfNode::Field)
15697 return;
15698 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15699 PFPFieldsWithEvaluatedOffset.insert(X: FD);
15700}
15701