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 HLSLAttributedResourceTypes(this_()),
942 SubstTemplateTemplateParmPacks(this_()), DeducedTemplates(this_()),
943 PackIndexingTemplates(this_()), ArrayParameterTypes(this_()),
944 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
945 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
946 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
947 LangOpts.XRayNeverInstrumentFiles,
948 LangOpts.XRayAttrListFiles, SM)),
949 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
950 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
951 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
952 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
953 CompCategories(this_()), LastSDM(nullptr, 0) {
954 addTranslationUnitDecl();
955}
956
957void ASTContext::cleanup() {
958 // Release the DenseMaps associated with DeclContext objects.
959 // FIXME: Is this the ideal solution?
960 ReleaseDeclContextMaps();
961
962 // Call all of the deallocation functions on all of their targets.
963 for (auto &Pair : Deallocations)
964 (Pair.first)(Pair.second);
965 Deallocations.clear();
966
967 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
968 // because they can contain DenseMaps.
969 for (llvm::DenseMap<const ObjCInterfaceDecl *,
970 const ASTRecordLayout *>::iterator
971 I = ObjCLayouts.begin(),
972 E = ObjCLayouts.end();
973 I != E;)
974 // Increment in loop to prevent using deallocated memory.
975 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
976 R->Destroy(Ctx&: *this);
977 ObjCLayouts.clear();
978
979 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
980 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
981 // Increment in loop to prevent using deallocated memory.
982 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
983 R->Destroy(Ctx&: *this);
984 }
985 ASTRecordLayouts.clear();
986
987 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
988 AEnd = DeclAttrs.end();
989 A != AEnd; ++A)
990 A->second->~AttrVec();
991 DeclAttrs.clear();
992
993 CtorClosureDefaultArgs.clear();
994
995 for (const auto &Value : ModuleInitializers)
996 Value.second->~PerModuleInitializers();
997 ModuleInitializers.clear();
998
999 TUDecl = nullptr;
1000 XRayFilter.reset();
1001 NoSanitizeL.reset();
1002}
1003
1004ASTContext::~ASTContext() { cleanup(); }
1005
1006void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1007 TraversalScope = TopLevelDecls;
1008 getParentMapContext().clear();
1009}
1010
1011void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1012 Deallocations.push_back(Elt: {Callback, Data});
1013}
1014
1015void
1016ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1017 ExternalSource = std::move(Source);
1018}
1019
1020void ASTContext::PrintStats() const {
1021 llvm::errs() << "\n*** AST Context Stats:\n";
1022 llvm::errs() << " " << Types.size() << " types total.\n";
1023
1024 unsigned counts[] = {
1025#define TYPE(Name, Parent) 0,
1026#define ABSTRACT_TYPE(Name, Parent)
1027#include "clang/AST/TypeNodes.inc"
1028 0 // Extra
1029 };
1030
1031 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1032 Type *T = Types[i];
1033 counts[(unsigned)T->getTypeClass()]++;
1034 }
1035
1036 unsigned Idx = 0;
1037 unsigned TotalBytes = 0;
1038#define TYPE(Name, Parent) \
1039 if (counts[Idx]) \
1040 llvm::errs() << " " << counts[Idx] << " " << #Name \
1041 << " types, " << sizeof(Name##Type) << " each " \
1042 << "(" << counts[Idx] * sizeof(Name##Type) \
1043 << " bytes)\n"; \
1044 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1045 ++Idx;
1046#define ABSTRACT_TYPE(Name, Parent)
1047#include "clang/AST/TypeNodes.inc"
1048
1049 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1050
1051 // Implicit special member functions.
1052 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1053 << NumImplicitDefaultConstructors
1054 << " implicit default constructors created\n";
1055 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1056 << NumImplicitCopyConstructors
1057 << " implicit copy constructors created\n";
1058 if (getLangOpts().CPlusPlus)
1059 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1060 << NumImplicitMoveConstructors
1061 << " implicit move constructors created\n";
1062 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1063 << NumImplicitCopyAssignmentOperators
1064 << " implicit copy assignment operators created\n";
1065 if (getLangOpts().CPlusPlus)
1066 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1067 << NumImplicitMoveAssignmentOperators
1068 << " implicit move assignment operators created\n";
1069 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1070 << NumImplicitDestructors
1071 << " implicit destructors created\n";
1072
1073 if (ExternalSource) {
1074 llvm::errs() << "\n";
1075 ExternalSource->PrintStats();
1076 }
1077
1078 BumpAlloc.PrintStats();
1079}
1080
1081void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1082 bool NotifyListeners) {
1083 if (NotifyListeners)
1084 if (auto *Listener = getASTMutationListener();
1085 Listener && !ND->isUnconditionallyVisible())
1086 Listener->RedefinedHiddenDefinition(D: ND, M);
1087
1088 MergedDefModules[cast<NamedDecl>(Val: ND->getCanonicalDecl())].push_back(NewVal: M);
1089}
1090
1091void ASTContext::deduplicateMergedDefinitionsFor(NamedDecl *ND) {
1092 auto It = MergedDefModules.find(Val: cast<NamedDecl>(Val: ND->getCanonicalDecl()));
1093 if (It == MergedDefModules.end())
1094 return;
1095
1096 auto &Merged = It->second;
1097 llvm::DenseSet<Module*> Found;
1098 for (Module *&M : Merged)
1099 if (!Found.insert(V: M).second)
1100 M = nullptr;
1101 llvm::erase(C&: Merged, V: nullptr);
1102}
1103
1104ArrayRef<Module *>
1105ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1106 auto MergedIt =
1107 MergedDefModules.find(Val: cast<NamedDecl>(Val: Def->getCanonicalDecl()));
1108 if (MergedIt == MergedDefModules.end())
1109 return {};
1110 return MergedIt->second;
1111}
1112
1113void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1114 if (LazyInitializers.empty())
1115 return;
1116
1117 auto *Source = Ctx.getExternalSource();
1118 assert(Source && "lazy initializers but no external source");
1119
1120 auto LazyInits = std::move(LazyInitializers);
1121 LazyInitializers.clear();
1122
1123 for (auto ID : LazyInits)
1124 Initializers.push_back(Elt: Source->GetExternalDecl(ID));
1125
1126 assert(LazyInitializers.empty() &&
1127 "GetExternalDecl for lazy module initializer added more inits");
1128}
1129
1130void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1131 // One special case: if we add a module initializer that imports another
1132 // module, and that module's only initializer is an ImportDecl, simplify.
1133 if (const auto *ID = dyn_cast<ImportDecl>(Val: D)) {
1134 auto It = ModuleInitializers.find(Val: ID->getImportedModule());
1135
1136 // Maybe the ImportDecl does nothing at all. (Common case.)
1137 if (It == ModuleInitializers.end())
1138 return;
1139
1140 // Maybe the ImportDecl only imports another ImportDecl.
1141 auto &Imported = *It->second;
1142 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1143 Imported.resolve(Ctx&: *this);
1144 auto *OnlyDecl = Imported.Initializers.front();
1145 if (isa<ImportDecl>(Val: OnlyDecl))
1146 D = OnlyDecl;
1147 }
1148 }
1149
1150 auto *&Inits = ModuleInitializers[M];
1151 if (!Inits)
1152 Inits = new (*this) PerModuleInitializers;
1153 Inits->Initializers.push_back(Elt: D);
1154}
1155
1156void ASTContext::addLazyModuleInitializers(Module *M,
1157 ArrayRef<GlobalDeclID> IDs) {
1158 auto *&Inits = ModuleInitializers[M];
1159 if (!Inits)
1160 Inits = new (*this) PerModuleInitializers;
1161 Inits->LazyInitializers.insert(I: Inits->LazyInitializers.end(),
1162 From: IDs.begin(), To: IDs.end());
1163}
1164
1165ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1166 auto It = ModuleInitializers.find(Val: M);
1167 if (It == ModuleInitializers.end())
1168 return {};
1169
1170 auto *Inits = It->second;
1171 Inits->resolve(Ctx&: *this);
1172 return Inits->Initializers;
1173}
1174
1175void ASTContext::setCurrentNamedModule(Module *M) {
1176 assert(M->isNamedModule());
1177 assert(!CurrentCXXNamedModule &&
1178 "We should set named module for ASTContext for only once");
1179 CurrentCXXNamedModule = M;
1180}
1181
1182bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1183 if (!M1 != !M2)
1184 return false;
1185
1186 /// Get the representative module for M. The representative module is the
1187 /// first module unit for a specific primary module name. So that the module
1188 /// units have the same representative module belongs to the same module.
1189 ///
1190 /// The process is helpful to reduce the expensive string operations.
1191 auto GetRepresentativeModule = [this](const Module *M) {
1192 auto Iter = SameModuleLookupSet.find(Val: M);
1193 if (Iter != SameModuleLookupSet.end())
1194 return Iter->second;
1195
1196 const Module *RepresentativeModule =
1197 PrimaryModuleNameMap.try_emplace(Key: M->getPrimaryModuleInterfaceName(), Args&: M)
1198 .first->second;
1199 SameModuleLookupSet[M] = RepresentativeModule;
1200 return RepresentativeModule;
1201 };
1202
1203 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1204 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1205}
1206
1207ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1208 if (!ExternCContext)
1209 ExternCContext = ExternCContextDecl::Create(C: *this, TU: getTranslationUnitDecl());
1210
1211 return ExternCContext;
1212}
1213
1214BuiltinTemplateDecl *
1215ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1216 const IdentifierInfo *II) const {
1217 auto *BuiltinTemplate =
1218 BuiltinTemplateDecl::Create(C: *this, DC: getTranslationUnitDecl(), Name: II, BTK);
1219 BuiltinTemplate->setImplicit();
1220 getTranslationUnitDecl()->addDecl(D: BuiltinTemplate);
1221
1222 return BuiltinTemplate;
1223}
1224
1225#define BuiltinTemplate(BTName) \
1226 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1227 if (!Decl##BTName) \
1228 Decl##BTName = \
1229 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1230 return Decl##BTName; \
1231 }
1232#include "clang/Basic/BuiltinTemplates.inc"
1233
1234RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1235 RecordDecl::TagKind TK) const {
1236 SourceLocation Loc;
1237 RecordDecl *NewDecl;
1238 if (getLangOpts().CPlusPlus)
1239 NewDecl = CXXRecordDecl::Create(C: *this, TK, DC: getTranslationUnitDecl(), StartLoc: Loc,
1240 IdLoc: Loc, Id: &Idents.get(Name));
1241 else
1242 NewDecl = RecordDecl::Create(C: *this, TK, DC: getTranslationUnitDecl(), StartLoc: Loc, IdLoc: Loc,
1243 Id: &Idents.get(Name));
1244 NewDecl->setImplicit();
1245 NewDecl->addAttr(A: TypeVisibilityAttr::CreateImplicit(
1246 Ctx&: const_cast<ASTContext &>(*this), Visibility: TypeVisibilityAttr::Default));
1247 return NewDecl;
1248}
1249
1250TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1251 StringRef Name) const {
1252 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1253 TypedefDecl *NewDecl = TypedefDecl::Create(
1254 C&: const_cast<ASTContext &>(*this), DC: getTranslationUnitDecl(),
1255 StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: &Idents.get(Name), TInfo);
1256 NewDecl->setImplicit();
1257 return NewDecl;
1258}
1259
1260TypedefDecl *ASTContext::getInt128Decl() const {
1261 if (!Int128Decl)
1262 Int128Decl = buildImplicitTypedef(T: Int128Ty, Name: "__int128_t");
1263 return Int128Decl;
1264}
1265
1266TypedefDecl *ASTContext::getUInt128Decl() const {
1267 if (!UInt128Decl)
1268 UInt128Decl = buildImplicitTypedef(T: UnsignedInt128Ty, Name: "__uint128_t");
1269 return UInt128Decl;
1270}
1271
1272void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1273 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1274 R = CanQualType::CreateUnsafe(Other: QualType(Ty, 0));
1275 Types.push_back(Elt: Ty);
1276}
1277
1278void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1279 const TargetInfo *AuxTarget) {
1280 assert((!this->Target || this->Target == &Target) &&
1281 "Incorrect target reinitialization");
1282 assert(VoidTy.isNull() && "Context reinitialized?");
1283
1284 this->Target = &Target;
1285 this->AuxTarget = AuxTarget;
1286
1287 ABI.reset(p: createCXXABI(T: Target));
1288 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(TI: Target, LangOpts);
1289
1290 // C99 6.2.5p19.
1291 InitBuiltinType(R&: VoidTy, K: BuiltinType::Void);
1292
1293 // C99 6.2.5p2.
1294 InitBuiltinType(R&: BoolTy, K: BuiltinType::Bool);
1295 // C99 6.2.5p3.
1296 if (LangOpts.CharIsSigned)
1297 InitBuiltinType(R&: CharTy, K: BuiltinType::Char_S);
1298 else
1299 InitBuiltinType(R&: CharTy, K: BuiltinType::Char_U);
1300 // C99 6.2.5p4.
1301 InitBuiltinType(R&: SignedCharTy, K: BuiltinType::SChar);
1302 InitBuiltinType(R&: ShortTy, K: BuiltinType::Short);
1303 InitBuiltinType(R&: IntTy, K: BuiltinType::Int);
1304 InitBuiltinType(R&: LongTy, K: BuiltinType::Long);
1305 InitBuiltinType(R&: LongLongTy, K: BuiltinType::LongLong);
1306
1307 // C99 6.2.5p6.
1308 InitBuiltinType(R&: UnsignedCharTy, K: BuiltinType::UChar);
1309 InitBuiltinType(R&: UnsignedShortTy, K: BuiltinType::UShort);
1310 InitBuiltinType(R&: UnsignedIntTy, K: BuiltinType::UInt);
1311 InitBuiltinType(R&: UnsignedLongTy, K: BuiltinType::ULong);
1312 InitBuiltinType(R&: UnsignedLongLongTy, K: BuiltinType::ULongLong);
1313
1314 // C99 6.2.5p10.
1315 InitBuiltinType(R&: FloatTy, K: BuiltinType::Float);
1316 InitBuiltinType(R&: DoubleTy, K: BuiltinType::Double);
1317 InitBuiltinType(R&: LongDoubleTy, K: BuiltinType::LongDouble);
1318
1319 // GNU extension, __float128 for IEEE quadruple precision
1320 InitBuiltinType(R&: Float128Ty, K: BuiltinType::Float128);
1321
1322 // __ibm128 for IBM extended precision
1323 InitBuiltinType(R&: Ibm128Ty, K: BuiltinType::Ibm128);
1324
1325 // C11 extension ISO/IEC TS 18661-3
1326 InitBuiltinType(R&: Float16Ty, K: BuiltinType::Float16);
1327
1328 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1329 InitBuiltinType(R&: ShortAccumTy, K: BuiltinType::ShortAccum);
1330 InitBuiltinType(R&: AccumTy, K: BuiltinType::Accum);
1331 InitBuiltinType(R&: LongAccumTy, K: BuiltinType::LongAccum);
1332 InitBuiltinType(R&: UnsignedShortAccumTy, K: BuiltinType::UShortAccum);
1333 InitBuiltinType(R&: UnsignedAccumTy, K: BuiltinType::UAccum);
1334 InitBuiltinType(R&: UnsignedLongAccumTy, K: BuiltinType::ULongAccum);
1335 InitBuiltinType(R&: ShortFractTy, K: BuiltinType::ShortFract);
1336 InitBuiltinType(R&: FractTy, K: BuiltinType::Fract);
1337 InitBuiltinType(R&: LongFractTy, K: BuiltinType::LongFract);
1338 InitBuiltinType(R&: UnsignedShortFractTy, K: BuiltinType::UShortFract);
1339 InitBuiltinType(R&: UnsignedFractTy, K: BuiltinType::UFract);
1340 InitBuiltinType(R&: UnsignedLongFractTy, K: BuiltinType::ULongFract);
1341 InitBuiltinType(R&: SatShortAccumTy, K: BuiltinType::SatShortAccum);
1342 InitBuiltinType(R&: SatAccumTy, K: BuiltinType::SatAccum);
1343 InitBuiltinType(R&: SatLongAccumTy, K: BuiltinType::SatLongAccum);
1344 InitBuiltinType(R&: SatUnsignedShortAccumTy, K: BuiltinType::SatUShortAccum);
1345 InitBuiltinType(R&: SatUnsignedAccumTy, K: BuiltinType::SatUAccum);
1346 InitBuiltinType(R&: SatUnsignedLongAccumTy, K: BuiltinType::SatULongAccum);
1347 InitBuiltinType(R&: SatShortFractTy, K: BuiltinType::SatShortFract);
1348 InitBuiltinType(R&: SatFractTy, K: BuiltinType::SatFract);
1349 InitBuiltinType(R&: SatLongFractTy, K: BuiltinType::SatLongFract);
1350 InitBuiltinType(R&: SatUnsignedShortFractTy, K: BuiltinType::SatUShortFract);
1351 InitBuiltinType(R&: SatUnsignedFractTy, K: BuiltinType::SatUFract);
1352 InitBuiltinType(R&: SatUnsignedLongFractTy, K: BuiltinType::SatULongFract);
1353
1354 // GNU extension, 128-bit integers.
1355 InitBuiltinType(R&: Int128Ty, K: BuiltinType::Int128);
1356 InitBuiltinType(R&: UnsignedInt128Ty, K: BuiltinType::UInt128);
1357
1358 // C++ 3.9.1p5
1359 if (TargetInfo::isTypeSigned(T: Target.getWCharType()))
1360 InitBuiltinType(R&: WCharTy, K: BuiltinType::WChar_S);
1361 else // -fshort-wchar makes wchar_t be unsigned.
1362 InitBuiltinType(R&: WCharTy, K: BuiltinType::WChar_U);
1363 if (LangOpts.CPlusPlus && LangOpts.WChar)
1364 WideCharTy = WCharTy;
1365 else {
1366 // C99 (or C++ using -fno-wchar).
1367 WideCharTy = getFromTargetType(Type: Target.getWCharType());
1368 }
1369
1370 WIntTy = getFromTargetType(Type: Target.getWIntType());
1371
1372 // C++20 (proposed)
1373 InitBuiltinType(R&: Char8Ty, K: BuiltinType::Char8);
1374
1375 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1376 InitBuiltinType(R&: Char16Ty, K: BuiltinType::Char16);
1377 else // C99
1378 Char16Ty = getFromTargetType(Type: Target.getChar16Type());
1379
1380 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1381 InitBuiltinType(R&: Char32Ty, K: BuiltinType::Char32);
1382 else // C99
1383 Char32Ty = getFromTargetType(Type: Target.getChar32Type());
1384
1385 // Placeholder type for type-dependent expressions whose type is
1386 // completely unknown. No code should ever check a type against
1387 // DependentTy and users should never see it; however, it is here to
1388 // help diagnose failures to properly check for type-dependent
1389 // expressions.
1390 InitBuiltinType(R&: DependentTy, K: BuiltinType::Dependent);
1391
1392 // Placeholder type for functions.
1393 InitBuiltinType(R&: OverloadTy, K: BuiltinType::Overload);
1394
1395 // Placeholder type for bound members.
1396 InitBuiltinType(R&: BoundMemberTy, K: BuiltinType::BoundMember);
1397
1398 // Placeholder type for unresolved templates.
1399 InitBuiltinType(R&: UnresolvedTemplateTy, K: BuiltinType::UnresolvedTemplate);
1400
1401 // Placeholder type for pseudo-objects.
1402 InitBuiltinType(R&: PseudoObjectTy, K: BuiltinType::PseudoObject);
1403
1404 // "any" type; useful for debugger-like clients.
1405 InitBuiltinType(R&: UnknownAnyTy, K: BuiltinType::UnknownAny);
1406
1407 // Placeholder type for unbridged ARC casts.
1408 InitBuiltinType(R&: ARCUnbridgedCastTy, K: BuiltinType::ARCUnbridgedCast);
1409
1410 // Placeholder type for builtin functions.
1411 InitBuiltinType(R&: BuiltinFnTy, K: BuiltinType::BuiltinFn);
1412
1413 // Placeholder type for OMP array sections.
1414 if (LangOpts.OpenMP) {
1415 InitBuiltinType(R&: ArraySectionTy, K: BuiltinType::ArraySection);
1416 InitBuiltinType(R&: OMPArrayShapingTy, K: BuiltinType::OMPArrayShaping);
1417 InitBuiltinType(R&: OMPIteratorTy, K: BuiltinType::OMPIterator);
1418 }
1419 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1420 // don't bother, as we're just using the same type as OMP.
1421 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1422 InitBuiltinType(R&: ArraySectionTy, K: BuiltinType::ArraySection);
1423 }
1424 if (LangOpts.MatrixTypes)
1425 InitBuiltinType(R&: IncompleteMatrixIdxTy, K: BuiltinType::IncompleteMatrixIdx);
1426
1427 // Builtin types for 'id', 'Class', and 'SEL'.
1428 InitBuiltinType(R&: ObjCBuiltinIdTy, K: BuiltinType::ObjCId);
1429 InitBuiltinType(R&: ObjCBuiltinClassTy, K: BuiltinType::ObjCClass);
1430 InitBuiltinType(R&: ObjCBuiltinSelTy, K: BuiltinType::ObjCSel);
1431
1432 if (LangOpts.OpenCL) {
1433#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1434 InitBuiltinType(SingletonId, BuiltinType::Id);
1435#include "clang/Basic/OpenCLImageTypes.def"
1436
1437 InitBuiltinType(R&: OCLSamplerTy, K: BuiltinType::OCLSampler);
1438 InitBuiltinType(R&: OCLEventTy, K: BuiltinType::OCLEvent);
1439 InitBuiltinType(R&: OCLClkEventTy, K: BuiltinType::OCLClkEvent);
1440 InitBuiltinType(R&: OCLQueueTy, K: BuiltinType::OCLQueue);
1441 InitBuiltinType(R&: OCLReserveIDTy, K: BuiltinType::OCLReserveID);
1442
1443#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1444 InitBuiltinType(Id##Ty, BuiltinType::Id);
1445#include "clang/Basic/OpenCLExtensionTypes.def"
1446 }
1447
1448 if (LangOpts.HLSL) {
1449#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1450 InitBuiltinType(SingletonId, BuiltinType::Id);
1451#include "clang/Basic/HLSLIntangibleTypes.def"
1452 }
1453
1454 if (Target.hasAArch64ACLETypes() ||
1455 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1456#define SVE_TYPE(Name, Id, SingletonId) \
1457 InitBuiltinType(SingletonId, BuiltinType::Id);
1458#include "clang/Basic/AArch64ACLETypes.def"
1459 }
1460
1461 if (Target.getTriple().isPPC64()) {
1462#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1463 InitBuiltinType(Id##Ty, BuiltinType::Id);
1464#include "clang/Basic/PPCTypes.def"
1465#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1466 InitBuiltinType(Id##Ty, BuiltinType::Id);
1467#include "clang/Basic/PPCTypes.def"
1468 }
1469
1470 if (Target.hasRISCVVTypes()) {
1471#define RVV_TYPE(Name, Id, SingletonId) \
1472 InitBuiltinType(SingletonId, BuiltinType::Id);
1473#include "clang/Basic/RISCVVTypes.def"
1474 }
1475
1476 if (Target.getTriple().isWasm() && Target.hasFeature(Feature: "reference-types")) {
1477#define WASM_TYPE(Name, Id, SingletonId) \
1478 InitBuiltinType(SingletonId, BuiltinType::Id);
1479#include "clang/Basic/WebAssemblyReferenceTypes.def"
1480 }
1481
1482 if (Target.hasAMDGPUTypes() || (AuxTarget && (AuxTarget->hasAMDGPUTypes()))) {
1483#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1484 InitBuiltinType(SingletonId, BuiltinType::Id);
1485#include "clang/Basic/AMDGPUTypes.def"
1486 }
1487
1488 if (Target.getTriple().isSPIRV() ||
1489 (AuxTarget && AuxTarget->getTriple().isSPIRV())) {
1490#define SPIRV_TYPE(Name, Id, SingletonId) \
1491 InitBuiltinType(SingletonId, BuiltinType::Id);
1492#include "clang/Basic/SPIRVTypes.def"
1493 }
1494
1495 // Builtin type for __objc_yes and __objc_no
1496 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1497 SignedCharTy : BoolTy);
1498
1499 ObjCConstantStringType = QualType();
1500
1501 ObjCSuperType = QualType();
1502
1503 // void * type
1504 if (LangOpts.OpenCLGenericAddressSpace) {
1505 auto Q = VoidTy.getQualifiers();
1506 Q.setAddressSpace(LangAS::opencl_generic);
1507 VoidPtrTy = getPointerType(T: getCanonicalType(
1508 T: getQualifiedType(T: VoidTy.getUnqualifiedType(), Qs: Q)));
1509 } else {
1510 VoidPtrTy = getPointerType(T: VoidTy);
1511 }
1512
1513 // nullptr type (C++0x 2.14.7)
1514 InitBuiltinType(R&: NullPtrTy, K: BuiltinType::NullPtr);
1515
1516 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1517 InitBuiltinType(R&: HalfTy, K: BuiltinType::Half);
1518
1519 InitBuiltinType(R&: BFloat16Ty, K: BuiltinType::BFloat16);
1520
1521 // Builtin type used to help define __builtin_va_list.
1522 VaListTagDecl = nullptr;
1523
1524 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1525 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1526 MSGuidTagDecl = buildImplicitRecord(Name: "_GUID");
1527 getTranslationUnitDecl()->addDecl(D: MSGuidTagDecl);
1528 }
1529}
1530
1531DiagnosticsEngine &ASTContext::getDiagnostics() const {
1532 return SourceMgr.getDiagnostics();
1533}
1534
1535AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1536 AttrVec *&Result = DeclAttrs[D];
1537 if (!Result) {
1538 void *Mem = Allocate(Size: sizeof(AttrVec));
1539 Result = new (Mem) AttrVec;
1540 }
1541
1542 return *Result;
1543}
1544
1545/// Erase the attributes corresponding to the given declaration.
1546void ASTContext::eraseDeclAttrs(const Decl *D) {
1547 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(Val: D);
1548 if (Pos != DeclAttrs.end()) {
1549 Pos->second->~AttrVec();
1550 DeclAttrs.erase(I: Pos);
1551 }
1552}
1553
1554ArrayRef<CXXDefaultArgExpr *>
1555ASTContext::getCtorClosureDefaultArgs(const CXXConstructorDecl *CD) {
1556 return CtorClosureDefaultArgs.lookup(Val: CD);
1557}
1558
1559void ASTContext::setCtorClosureDefaultArgs(const CXXConstructorDecl *CD,
1560 ArrayRef<CXXDefaultArgExpr *> Args) {
1561 assert(!CtorClosureDefaultArgs.contains(CD));
1562 CtorClosureDefaultArgs[CD] = Args;
1563}
1564
1565ArrayRef<ExplicitInstantiationDecl *>
1566ASTContext::getExplicitInstantiationDecls(const NamedDecl *Spec) const {
1567 auto It =
1568 ExplicitInstantiations.find(Val: cast<NamedDecl>(Val: Spec->getCanonicalDecl()));
1569 if (It != ExplicitInstantiations.end())
1570 return It->second;
1571 return {};
1572}
1573
1574void ASTContext::addExplicitInstantiationDecl(const NamedDecl *Spec,
1575 ExplicitInstantiationDecl *EID) {
1576 ExplicitInstantiations[cast<NamedDecl>(Val: Spec->getCanonicalDecl())].push_back(
1577 NewVal: EID);
1578}
1579
1580// FIXME: Remove ?
1581MemberSpecializationInfo *
1582ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1583 assert(Var->isStaticDataMember() && "Not a static data member");
1584 return getTemplateOrSpecializationInfo(Var)
1585 .dyn_cast<MemberSpecializationInfo *>();
1586}
1587
1588ASTContext::TemplateOrSpecializationInfo
1589ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1590 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1591 TemplateOrInstantiation.find(Val: Var);
1592 if (Pos == TemplateOrInstantiation.end())
1593 return {};
1594
1595 return Pos->second;
1596}
1597
1598void
1599ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1600 TemplateSpecializationKind TSK,
1601 SourceLocation PointOfInstantiation) {
1602 assert(Inst->isStaticDataMember() && "Not a static data member");
1603 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1604 setTemplateOrSpecializationInfo(Inst, TSI: new (*this) MemberSpecializationInfo(
1605 Tmpl, TSK, PointOfInstantiation));
1606}
1607
1608void
1609ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1610 TemplateOrSpecializationInfo TSI) {
1611 assert(!TemplateOrInstantiation[Inst] &&
1612 "Already noted what the variable was instantiated from");
1613 TemplateOrInstantiation[Inst] = TSI;
1614}
1615
1616NamedDecl *
1617ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1618 return InstantiatedFromUsingDecl.lookup(Val: UUD);
1619}
1620
1621void
1622ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1623 assert((isa<UsingDecl>(Pattern) ||
1624 isa<UnresolvedUsingValueDecl>(Pattern) ||
1625 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1626 "pattern decl is not a using decl");
1627 assert((isa<UsingDecl>(Inst) ||
1628 isa<UnresolvedUsingValueDecl>(Inst) ||
1629 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1630 "instantiation did not produce a using decl");
1631 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1632 InstantiatedFromUsingDecl[Inst] = Pattern;
1633}
1634
1635UsingEnumDecl *
1636ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) {
1637 return InstantiatedFromUsingEnumDecl.lookup(Val: UUD);
1638}
1639
1640void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
1641 UsingEnumDecl *Pattern) {
1642 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1643 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1644}
1645
1646UsingShadowDecl *
1647ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1648 return InstantiatedFromUsingShadowDecl.lookup(Val: Inst);
1649}
1650
1651void
1652ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1653 UsingShadowDecl *Pattern) {
1654 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1655 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1656}
1657
1658FieldDecl *
1659ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const {
1660 return InstantiatedFromUnnamedFieldDecl.lookup(Val: Field);
1661}
1662
1663void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1664 FieldDecl *Tmpl) {
1665 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1666 "Instantiated field decl is not unnamed");
1667 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1668 "Template field decl is not unnamed");
1669 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1670 "Already noted what unnamed field was instantiated from");
1671
1672 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1673}
1674
1675ASTContext::overridden_cxx_method_iterator
1676ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1677 return overridden_methods(Method).begin();
1678}
1679
1680ASTContext::overridden_cxx_method_iterator
1681ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1682 return overridden_methods(Method).end();
1683}
1684
1685unsigned
1686ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1687 auto Range = overridden_methods(Method);
1688 return Range.end() - Range.begin();
1689}
1690
1691ASTContext::overridden_method_range
1692ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1693 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1694 OverriddenMethods.find(Val: Method->getCanonicalDecl());
1695 if (Pos == OverriddenMethods.end())
1696 return overridden_method_range(nullptr, nullptr);
1697 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1698}
1699
1700void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1701 const CXXMethodDecl *Overridden) {
1702 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1703 OverriddenMethods[Method].push_back(NewVal: Overridden);
1704}
1705
1706void ASTContext::getOverriddenMethods(
1707 const NamedDecl *D,
1708 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1709 assert(D);
1710
1711 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(Val: D)) {
1712 Overridden.append(in_start: overridden_methods_begin(Method: CXXMethod),
1713 in_end: overridden_methods_end(Method: CXXMethod));
1714 return;
1715 }
1716
1717 const auto *Method = dyn_cast<ObjCMethodDecl>(Val: D);
1718 if (!Method)
1719 return;
1720
1721 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1722 Method->getOverriddenMethods(Overridden&: OverDecls);
1723 Overridden.append(in_start: OverDecls.begin(), in_end: OverDecls.end());
1724}
1725
1726std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1727ASTContext::getRelocationInfoForCXXRecord(const CXXRecordDecl *RD) const {
1728 assert(RD);
1729 CXXRecordDecl *D = RD->getDefinition();
1730 auto it = RelocatableClasses.find(Val: D);
1731 if (it != RelocatableClasses.end())
1732 return it->getSecond();
1733 return std::nullopt;
1734}
1735
1736void ASTContext::setRelocationInfoForCXXRecord(
1737 const CXXRecordDecl *RD, CXXRecordDeclRelocationInfo Info) {
1738 assert(RD);
1739 CXXRecordDecl *D = RD->getDefinition();
1740 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1741 RelocatableClasses.insert(KV: {D, Info});
1742}
1743
1744static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(
1745 const ASTContext &Context, const CXXRecordDecl *Class) {
1746 if (!Class->isPolymorphic())
1747 return false;
1748 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(ThisClass: Class);
1749 using AuthAttr = VTablePointerAuthenticationAttr;
1750 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1751 if (!ExplicitAuth)
1752 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1753 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1754 ExplicitAuth->getAddressDiscrimination();
1755 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1756 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1757 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1758}
1759
1760ASTContext::PointerAuthContent
1761ASTContext::findPointerAuthContent(QualType T) const {
1762 assert(isPointerAuthenticationAvailable());
1763
1764 T = T.getCanonicalType();
1765 if (T->isDependentType())
1766 return PointerAuthContent::None;
1767
1768 if (T.hasAddressDiscriminatedPointerAuth())
1769 return PointerAuthContent::AddressDiscriminatedData;
1770 const RecordDecl *RD = T->getAsRecordDecl();
1771 if (!RD)
1772 return PointerAuthContent::None;
1773
1774 if (RD->isInvalidDecl())
1775 return PointerAuthContent::None;
1776
1777 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(Val: RD);
1778 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1779 return Existing->second;
1780
1781 PointerAuthContent Result = PointerAuthContent::None;
1782
1783 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1784 auto [ResultIter, DidAdd] =
1785 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(Key: RD, Args&: Result);
1786 (void)ResultIter;
1787 (void)DidAdd;
1788 assert(DidAdd);
1789 return Result;
1790 };
1791 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1792 static_assert(PointerAuthContent::None <
1793 PointerAuthContent::AddressDiscriminatedVTable);
1794 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1795 PointerAuthContent::AddressDiscriminatedData);
1796 if (NewResult > Result)
1797 Result = NewResult;
1798 return Result != PointerAuthContent::AddressDiscriminatedData;
1799 };
1800 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
1801 if (primaryBaseHaseAddressDiscriminatedVTableAuthentication(Context: *this, Class: CXXRD) &&
1802 !ShouldContinueAfterUpdate(
1803 PointerAuthContent::AddressDiscriminatedVTable))
1804 return SaveResultAndReturn();
1805 for (auto Base : CXXRD->bases()) {
1806 if (!ShouldContinueAfterUpdate(findPointerAuthContent(T: Base.getType())))
1807 return SaveResultAndReturn();
1808 }
1809 }
1810 for (auto *FieldDecl : RD->fields()) {
1811 if (!ShouldContinueAfterUpdate(
1812 findPointerAuthContent(T: FieldDecl->getType())))
1813 return SaveResultAndReturn();
1814 }
1815 return SaveResultAndReturn();
1816}
1817
1818void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1819 assert(!Import->getNextLocalImport() &&
1820 "Import declaration already in the chain");
1821 assert(!Import->isFromASTFile() && "Non-local import declaration");
1822 if (!FirstLocalImport) {
1823 FirstLocalImport = Import;
1824 LastLocalImport = Import;
1825 return;
1826 }
1827
1828 LastLocalImport->setNextLocalImport(Import);
1829 LastLocalImport = Import;
1830}
1831
1832//===----------------------------------------------------------------------===//
1833// Type Sizing and Analysis
1834//===----------------------------------------------------------------------===//
1835
1836/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1837/// scalar floating point type.
1838const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1839 switch (T->castAs<BuiltinType>()->getKind()) {
1840 default:
1841 llvm_unreachable("Not a floating point type!");
1842 case BuiltinType::BFloat16:
1843 return Target->getBFloat16Format();
1844 case BuiltinType::Float16:
1845 return Target->getHalfFormat();
1846 case BuiltinType::Half:
1847 return Target->getHalfFormat();
1848 case BuiltinType::Float: return Target->getFloatFormat();
1849 case BuiltinType::Double: return Target->getDoubleFormat();
1850 case BuiltinType::Ibm128:
1851 return Target->getIbm128Format();
1852 case BuiltinType::LongDouble:
1853 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1854 return AuxTarget->getLongDoubleFormat();
1855 return Target->getLongDoubleFormat();
1856 case BuiltinType::Float128:
1857 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1858 return AuxTarget->getFloat128Format();
1859 return Target->getFloat128Format();
1860 }
1861}
1862
1863CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1864 unsigned Align = Target->getCharWidth();
1865
1866 const unsigned AlignFromAttr = D->getMaxAlignment();
1867 if (AlignFromAttr)
1868 Align = AlignFromAttr;
1869
1870 // __attribute__((aligned)) can increase or decrease alignment
1871 // *except* on a struct or struct member, where it only increases
1872 // alignment unless 'packed' is also specified.
1873 //
1874 // It is an error for alignas to decrease alignment, so we can
1875 // ignore that possibility; Sema should diagnose it.
1876 bool UseAlignAttrOnly;
1877 if (const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D))
1878 UseAlignAttrOnly =
1879 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1880 else
1881 UseAlignAttrOnly = AlignFromAttr != 0;
1882 // If we're using the align attribute only, just ignore everything
1883 // else about the declaration and its type.
1884 if (UseAlignAttrOnly) {
1885 // do nothing
1886 } else if (const auto *VD = dyn_cast<ValueDecl>(Val: D)) {
1887 QualType T = VD->getType();
1888 if (const auto *RT = T->getAs<ReferenceType>()) {
1889 if (ForAlignof)
1890 T = RT->getPointeeType();
1891 else
1892 T = getPointerType(T: RT->getPointeeType());
1893 }
1894 QualType BaseT = getBaseElementType(QT: T);
1895 if (T->isFunctionType())
1896 Align = getTypeInfoImpl(T: T.getTypePtr()).Align;
1897 else if (!BaseT->isIncompleteType()) {
1898 // Adjust alignments of declarations with array type by the
1899 // large-array alignment on the target.
1900 if (const ArrayType *arrayType = getAsArrayType(T)) {
1901 unsigned MinWidth = Target->getLargeArrayMinWidth();
1902 if (!ForAlignof && MinWidth) {
1903 if (isa<VariableArrayType>(Val: arrayType))
1904 Align = std::max(a: Align, b: Target->getLargeArrayAlign());
1905 else if (isa<ConstantArrayType>(Val: arrayType) &&
1906 MinWidth <= getTypeSize(T: cast<ConstantArrayType>(Val: arrayType)))
1907 Align = std::max(a: Align, b: Target->getLargeArrayAlign());
1908 }
1909 }
1910 Align = std::max(a: Align, b: getPreferredTypeAlign(T: T.getTypePtr()));
1911 if (BaseT.getQualifiers().hasUnaligned())
1912 Align = Target->getCharWidth();
1913 }
1914
1915 // Ensure minimum alignment for global variables.
1916 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
1917 if (VD->hasGlobalStorage() && !ForAlignof) {
1918 uint64_t TypeSize =
1919 !BaseT->isIncompleteType() ? getTypeSize(T: T.getTypePtr()) : 0;
1920 Align = std::max(a: Align, b: getMinGlobalAlignOfVar(Size: TypeSize, VD));
1921 }
1922
1923 // Fields can be subject to extra alignment constraints, like if
1924 // the field is packed, the struct is packed, or the struct has a
1925 // a max-field-alignment constraint (#pragma pack). So calculate
1926 // the actual alignment of the field within the struct, and then
1927 // (as we're expected to) constrain that by the alignment of the type.
1928 if (const auto *Field = dyn_cast<FieldDecl>(Val: VD)) {
1929 const RecordDecl *Parent = Field->getParent();
1930 // We can only produce a sensible answer if the record is valid.
1931 if (!Parent->isInvalidDecl()) {
1932 const ASTRecordLayout &Layout = getASTRecordLayout(D: Parent);
1933
1934 // Start with the record's overall alignment.
1935 unsigned FieldAlign = toBits(CharSize: Layout.getAlignment());
1936
1937 // Use the GCD of that and the offset within the record.
1938 uint64_t Offset = Layout.getFieldOffset(FieldNo: Field->getFieldIndex());
1939 if (Offset > 0) {
1940 // Alignment is always a power of 2, so the GCD will be a power of 2,
1941 // which means we get to do this crazy thing instead of Euclid's.
1942 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1943 if (LowBitOfOffset < FieldAlign)
1944 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1945 }
1946
1947 Align = std::min(a: Align, b: FieldAlign);
1948 }
1949 }
1950 }
1951
1952 // Some targets have hard limitation on the maximum requestable alignment in
1953 // aligned attribute for static variables.
1954 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1955 const auto *VD = dyn_cast<VarDecl>(Val: D);
1956 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1957 Align = std::min(a: Align, b: MaxAlignedAttr);
1958
1959 return toCharUnitsFromBits(BitSize: Align);
1960}
1961
1962CharUnits ASTContext::getExnObjectAlignment() const {
1963 return toCharUnitsFromBits(BitSize: Target->getExnObjectAlignment());
1964}
1965
1966// getTypeInfoDataSizeInChars - Return the size of a type, in
1967// chars. If the type is a record, its data size is returned. This is
1968// the size of the memcpy that's performed when assigning this type
1969// using a trivial copy/move assignment operator.
1970TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1971 TypeInfoChars Info = getTypeInfoInChars(T);
1972
1973 // In C++, objects can sometimes be allocated into the tail padding
1974 // of a base-class subobject. We decide whether that's possible
1975 // during class layout, so here we can just trust the layout results.
1976 if (getLangOpts().CPlusPlus) {
1977 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1978 const ASTRecordLayout &layout = getASTRecordLayout(D: RD);
1979 Info.Width = layout.getDataSize();
1980 }
1981 }
1982
1983 return Info;
1984}
1985
1986/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1987/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1988TypeInfoChars
1989static getConstantArrayInfoInChars(const ASTContext &Context,
1990 const ConstantArrayType *CAT) {
1991 TypeInfoChars EltInfo = Context.getTypeInfoInChars(T: CAT->getElementType());
1992 uint64_t Size = CAT->getZExtSize();
1993 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1994 (uint64_t)(-1)/Size) &&
1995 "Overflow in array type char size evaluation");
1996 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1997 unsigned Align = EltInfo.Align.getQuantity();
1998 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1999 Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default) == 64)
2000 Width = llvm::alignTo(Value: Width, Align);
2001 return TypeInfoChars(CharUnits::fromQuantity(Quantity: Width),
2002 CharUnits::fromQuantity(Quantity: Align),
2003 EltInfo.AlignRequirement);
2004}
2005
2006TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
2007 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: T))
2008 return getConstantArrayInfoInChars(Context: *this, CAT);
2009 TypeInfo Info = getTypeInfo(T);
2010 return TypeInfoChars(toCharUnitsFromBits(BitSize: Info.Width),
2011 toCharUnitsFromBits(BitSize: Info.Align), Info.AlignRequirement);
2012}
2013
2014TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
2015 return getTypeInfoInChars(T: T.getTypePtr());
2016}
2017
2018bool ASTContext::isPromotableIntegerType(QualType T) const {
2019 // HLSL doesn't promote all small integer types to int, it
2020 // just uses the rank-based promotion rules for all types.
2021 if (getLangOpts().HLSL)
2022 return false;
2023
2024 if (const auto *BT = T->getAs<BuiltinType>())
2025 switch (BT->getKind()) {
2026 case BuiltinType::Bool:
2027 case BuiltinType::Char_S:
2028 case BuiltinType::Char_U:
2029 case BuiltinType::SChar:
2030 case BuiltinType::UChar:
2031 case BuiltinType::Short:
2032 case BuiltinType::UShort:
2033 case BuiltinType::WChar_S:
2034 case BuiltinType::WChar_U:
2035 case BuiltinType::Char8:
2036 case BuiltinType::Char16:
2037 case BuiltinType::Char32:
2038 return true;
2039 default:
2040 return false;
2041 }
2042
2043 // Enumerated types are promotable to their compatible integer types
2044 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2045 if (const auto *ED = T->getAsEnumDecl()) {
2046 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2047 ED->isScoped())
2048 return false;
2049
2050 return true;
2051 }
2052
2053 // OverflowBehaviorTypes are promotable if their underlying type is promotable
2054 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
2055 return isPromotableIntegerType(T: OBT->getUnderlyingType());
2056 }
2057
2058 return false;
2059}
2060
2061bool ASTContext::isAlignmentRequired(const Type *T) const {
2062 return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None;
2063}
2064
2065bool ASTContext::isAlignmentRequired(QualType T) const {
2066 return isAlignmentRequired(T: T.getTypePtr());
2067}
2068
2069unsigned ASTContext::getTypeAlignIfKnown(QualType T,
2070 bool NeedsPreferredAlignment) const {
2071 // An alignment on a typedef overrides anything else.
2072 if (const auto *TT = T->getAs<TypedefType>())
2073 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2074 return Align;
2075
2076 // If we have an (array of) complete type, we're done.
2077 T = getBaseElementType(QT: T);
2078 if (!T->isIncompleteType())
2079 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2080
2081 // If we had an array type, its element type might be a typedef
2082 // type with an alignment attribute.
2083 if (const auto *TT = T->getAs<TypedefType>())
2084 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2085 return Align;
2086
2087 // Otherwise, see if the declaration of the type had an attribute.
2088 if (const auto *TD = T->getAsTagDecl())
2089 return TD->getMaxAlignment();
2090
2091 return 0;
2092}
2093
2094TypeInfo ASTContext::getTypeInfo(const Type *T) const {
2095 TypeInfoMap::iterator I = MemoizedTypeInfo.find(Val: T);
2096 if (I != MemoizedTypeInfo.end())
2097 return I->second;
2098
2099 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2100 TypeInfo TI = getTypeInfoImpl(T);
2101 MemoizedTypeInfo[T] = TI;
2102 return TI;
2103}
2104
2105/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2106/// method does not work on incomplete types.
2107///
2108/// FIXME: Pointers into different addr spaces could have different sizes and
2109/// alignment requirements: getPointerInfo should take an AddrSpace, this
2110/// should take a QualType, &c.
2111TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2112 uint64_t Width = 0;
2113 unsigned Align = 8;
2114 AlignRequirementKind AlignRequirement = AlignRequirementKind::None;
2115 LangAS AS = LangAS::Default;
2116 switch (T->getTypeClass()) {
2117#define TYPE(Class, Base)
2118#define ABSTRACT_TYPE(Class, Base)
2119#define NON_CANONICAL_TYPE(Class, Base)
2120#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2121#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2122 case Type::Class: \
2123 assert(!T->isDependentType() && "should not see dependent types here"); \
2124 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2125#include "clang/AST/TypeNodes.inc"
2126 llvm_unreachable("Should not see dependent types");
2127
2128 case Type::FunctionNoProto:
2129 case Type::FunctionProto:
2130 // GCC extension: alignof(function) = 32 bits
2131 Width = 0;
2132 Align = 32;
2133 break;
2134
2135 case Type::IncompleteArray:
2136 case Type::VariableArray:
2137 case Type::ConstantArray:
2138 case Type::ArrayParameter: {
2139 // Model non-constant sized arrays as size zero, but track the alignment.
2140 uint64_t Size = 0;
2141 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: T))
2142 Size = CAT->getZExtSize();
2143
2144 TypeInfo EltInfo = getTypeInfo(T: cast<ArrayType>(Val: T)->getElementType());
2145 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2146 "Overflow in array type bit size evaluation");
2147 Width = EltInfo.Width * Size;
2148 Align = EltInfo.Align;
2149 AlignRequirement = EltInfo.AlignRequirement;
2150 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2151 getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default) == 64)
2152 Width = llvm::alignTo(Value: Width, Align);
2153 break;
2154 }
2155
2156 case Type::ExtVector:
2157 case Type::Vector: {
2158 const auto *VT = cast<VectorType>(Val: T);
2159 TypeInfo EltInfo = getTypeInfo(T: VT->getElementType());
2160 Width = VT->isPackedVectorBoolType(ctx: *this)
2161 ? VT->getNumElements()
2162 : EltInfo.Width * VT->getNumElements();
2163 // Enforce at least byte size and alignment.
2164 Width = std::max<unsigned>(a: 8, b: Width);
2165 Align = std::max<unsigned>(
2166 a: 8, b: Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2167
2168 // If the alignment is not a power of 2, round up to the next power of 2.
2169 // This happens for non-power-of-2 length vectors.
2170 if (Align & (Align-1)) {
2171 Align = llvm::bit_ceil(Value: Align);
2172 Width = llvm::alignTo(Value: Width, Align);
2173 }
2174 // Adjust the alignment based on the target max.
2175 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2176 if (TargetVectorAlign && TargetVectorAlign < Align)
2177 Align = TargetVectorAlign;
2178 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2179 // Adjust the alignment for fixed-length SVE vectors. This is important
2180 // for non-power-of-2 vector lengths.
2181 Align = 128;
2182 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2183 // Adjust the alignment for fixed-length SVE predicates.
2184 Align = 16;
2185 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2186 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2187 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2188 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2189 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2190 // Adjust the alignment for fixed-length RVV vectors.
2191 Align = std::min<unsigned>(a: 64, b: Width);
2192 break;
2193 }
2194
2195 case Type::ConstantMatrix: {
2196 const auto *MT = cast<ConstantMatrixType>(Val: T);
2197 TypeInfo ElementInfo = getTypeInfo(T: MT->getElementType());
2198 // The internal layout of a matrix value is implementation defined.
2199 // Initially be ABI compatible with arrays with respect to alignment and
2200 // size.
2201 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2202 Align = ElementInfo.Align;
2203 break;
2204 }
2205
2206 case Type::Builtin:
2207 switch (cast<BuiltinType>(Val: T)->getKind()) {
2208 default: llvm_unreachable("Unknown builtin type!");
2209 case BuiltinType::Void:
2210 // GCC extension: alignof(void) = 8 bits.
2211 Width = 0;
2212 Align = 8;
2213 break;
2214 case BuiltinType::Bool:
2215 Width = Target->getBoolWidth();
2216 Align = Target->getBoolAlign();
2217 break;
2218 case BuiltinType::Char_S:
2219 case BuiltinType::Char_U:
2220 case BuiltinType::UChar:
2221 case BuiltinType::SChar:
2222 case BuiltinType::Char8:
2223 Width = Target->getCharWidth();
2224 Align = Target->getCharAlign();
2225 break;
2226 case BuiltinType::WChar_S:
2227 case BuiltinType::WChar_U:
2228 Width = Target->getWCharWidth();
2229 Align = Target->getWCharAlign();
2230 break;
2231 case BuiltinType::Char16:
2232 Width = Target->getChar16Width();
2233 Align = Target->getChar16Align();
2234 break;
2235 case BuiltinType::Char32:
2236 Width = Target->getChar32Width();
2237 Align = Target->getChar32Align();
2238 break;
2239 case BuiltinType::UShort:
2240 case BuiltinType::Short:
2241 Width = Target->getShortWidth();
2242 Align = Target->getShortAlign();
2243 break;
2244 case BuiltinType::UInt:
2245 case BuiltinType::Int:
2246 Width = Target->getIntWidth();
2247 Align = Target->getIntAlign();
2248 break;
2249 case BuiltinType::ULong:
2250 case BuiltinType::Long:
2251 Width = Target->getLongWidth();
2252 Align = Target->getLongAlign();
2253 break;
2254 case BuiltinType::ULongLong:
2255 case BuiltinType::LongLong:
2256 Width = Target->getLongLongWidth();
2257 Align = Target->getLongLongAlign();
2258 break;
2259 case BuiltinType::Int128:
2260 case BuiltinType::UInt128:
2261 Width = 128;
2262 Align = Target->getInt128Align();
2263 break;
2264 case BuiltinType::ShortAccum:
2265 case BuiltinType::UShortAccum:
2266 case BuiltinType::SatShortAccum:
2267 case BuiltinType::SatUShortAccum:
2268 Width = Target->getShortAccumWidth();
2269 Align = Target->getShortAccumAlign();
2270 break;
2271 case BuiltinType::Accum:
2272 case BuiltinType::UAccum:
2273 case BuiltinType::SatAccum:
2274 case BuiltinType::SatUAccum:
2275 Width = Target->getAccumWidth();
2276 Align = Target->getAccumAlign();
2277 break;
2278 case BuiltinType::LongAccum:
2279 case BuiltinType::ULongAccum:
2280 case BuiltinType::SatLongAccum:
2281 case BuiltinType::SatULongAccum:
2282 Width = Target->getLongAccumWidth();
2283 Align = Target->getLongAccumAlign();
2284 break;
2285 case BuiltinType::ShortFract:
2286 case BuiltinType::UShortFract:
2287 case BuiltinType::SatShortFract:
2288 case BuiltinType::SatUShortFract:
2289 Width = Target->getShortFractWidth();
2290 Align = Target->getShortFractAlign();
2291 break;
2292 case BuiltinType::Fract:
2293 case BuiltinType::UFract:
2294 case BuiltinType::SatFract:
2295 case BuiltinType::SatUFract:
2296 Width = Target->getFractWidth();
2297 Align = Target->getFractAlign();
2298 break;
2299 case BuiltinType::LongFract:
2300 case BuiltinType::ULongFract:
2301 case BuiltinType::SatLongFract:
2302 case BuiltinType::SatULongFract:
2303 Width = Target->getLongFractWidth();
2304 Align = Target->getLongFractAlign();
2305 break;
2306 case BuiltinType::BFloat16:
2307 if (Target->hasBFloat16Type()) {
2308 Width = Target->getBFloat16Width();
2309 Align = Target->getBFloat16Align();
2310 } else if ((getLangOpts().SYCLIsDevice ||
2311 (getLangOpts().OpenMP &&
2312 getLangOpts().OpenMPIsTargetDevice)) &&
2313 AuxTarget->hasBFloat16Type()) {
2314 Width = AuxTarget->getBFloat16Width();
2315 Align = AuxTarget->getBFloat16Align();
2316 }
2317 break;
2318 case BuiltinType::Float16:
2319 case BuiltinType::Half:
2320 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2321 !getLangOpts().OpenMPIsTargetDevice) {
2322 Width = Target->getHalfWidth();
2323 Align = Target->getHalfAlign();
2324 } else {
2325 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2326 "Expected OpenMP device compilation.");
2327 Width = AuxTarget->getHalfWidth();
2328 Align = AuxTarget->getHalfAlign();
2329 }
2330 break;
2331 case BuiltinType::Float:
2332 Width = Target->getFloatWidth();
2333 Align = Target->getFloatAlign();
2334 break;
2335 case BuiltinType::Double:
2336 Width = Target->getDoubleWidth();
2337 Align = Target->getDoubleAlign();
2338 break;
2339 case BuiltinType::Ibm128:
2340 Width = Target->getIbm128Width();
2341 Align = Target->getIbm128Align();
2342 break;
2343 case BuiltinType::LongDouble:
2344 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2345 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2346 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2347 Width = AuxTarget->getLongDoubleWidth();
2348 Align = AuxTarget->getLongDoubleAlign();
2349 } else {
2350 Width = Target->getLongDoubleWidth();
2351 Align = Target->getLongDoubleAlign();
2352 }
2353 break;
2354 case BuiltinType::Float128:
2355 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2356 !getLangOpts().OpenMPIsTargetDevice) {
2357 Width = Target->getFloat128Width();
2358 Align = Target->getFloat128Align();
2359 } else {
2360 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2361 "Expected OpenMP device compilation.");
2362 Width = AuxTarget->getFloat128Width();
2363 Align = AuxTarget->getFloat128Align();
2364 }
2365 break;
2366 case BuiltinType::NullPtr:
2367 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2368 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2369 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2370 break;
2371 case BuiltinType::ObjCId:
2372 case BuiltinType::ObjCClass:
2373 case BuiltinType::ObjCSel:
2374 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2375 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2376 break;
2377 case BuiltinType::OCLSampler:
2378 case BuiltinType::OCLEvent:
2379 case BuiltinType::OCLClkEvent:
2380 case BuiltinType::OCLQueue:
2381 case BuiltinType::OCLReserveID:
2382#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2383 case BuiltinType::Id:
2384#include "clang/Basic/OpenCLImageTypes.def"
2385#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2386 case BuiltinType::Id:
2387#include "clang/Basic/OpenCLExtensionTypes.def"
2388 AS = Target->getOpenCLTypeAddrSpace(TK: getOpenCLTypeKind(T));
2389 Width = Target->getPointerWidth(AddrSpace: AS);
2390 Align = Target->getPointerAlign(AddrSpace: AS);
2391 break;
2392 // The SVE types are effectively target-specific. The length of an
2393 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2394 // of 128 bits. There is one predicate bit for each vector byte, so the
2395 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2396 //
2397 // Because the length is only known at runtime, we use a dummy value
2398 // of 0 for the static length. The alignment values are those defined
2399 // by the Procedure Call Standard for the Arm Architecture.
2400#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2401 case BuiltinType::Id: \
2402 Width = 0; \
2403 Align = 128; \
2404 break;
2405#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2406 case BuiltinType::Id: \
2407 Width = 0; \
2408 Align = 16; \
2409 break;
2410#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2411 case BuiltinType::Id: \
2412 Width = 0; \
2413 Align = 16; \
2414 break;
2415#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2416 case BuiltinType::Id: \
2417 Width = Bits; \
2418 Align = Bits; \
2419 break;
2420#include "clang/Basic/AArch64ACLETypes.def"
2421#define PPC_VECTOR_TYPE(Name, Id, Size) \
2422 case BuiltinType::Id: \
2423 Width = Size; \
2424 Align = Size; \
2425 break;
2426#include "clang/Basic/PPCTypes.def"
2427#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2428 IsFP, IsBF) \
2429 case BuiltinType::Id: \
2430 Width = 0; \
2431 Align = ElBits; \
2432 break;
2433#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2434 case BuiltinType::Id: \
2435 Width = 0; \
2436 Align = 8; \
2437 break;
2438#include "clang/Basic/RISCVVTypes.def"
2439#define WASM_TYPE(Name, Id, SingletonId) \
2440 case BuiltinType::Id: \
2441 Width = 0; \
2442 Align = 8; \
2443 break;
2444#include "clang/Basic/WebAssemblyReferenceTypes.def"
2445#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2446 case BuiltinType::ID: \
2447 Width = WIDTH; \
2448 Align = ALIGN; \
2449 break;
2450#include "clang/Basic/AMDGPUTypes.def"
2451#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2452#include "clang/Basic/HLSLIntangibleTypes.def"
2453 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2454 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2455 break;
2456#define SPIRV_TYPE(Name, Id, SingletonId) \
2457 case BuiltinType::Id: \
2458 Width = Target->getPointerWidth(LangAS::Default); \
2459 Align = Target->getPointerAlign(LangAS::Default); \
2460 break;
2461#include "clang/Basic/SPIRVTypes.def"
2462 }
2463 break;
2464 case Type::ObjCObjectPointer:
2465 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2466 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2467 break;
2468 case Type::BlockPointer:
2469 AS = cast<BlockPointerType>(Val: T)->getPointeeType().getAddressSpace();
2470 Width = Target->getPointerWidth(AddrSpace: AS);
2471 Align = Target->getPointerAlign(AddrSpace: AS);
2472 break;
2473 case Type::LValueReference:
2474 case Type::RValueReference:
2475 // alignof and sizeof should never enter this code path here, so we go
2476 // the pointer route.
2477 AS = cast<ReferenceType>(Val: T)->getPointeeType().getAddressSpace();
2478 Width = Target->getPointerWidth(AddrSpace: AS);
2479 Align = Target->getPointerAlign(AddrSpace: AS);
2480 break;
2481 case Type::Pointer:
2482 AS = cast<PointerType>(Val: T)->getPointeeType().getAddressSpace();
2483 Width = Target->getPointerWidth(AddrSpace: AS);
2484 Align = Target->getPointerAlign(AddrSpace: AS);
2485 break;
2486 case Type::MemberPointer: {
2487 const auto *MPT = cast<MemberPointerType>(Val: T);
2488 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2489 Width = MPI.Width;
2490 Align = MPI.Align;
2491 break;
2492 }
2493 case Type::Complex: {
2494 // Complex types have the same alignment as their elements, but twice the
2495 // size.
2496 TypeInfo EltInfo = getTypeInfo(T: cast<ComplexType>(Val: T)->getElementType());
2497 Width = EltInfo.Width * 2;
2498 Align = EltInfo.Align;
2499 break;
2500 }
2501 case Type::ObjCObject:
2502 return getTypeInfo(T: cast<ObjCObjectType>(Val: T)->getBaseType().getTypePtr());
2503 case Type::Adjusted:
2504 case Type::Decayed:
2505 return getTypeInfo(T: cast<AdjustedType>(Val: T)->getAdjustedType().getTypePtr());
2506 case Type::ObjCInterface: {
2507 const auto *ObjCI = cast<ObjCInterfaceType>(Val: T);
2508 if (ObjCI->getDecl()->isInvalidDecl()) {
2509 Width = 8;
2510 Align = 8;
2511 break;
2512 }
2513 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(D: ObjCI->getDecl());
2514 Width = toBits(CharSize: Layout.getSize());
2515 Align = toBits(CharSize: Layout.getAlignment());
2516 break;
2517 }
2518 case Type::BitInt: {
2519 const auto *EIT = cast<BitIntType>(Val: T);
2520 Align = Target->getBitIntAlign(NumBits: EIT->getNumBits());
2521 Width = Target->getBitIntWidth(NumBits: EIT->getNumBits());
2522 break;
2523 }
2524 case Type::Record:
2525 case Type::Enum: {
2526 const auto *TT = cast<TagType>(Val: T);
2527 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2528
2529 if (TD->isInvalidDecl()) {
2530 Width = 8;
2531 Align = 8;
2532 break;
2533 }
2534
2535 if (isa<EnumType>(Val: TT)) {
2536 const EnumDecl *ED = cast<EnumDecl>(Val: TD);
2537 TypeInfo Info =
2538 getTypeInfo(T: ED->getIntegerType()->getUnqualifiedDesugaredType());
2539 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2540 Info.Align = AttrAlign;
2541 Info.AlignRequirement = AlignRequirementKind::RequiredByEnum;
2542 }
2543 return Info;
2544 }
2545
2546 const auto *RD = cast<RecordDecl>(Val: TD);
2547 const ASTRecordLayout &Layout = getASTRecordLayout(D: RD);
2548 Width = toBits(CharSize: Layout.getSize());
2549 Align = toBits(CharSize: Layout.getAlignment());
2550 AlignRequirement = RD->hasAttr<AlignedAttr>()
2551 ? AlignRequirementKind::RequiredByRecord
2552 : AlignRequirementKind::None;
2553 break;
2554 }
2555
2556 case Type::SubstTemplateTypeParm:
2557 return getTypeInfo(T: cast<SubstTemplateTypeParmType>(Val: T)->
2558 getReplacementType().getTypePtr());
2559
2560 case Type::Auto:
2561 case Type::DeducedTemplateSpecialization: {
2562 const auto *A = cast<DeducedType>(Val: T);
2563 assert(!A->getDeducedType().isNull() &&
2564 "cannot request the size of an undeduced or dependent auto type");
2565 return getTypeInfo(T: A->getDeducedType().getTypePtr());
2566 }
2567
2568 case Type::Paren:
2569 return getTypeInfo(T: cast<ParenType>(Val: T)->getInnerType().getTypePtr());
2570
2571 case Type::MacroQualified:
2572 return getTypeInfo(
2573 T: cast<MacroQualifiedType>(Val: T)->getUnderlyingType().getTypePtr());
2574
2575 case Type::ObjCTypeParam:
2576 return getTypeInfo(T: cast<ObjCTypeParamType>(Val: T)->desugar().getTypePtr());
2577
2578 case Type::Using:
2579 return getTypeInfo(T: cast<UsingType>(Val: T)->desugar().getTypePtr());
2580
2581 case Type::Typedef: {
2582 const auto *TT = cast<TypedefType>(Val: T);
2583 TypeInfo Info = getTypeInfo(T: TT->desugar().getTypePtr());
2584 // If the typedef has an aligned attribute on it, it overrides any computed
2585 // alignment we have. This violates the GCC documentation (which says that
2586 // attribute(aligned) can only round up) but matches its implementation.
2587 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2588 Align = AttrAlign;
2589 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2590 } else {
2591 Align = Info.Align;
2592 AlignRequirement = Info.AlignRequirement;
2593 }
2594 Width = Info.Width;
2595 break;
2596 }
2597
2598 case Type::Attributed:
2599 return getTypeInfo(
2600 T: cast<AttributedType>(Val: T)->getEquivalentType().getTypePtr());
2601
2602 case Type::CountAttributed:
2603 return getTypeInfo(T: cast<CountAttributedType>(Val: T)->desugar().getTypePtr());
2604
2605 case Type::LateParsedAttr:
2606 return getTypeInfo(T: cast<LateParsedAttrType>(Val: T)->desugar().getTypePtr());
2607
2608 case Type::BTFTagAttributed:
2609 return getTypeInfo(
2610 T: cast<BTFTagAttributedType>(Val: T)->getWrappedType().getTypePtr());
2611
2612 case Type::OverflowBehavior:
2613 return getTypeInfo(
2614 T: cast<OverflowBehaviorType>(Val: T)->getUnderlyingType().getTypePtr());
2615
2616 case Type::HLSLAttributedResource:
2617 return getTypeInfo(
2618 T: cast<HLSLAttributedResourceType>(Val: T)->getWrappedType().getTypePtr());
2619
2620 case Type::HLSLInlineSpirv: {
2621 const auto *ST = cast<HLSLInlineSpirvType>(Val: T);
2622 // Size is specified in bytes, convert to bits
2623 Width = ST->getSize() * 8;
2624 Align = ST->getAlignment();
2625 if (Width == 0 && Align == 0) {
2626 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2627 Width = 32;
2628 Align = 32;
2629 }
2630 break;
2631 }
2632
2633 case Type::Atomic: {
2634 // Start with the base type information.
2635 TypeInfo Info = getTypeInfo(T: cast<AtomicType>(Val: T)->getValueType());
2636 Width = Info.Width;
2637 Align = Info.Align;
2638
2639 if (!Width) {
2640 // An otherwise zero-sized type should still generate an
2641 // atomic operation.
2642 Width = Target->getCharWidth();
2643 assert(Align);
2644 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2645 // If the size of the type doesn't exceed the platform's max
2646 // atomic promotion width, make the size and alignment more
2647 // favorable to atomic operations:
2648
2649 // Round the size up to a power of 2.
2650 Width = llvm::bit_ceil(Value: Width);
2651
2652 // Set the alignment equal to the size.
2653 Align = static_cast<unsigned>(Width);
2654 }
2655 }
2656 break;
2657
2658 case Type::PredefinedSugar:
2659 return getTypeInfo(T: cast<PredefinedSugarType>(Val: T)->desugar().getTypePtr());
2660
2661 case Type::Pipe:
2662 Width = Target->getPointerWidth(AddrSpace: LangAS::opencl_global);
2663 Align = Target->getPointerAlign(AddrSpace: LangAS::opencl_global);
2664 break;
2665 }
2666
2667 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2668 return TypeInfo(Width, Align, AlignRequirement);
2669}
2670
2671unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2672 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(Val: T);
2673 if (I != MemoizedUnadjustedAlign.end())
2674 return I->second;
2675
2676 unsigned UnadjustedAlign;
2677 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2678 const ASTRecordLayout &Layout = getASTRecordLayout(D: RT->getDecl());
2679 UnadjustedAlign = toBits(CharSize: Layout.getUnadjustedAlignment());
2680 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2681 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(D: ObjCI->getDecl());
2682 UnadjustedAlign = toBits(CharSize: Layout.getUnadjustedAlignment());
2683 } else {
2684 UnadjustedAlign = getTypeAlign(T: T->getUnqualifiedDesugaredType());
2685 }
2686
2687 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2688 return UnadjustedAlign;
2689}
2690
2691unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2692 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2693 TargetTriple: getTargetInfo().getTriple(), Features: Target->getTargetOpts().FeatureMap);
2694 return SimdAlign;
2695}
2696
2697/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2698CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2699 return CharUnits::fromQuantity(Quantity: BitSize / getCharWidth());
2700}
2701
2702/// toBits - Convert a size in characters to a size in characters.
2703int64_t ASTContext::toBits(CharUnits CharSize) const {
2704 return CharSize.getQuantity() * getCharWidth();
2705}
2706
2707/// getTypeSizeInChars - Return the size of the specified type, in characters.
2708/// This method does not work on incomplete types.
2709CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2710 return getTypeInfoInChars(T).Width;
2711}
2712CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2713 return getTypeInfoInChars(T).Width;
2714}
2715
2716/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2717/// characters. This method does not work on incomplete types.
2718CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2719 return toCharUnitsFromBits(BitSize: getTypeAlign(T));
2720}
2721CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2722 return toCharUnitsFromBits(BitSize: getTypeAlign(T));
2723}
2724
2725/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2726/// type, in characters, before alignment adjustments. This method does
2727/// not work on incomplete types.
2728CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2729 return toCharUnitsFromBits(BitSize: getTypeUnadjustedAlign(T));
2730}
2731CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2732 return toCharUnitsFromBits(BitSize: getTypeUnadjustedAlign(T));
2733}
2734
2735/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2736/// type for the current target in bits. This can be different than the ABI
2737/// alignment in cases where it is beneficial for performance or backwards
2738/// compatibility preserving to overalign a data type. (Note: despite the name,
2739/// the preferred alignment is ABI-impacting, and not an optimization.)
2740unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2741 TypeInfo TI = getTypeInfo(T);
2742 unsigned ABIAlign = TI.Align;
2743
2744 T = T->getBaseElementTypeUnsafe();
2745
2746 // The preferred alignment of member pointers is that of a pointer.
2747 if (T->isMemberPointerType())
2748 return getPreferredTypeAlign(T: getPointerDiffType().getTypePtr());
2749
2750 if (!Target->allowsLargerPreferedTypeAlignment())
2751 return ABIAlign;
2752
2753 if (const auto *RD = T->getAsRecordDecl()) {
2754 // When used as part of a typedef, or together with a 'packed' attribute,
2755 // the 'aligned' attribute can be used to decrease alignment. Note that the
2756 // 'packed' case is already taken into consideration when computing the
2757 // alignment, we only need to handle the typedef case here.
2758 if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
2759 RD->isInvalidDecl())
2760 return ABIAlign;
2761
2762 unsigned PreferredAlign = static_cast<unsigned>(
2763 toBits(CharSize: getASTRecordLayout(D: RD).PreferredAlignment));
2764 assert(PreferredAlign >= ABIAlign &&
2765 "PreferredAlign should be at least as large as ABIAlign.");
2766 return PreferredAlign;
2767 }
2768
2769 // Double (and, for targets supporting AIX `power` alignment, long double) and
2770 // long long should be naturally aligned (despite requiring less alignment) if
2771 // possible.
2772 if (const auto *CT = T->getAs<ComplexType>())
2773 T = CT->getElementType().getTypePtr();
2774 if (const auto *ED = T->getAsEnumDecl())
2775 T = ED->getIntegerType().getTypePtr();
2776 if (T->isSpecificBuiltinType(K: BuiltinType::Double) ||
2777 T->isSpecificBuiltinType(K: BuiltinType::LongLong) ||
2778 T->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
2779 (T->isSpecificBuiltinType(K: BuiltinType::LongDouble) &&
2780 Target->defaultsToAIXPowerAlignment()))
2781 // Don't increase the alignment if an alignment attribute was specified on a
2782 // typedef declaration.
2783 if (!TI.isAlignRequired())
2784 return std::max(a: ABIAlign, b: (unsigned)getTypeSize(T));
2785
2786 return ABIAlign;
2787}
2788
2789/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2790/// for __attribute__((aligned)) on this target, to be used if no alignment
2791/// value is specified.
2792unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2793 return getTargetInfo().getDefaultAlignForAttributeAligned();
2794}
2795
2796/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2797/// to a global variable of the specified type.
2798unsigned ASTContext::getAlignOfGlobalVar(QualType T, const VarDecl *VD) const {
2799 uint64_t TypeSize = getTypeSize(T: T.getTypePtr());
2800 return std::max(a: getPreferredTypeAlign(T),
2801 b: getMinGlobalAlignOfVar(Size: TypeSize, VD));
2802}
2803
2804/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2805/// should be given to a global variable of the specified type.
2806CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T,
2807 const VarDecl *VD) const {
2808 return toCharUnitsFromBits(BitSize: getAlignOfGlobalVar(T, VD));
2809}
2810
2811unsigned ASTContext::getMinGlobalAlignOfVar(uint64_t Size,
2812 const VarDecl *VD) const {
2813 // Make the default handling as that of a non-weak definition in the
2814 // current translation unit.
2815 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2816 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2817}
2818
2819CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2820 CharUnits Offset = CharUnits::Zero();
2821 const ASTRecordLayout *Layout = &getASTRecordLayout(D: RD);
2822 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2823 Offset += Layout->getBaseClassOffset(Base);
2824 Layout = &getASTRecordLayout(D: Base);
2825 }
2826 return Offset;
2827}
2828
2829CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2830 const ValueDecl *MPD = MP.getMemberPointerDecl();
2831 CharUnits ThisAdjustment = CharUnits::Zero();
2832 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2833 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2834 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: MPD->getDeclContext());
2835 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2836 const CXXRecordDecl *Base = RD;
2837 const CXXRecordDecl *Derived = Path[I];
2838 if (DerivedMember)
2839 std::swap(a&: Base, b&: Derived);
2840 ThisAdjustment += getASTRecordLayout(D: Derived).getBaseClassOffset(Base);
2841 RD = Path[I];
2842 }
2843 if (DerivedMember)
2844 ThisAdjustment = -ThisAdjustment;
2845 return ThisAdjustment;
2846}
2847
2848/// DeepCollectObjCIvars -
2849/// This routine first collects all declared, but not synthesized, ivars in
2850/// super class and then collects all ivars, including those synthesized for
2851/// current class. This routine is used for implementation of current class
2852/// when all ivars, declared and synthesized are known.
2853void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2854 bool leafClass,
2855 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2856 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2857 DeepCollectObjCIvars(OI: SuperClass, leafClass: false, Ivars);
2858 if (!leafClass) {
2859 llvm::append_range(C&: Ivars, R: OI->ivars());
2860 } else {
2861 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2862 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2863 Iv= Iv->getNextIvar())
2864 Ivars.push_back(Elt: Iv);
2865 }
2866}
2867
2868/// CollectInheritedProtocols - Collect all protocols in current class and
2869/// those inherited by it.
2870void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2871 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2872 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(Val: CDecl)) {
2873 // We can use protocol_iterator here instead of
2874 // all_referenced_protocol_iterator since we are walking all categories.
2875 for (auto *Proto : OI->all_referenced_protocols()) {
2876 CollectInheritedProtocols(CDecl: Proto, Protocols);
2877 }
2878
2879 // Categories of this Interface.
2880 for (const auto *Cat : OI->visible_categories())
2881 CollectInheritedProtocols(CDecl: Cat, Protocols);
2882
2883 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2884 while (SD) {
2885 CollectInheritedProtocols(CDecl: SD, Protocols);
2886 SD = SD->getSuperClass();
2887 }
2888 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(Val: CDecl)) {
2889 for (auto *Proto : OC->protocols()) {
2890 CollectInheritedProtocols(CDecl: Proto, Protocols);
2891 }
2892 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(Val: CDecl)) {
2893 // Insert the protocol.
2894 if (!Protocols.insert(
2895 Ptr: const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2896 return;
2897
2898 for (auto *Proto : OP->protocols())
2899 CollectInheritedProtocols(CDecl: Proto, Protocols);
2900 }
2901}
2902
2903static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2904 const RecordDecl *RD,
2905 bool CheckIfTriviallyCopyable) {
2906 assert(RD->isUnion() && "Must be union type");
2907 CharUnits UnionSize =
2908 Context.getTypeSizeInChars(T: Context.getCanonicalTagType(TD: RD));
2909
2910 for (const auto *Field : RD->fields()) {
2911 if (!Context.hasUniqueObjectRepresentations(Ty: Field->getType(),
2912 CheckIfTriviallyCopyable))
2913 return false;
2914 CharUnits FieldSize = Context.getTypeSizeInChars(T: Field->getType());
2915 if (FieldSize != UnionSize)
2916 return false;
2917 }
2918 return !RD->field_empty();
2919}
2920
2921static int64_t getSubobjectOffset(const FieldDecl *Field,
2922 const ASTContext &Context,
2923 const clang::ASTRecordLayout & /*Layout*/) {
2924 return Context.getFieldOffset(FD: Field);
2925}
2926
2927static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2928 const ASTContext &Context,
2929 const clang::ASTRecordLayout &Layout) {
2930 return Context.toBits(CharSize: Layout.getBaseClassOffset(Base: RD));
2931}
2932
2933static std::optional<int64_t>
2934structHasUniqueObjectRepresentations(const ASTContext &Context,
2935 const RecordDecl *RD,
2936 bool CheckIfTriviallyCopyable);
2937
2938static std::optional<int64_t>
2939getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2940 bool CheckIfTriviallyCopyable) {
2941 if (const auto *RD = Field->getType()->getAsRecordDecl();
2942 RD && !RD->isUnion())
2943 return structHasUniqueObjectRepresentations(Context, RD,
2944 CheckIfTriviallyCopyable);
2945
2946 // A _BitInt type may not be unique if it has padding bits
2947 // but if it is a bitfield the padding bits are not used.
2948 bool IsBitIntType = Field->getType()->isBitIntType();
2949 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2950 !Context.hasUniqueObjectRepresentations(Ty: Field->getType(),
2951 CheckIfTriviallyCopyable))
2952 return std::nullopt;
2953
2954 int64_t FieldSizeInBits =
2955 Context.toBits(CharSize: Context.getTypeSizeInChars(T: Field->getType()));
2956 if (Field->isBitField()) {
2957 // If we have explicit padding bits, they don't contribute bits
2958 // to the actual object representation, so return 0.
2959 if (Field->isUnnamedBitField())
2960 return 0;
2961
2962 int64_t BitfieldSize = Field->getBitWidthValue();
2963 if (IsBitIntType) {
2964 if ((unsigned)BitfieldSize >
2965 cast<BitIntType>(Val: Field->getType())->getNumBits())
2966 return std::nullopt;
2967 } else if (BitfieldSize > FieldSizeInBits) {
2968 return std::nullopt;
2969 }
2970 FieldSizeInBits = BitfieldSize;
2971 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2972 Ty: Field->getType(), CheckIfTriviallyCopyable)) {
2973 return std::nullopt;
2974 }
2975 return FieldSizeInBits;
2976}
2977
2978static std::optional<int64_t>
2979getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context,
2980 bool CheckIfTriviallyCopyable) {
2981 return structHasUniqueObjectRepresentations(Context, RD,
2982 CheckIfTriviallyCopyable);
2983}
2984
2985template <typename RangeT>
2986static std::optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations(
2987 const RangeT &Subobjects, int64_t CurOffsetInBits,
2988 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2989 bool CheckIfTriviallyCopyable) {
2990 for (const auto *Subobject : Subobjects) {
2991 std::optional<int64_t> SizeInBits =
2992 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2993 if (!SizeInBits)
2994 return std::nullopt;
2995 if (*SizeInBits != 0) {
2996 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2997 if (Offset != CurOffsetInBits)
2998 return std::nullopt;
2999 CurOffsetInBits += *SizeInBits;
3000 }
3001 }
3002 return CurOffsetInBits;
3003}
3004
3005static std::optional<int64_t>
3006structHasUniqueObjectRepresentations(const ASTContext &Context,
3007 const RecordDecl *RD,
3008 bool CheckIfTriviallyCopyable) {
3009 assert(!RD->isUnion() && "Must be struct/class type");
3010 const auto &Layout = Context.getASTRecordLayout(D: RD);
3011
3012 int64_t CurOffsetInBits = 0;
3013 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD)) {
3014 if (ClassDecl->isDynamicClass())
3015 return std::nullopt;
3016
3017 SmallVector<CXXRecordDecl *, 4> Bases;
3018 for (const auto &Base : ClassDecl->bases()) {
3019 // Empty types can be inherited from, and non-empty types can potentially
3020 // have tail padding, so just make sure there isn't an error.
3021 Bases.emplace_back(Args: Base.getType()->getAsCXXRecordDecl());
3022 }
3023
3024 llvm::sort(C&: Bases, Comp: [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3025 return Layout.getBaseClassOffset(Base: L) < Layout.getBaseClassOffset(Base: R);
3026 });
3027
3028 std::optional<int64_t> OffsetAfterBases =
3029 structSubobjectsHaveUniqueObjectRepresentations(
3030 Subobjects: Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
3031 if (!OffsetAfterBases)
3032 return std::nullopt;
3033 CurOffsetInBits = *OffsetAfterBases;
3034 }
3035
3036 std::optional<int64_t> OffsetAfterFields =
3037 structSubobjectsHaveUniqueObjectRepresentations(
3038 Subobjects: RD->fields(), CurOffsetInBits, Context, Layout,
3039 CheckIfTriviallyCopyable);
3040 if (!OffsetAfterFields)
3041 return std::nullopt;
3042 CurOffsetInBits = *OffsetAfterFields;
3043
3044 return CurOffsetInBits;
3045}
3046
3047bool ASTContext::hasUniqueObjectRepresentations(
3048 QualType Ty, bool CheckIfTriviallyCopyable) const {
3049 // C++17 [meta.unary.prop]:
3050 // The predicate condition for a template specialization
3051 // has_unique_object_representations<T> shall be satisfied if and only if:
3052 // (9.1) - T is trivially copyable, and
3053 // (9.2) - any two objects of type T with the same value have the same
3054 // object representation, where:
3055 // - two objects of array or non-union class type are considered to have
3056 // the same value if their respective sequences of direct subobjects
3057 // have the same values, and
3058 // - two objects of union type are considered to have the same value if
3059 // they have the same active member and the corresponding members have
3060 // the same value.
3061 // The set of scalar types for which this condition holds is
3062 // implementation-defined. [ Note: If a type has padding bits, the condition
3063 // does not hold; otherwise, the condition holds true for unsigned integral
3064 // types. -- end note ]
3065 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3066
3067 // Arrays are unique only if their element type is unique.
3068 if (Ty->isArrayType())
3069 return hasUniqueObjectRepresentations(Ty: getBaseElementType(QT: Ty),
3070 CheckIfTriviallyCopyable);
3071
3072 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3073 "hasUniqueObjectRepresentations should not be called with an "
3074 "incomplete type");
3075
3076 // (9.1) - T is trivially copyable...
3077 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(Context: *this))
3078 return false;
3079
3080 // All integrals and enums are unique.
3081 if (Ty->isIntegralOrEnumerationType()) {
3082 // Address discriminated integer types are not unique.
3083 if (Ty.hasAddressDiscriminatedPointerAuth())
3084 return false;
3085 // Except _BitInt types that have padding bits.
3086 if (const auto *BIT = Ty->getAs<BitIntType>())
3087 return getTypeSize(T: BIT) == BIT->getNumBits();
3088
3089 return true;
3090 }
3091
3092 // All other pointers are unique.
3093 if (Ty->isPointerType())
3094 return !Ty.hasAddressDiscriminatedPointerAuth();
3095
3096 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3097 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3098
3099 if (const auto *Record = Ty->getAsRecordDecl()) {
3100 if (Record->isInvalidDecl())
3101 return false;
3102
3103 if (Record->isUnion())
3104 return unionHasUniqueObjectRepresentations(Context: *this, RD: Record,
3105 CheckIfTriviallyCopyable);
3106
3107 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3108 Context: *this, RD: Record, CheckIfTriviallyCopyable);
3109
3110 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(T: Ty));
3111 }
3112
3113 // FIXME: More cases to handle here (list by rsmith):
3114 // vectors (careful about, eg, vector of 3 foo)
3115 // _Complex int and friends
3116 // _Atomic T
3117 // Obj-C block pointers
3118 // Obj-C object pointers
3119 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3120 // clk_event_t, queue_t, reserve_id_t)
3121 // There're also Obj-C class types and the Obj-C selector type, but I think it
3122 // makes sense for those to return false here.
3123
3124 return false;
3125}
3126
3127unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
3128 unsigned count = 0;
3129 // Count ivars declared in class extension.
3130 for (const auto *Ext : OI->known_extensions())
3131 count += Ext->ivar_size();
3132
3133 // Count ivar defined in this class's implementation. This
3134 // includes synthesized ivars.
3135 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3136 count += ImplDecl->ivar_size();
3137
3138 return count;
3139}
3140
3141bool ASTContext::isSentinelNullExpr(const Expr *E) {
3142 if (!E)
3143 return false;
3144
3145 // nullptr_t is always treated as null.
3146 if (E->getType()->isNullPtrType()) return true;
3147
3148 if (E->getType()->isAnyPointerType() &&
3149 E->IgnoreParenCasts()->isNullPointerConstant(Ctx&: *this,
3150 NPC: Expr::NPC_ValueDependentIsNull))
3151 return true;
3152
3153 // Unfortunately, __null has type 'int'.
3154 if (isa<GNUNullExpr>(Val: E)) return true;
3155
3156 return false;
3157}
3158
3159/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3160/// exists.
3161ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
3162 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3163 I = ObjCImpls.find(Val: D);
3164 if (I != ObjCImpls.end())
3165 return cast<ObjCImplementationDecl>(Val: I->second);
3166 return nullptr;
3167}
3168
3169/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3170/// exists.
3171ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
3172 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3173 I = ObjCImpls.find(Val: D);
3174 if (I != ObjCImpls.end())
3175 return cast<ObjCCategoryImplDecl>(Val: I->second);
3176 return nullptr;
3177}
3178
3179/// Set the implementation of ObjCInterfaceDecl.
3180void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
3181 ObjCImplementationDecl *ImplD) {
3182 assert(IFaceD && ImplD && "Passed null params");
3183 ObjCImpls[IFaceD] = ImplD;
3184}
3185
3186/// Set the implementation of ObjCCategoryDecl.
3187void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
3188 ObjCCategoryImplDecl *ImplD) {
3189 assert(CatD && ImplD && "Passed null params");
3190 ObjCImpls[CatD] = ImplD;
3191}
3192
3193const ObjCMethodDecl *
3194ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
3195 return ObjCMethodRedecls.lookup(Val: MD);
3196}
3197
3198void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
3199 const ObjCMethodDecl *Redecl) {
3200 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3201 ObjCMethodRedecls[MD] = Redecl;
3202}
3203
3204const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
3205 const NamedDecl *ND) const {
3206 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(Val: ND->getDeclContext()))
3207 return ID;
3208 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(Val: ND->getDeclContext()))
3209 return CD->getClassInterface();
3210 if (const auto *IMD = dyn_cast<ObjCImplDecl>(Val: ND->getDeclContext()))
3211 return IMD->getClassInterface();
3212
3213 return nullptr;
3214}
3215
3216/// Get the copy initialization expression of VarDecl, or nullptr if
3217/// none exists.
3218BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
3219 assert(VD && "Passed null params");
3220 assert(VD->hasAttr<BlocksAttr>() &&
3221 "getBlockVarCopyInits - not __block var");
3222 auto I = BlockVarCopyInits.find(Val: VD);
3223 if (I != BlockVarCopyInits.end())
3224 return I->second;
3225 return {nullptr, false};
3226}
3227
3228/// Set the copy initialization expression of a block var decl.
3229void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
3230 bool CanThrow) {
3231 assert(VD && CopyExpr && "Passed null params");
3232 assert(VD->hasAttr<BlocksAttr>() &&
3233 "setBlockVarCopyInits - not __block var");
3234 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3235}
3236
3237TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
3238 unsigned DataSize) const {
3239 if (!DataSize)
3240 DataSize = TypeLoc::getFullDataSizeForType(Ty: T);
3241 else
3242 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3243 "incorrect data size provided to CreateTypeSourceInfo!");
3244
3245 auto *TInfo =
3246 (TypeSourceInfo*)BumpAlloc.Allocate(Size: sizeof(TypeSourceInfo) + DataSize, Alignment: 8);
3247 new (TInfo) TypeSourceInfo(T, DataSize);
3248 return TInfo;
3249}
3250
3251TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
3252 SourceLocation L) const {
3253 TypeSourceInfo *TSI = CreateTypeSourceInfo(T);
3254 TSI->getTypeLoc().initialize(Context&: const_cast<ASTContext &>(*this), Loc: L);
3255 return TSI;
3256}
3257
3258const ASTRecordLayout &
3259ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
3260 return getObjCLayout(D);
3261}
3262
3263static auto getCanonicalTemplateArguments(const ASTContext &C,
3264 ArrayRef<TemplateArgument> Args,
3265 bool &AnyNonCanonArgs) {
3266 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3267 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(Args: CanonArgs);
3268 return CanonArgs;
3269}
3270
3271bool ASTContext::canonicalizeTemplateArguments(
3272 MutableArrayRef<TemplateArgument> Args) const {
3273 bool AnyNonCanonArgs = false;
3274 for (auto &Arg : Args) {
3275 TemplateArgument OrigArg = Arg;
3276 Arg = getCanonicalTemplateArgument(Arg);
3277 AnyNonCanonArgs |= !Arg.structurallyEquals(Other: OrigArg);
3278 }
3279 return AnyNonCanonArgs;
3280}
3281
3282//===----------------------------------------------------------------------===//
3283// Type creation/memoization methods
3284//===----------------------------------------------------------------------===//
3285
3286QualType
3287ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3288 unsigned fastQuals = quals.getFastQualifiers();
3289 quals.removeFastQualifiers();
3290
3291 // Check if we've already instantiated this type.
3292 llvm::FoldingSetNodeID ID;
3293 ExtQuals::Profile(ID, BaseType: baseType, Quals: quals);
3294 void *insertPos = nullptr;
3295 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos&: insertPos)) {
3296 assert(eq->getQualifiers() == quals);
3297 return QualType(eq, fastQuals);
3298 }
3299
3300 // If the base type is not canonical, make the appropriate canonical type.
3301 QualType canon;
3302 if (!baseType->isCanonicalUnqualified()) {
3303 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3304 canonSplit.Quals.addConsistentQualifiers(qs: quals);
3305 canon = getExtQualType(baseType: canonSplit.Ty, quals: canonSplit.Quals);
3306
3307 // Re-find the insert position.
3308 (void) ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos&: insertPos);
3309 }
3310
3311 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3312 ExtQualNodes.InsertNode(N: eq, InsertPos: insertPos);
3313 return QualType(eq, fastQuals);
3314}
3315
3316QualType ASTContext::getAddrSpaceQualType(QualType T,
3317 LangAS AddressSpace) const {
3318 QualType CanT = getCanonicalType(T);
3319 if (CanT.getAddressSpace() == AddressSpace)
3320 return T;
3321
3322 // If we are composing extended qualifiers together, merge together
3323 // into one ExtQuals node.
3324 QualifierCollector Quals;
3325 const Type *TypeNode = Quals.strip(type: T);
3326
3327 // If this type already has an address space specified, it cannot get
3328 // another one.
3329 assert(!Quals.hasAddressSpace() &&
3330 "Type cannot be in multiple addr spaces!");
3331 Quals.addAddressSpace(space: AddressSpace);
3332
3333 return getExtQualType(baseType: TypeNode, quals: Quals);
3334}
3335
3336QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
3337 // If the type is not qualified with an address space, just return it
3338 // immediately.
3339 if (!T.hasAddressSpace())
3340 return T;
3341
3342 QualifierCollector Quals;
3343 const Type *TypeNode;
3344 // For arrays, strip the qualifier off the element type, then reconstruct the
3345 // array type
3346 if (T.getTypePtr()->isArrayType()) {
3347 T = getUnqualifiedArrayType(T, Quals);
3348 TypeNode = T.getTypePtr();
3349 } else {
3350 // If we are composing extended qualifiers together, merge together
3351 // into one ExtQuals node.
3352 while (T.hasAddressSpace()) {
3353 TypeNode = Quals.strip(type: T);
3354
3355 // If the type no longer has an address space after stripping qualifiers,
3356 // jump out.
3357 if (!QualType(TypeNode, 0).hasAddressSpace())
3358 break;
3359
3360 // There might be sugar in the way. Strip it and try again.
3361 T = T.getSingleStepDesugaredType(Context: *this);
3362 }
3363 }
3364
3365 Quals.removeAddressSpace();
3366
3367 // Removal of the address space can mean there are no longer any
3368 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3369 // or required.
3370 if (Quals.hasNonFastQualifiers())
3371 return getExtQualType(baseType: TypeNode, quals: Quals);
3372 else
3373 return QualType(TypeNode, Quals.getFastQualifiers());
3374}
3375
3376uint16_t
3377ASTContext::getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD,
3378 bool IsVTTEntry) {
3379 assert(RD->isPolymorphic() &&
3380 "Attempted to get vtable pointer discriminator on a monomorphic type");
3381
3382 std::unique_ptr<MangleContext> MC(createMangleContext());
3383 SmallString<256> Str;
3384 llvm::raw_svector_ostream Out(Str);
3385 MC->mangleCXXVTable(RD, Out);
3386 if (IsVTTEntry)
3387 Out << VTTVTablePointerDiscriminatorSuffix;
3388 return llvm::getPointerAuthStableSipHash(S: Str);
3389}
3390
3391/// Encode a function type for use in the discriminator of a function pointer
3392/// type. We can't use the itanium scheme for this since C has quite permissive
3393/// rules for type compatibility that we need to be compatible with.
3394///
3395/// Formally, this function associates every function pointer type T with an
3396/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3397/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3398/// compatibility requires equivalent treatment under the ABI, so
3399/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3400/// a subset of ~. Crucially, however, it must be a proper subset because
3401/// CCompatible is not an equivalence relation: for example, int[] is compatible
3402/// with both int[1] and int[2], but the latter are not compatible with each
3403/// other. Therefore this encoding function must be careful to only distinguish
3404/// types if there is no third type with which they are both required to be
3405/// compatible.
3406static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx,
3407 raw_ostream &OS, QualType QT) {
3408 // FIXME: Consider address space qualifiers.
3409 const Type *T = QT.getCanonicalType().getTypePtr();
3410
3411 // FIXME: Consider using the C++ type mangling when we encounter a construct
3412 // that is incompatible with C.
3413
3414 switch (T->getTypeClass()) {
3415 case Type::Atomic:
3416 return encodeTypeForFunctionPointerAuth(
3417 Ctx, OS, QT: cast<AtomicType>(Val: T)->getValueType());
3418
3419 case Type::LValueReference:
3420 OS << "R";
3421 encodeTypeForFunctionPointerAuth(Ctx, OS,
3422 QT: cast<ReferenceType>(Val: T)->getPointeeType());
3423 return;
3424 case Type::RValueReference:
3425 OS << "O";
3426 encodeTypeForFunctionPointerAuth(Ctx, OS,
3427 QT: cast<ReferenceType>(Val: T)->getPointeeType());
3428 return;
3429
3430 case Type::Pointer:
3431 // C11 6.7.6.1p2:
3432 // For two pointer types to be compatible, both shall be identically
3433 // qualified and both shall be pointers to compatible types.
3434 // FIXME: we should also consider pointee types.
3435 OS << "P";
3436 return;
3437
3438 case Type::ObjCObjectPointer:
3439 case Type::BlockPointer:
3440 OS << "P";
3441 return;
3442
3443 case Type::Complex:
3444 OS << "C";
3445 return encodeTypeForFunctionPointerAuth(
3446 Ctx, OS, QT: cast<ComplexType>(Val: T)->getElementType());
3447
3448 case Type::VariableArray:
3449 case Type::ConstantArray:
3450 case Type::IncompleteArray:
3451 case Type::ArrayParameter:
3452 // C11 6.7.6.2p6:
3453 // For two array types to be compatible, both shall have compatible
3454 // element types, and if both size specifiers are present, and are integer
3455 // constant expressions, then both size specifiers shall have the same
3456 // constant value [...]
3457 //
3458 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3459 // width of the array.
3460 OS << "A";
3461 return encodeTypeForFunctionPointerAuth(
3462 Ctx, OS, QT: cast<ArrayType>(Val: T)->getElementType());
3463
3464 case Type::ObjCInterface:
3465 case Type::ObjCObject:
3466 OS << "<objc_object>";
3467 return;
3468
3469 case Type::Enum: {
3470 // C11 6.7.2.2p4:
3471 // Each enumerated type shall be compatible with char, a signed integer
3472 // type, or an unsigned integer type.
3473 //
3474 // So we have to treat enum types as integers.
3475 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3476 return encodeTypeForFunctionPointerAuth(
3477 Ctx, OS, QT: UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3478 }
3479
3480 case Type::FunctionNoProto:
3481 case Type::FunctionProto: {
3482 // C11 6.7.6.3p15:
3483 // For two function types to be compatible, both shall specify compatible
3484 // return types. Moreover, the parameter type lists, if both are present,
3485 // shall agree in the number of parameters and in the use of the ellipsis
3486 // terminator; corresponding parameters shall have compatible types.
3487 //
3488 // That paragraph goes on to describe how unprototyped functions are to be
3489 // handled, which we ignore here. Unprototyped function pointers are hashed
3490 // as though they were prototyped nullary functions since thats probably
3491 // what the user meant. This behavior is non-conforming.
3492 // FIXME: If we add a "custom discriminator" function type attribute we
3493 // should encode functions as their discriminators.
3494 OS << "F";
3495 const auto *FuncType = cast<FunctionType>(Val: T);
3496 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: FuncType->getReturnType());
3497 if (const auto *FPT = dyn_cast<FunctionProtoType>(Val: FuncType)) {
3498 for (QualType Param : FPT->param_types()) {
3499 Param = Ctx.getSignatureParameterType(T: Param);
3500 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: Param);
3501 }
3502 if (FPT->isVariadic())
3503 OS << "z";
3504 }
3505 OS << "E";
3506 return;
3507 }
3508
3509 case Type::MemberPointer: {
3510 OS << "M";
3511 const auto *MPT = T->castAs<MemberPointerType>();
3512 encodeTypeForFunctionPointerAuth(
3513 Ctx, OS, QT: QualType(MPT->getQualifier().getAsType(), 0));
3514 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: MPT->getPointeeType());
3515 return;
3516 }
3517 case Type::ExtVector:
3518 case Type::Vector:
3519 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3520 break;
3521
3522 // Don't bother discriminating based on these types.
3523 case Type::Pipe:
3524 case Type::BitInt:
3525 case Type::ConstantMatrix:
3526 OS << "?";
3527 return;
3528
3529 case Type::Builtin: {
3530 const auto *BTy = T->castAs<BuiltinType>();
3531 switch (BTy->getKind()) {
3532#define SIGNED_TYPE(Id, SingletonId) \
3533 case BuiltinType::Id: \
3534 OS << "i"; \
3535 return;
3536#define UNSIGNED_TYPE(Id, SingletonId) \
3537 case BuiltinType::Id: \
3538 OS << "i"; \
3539 return;
3540#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3541#define BUILTIN_TYPE(Id, SingletonId)
3542#include "clang/AST/BuiltinTypes.def"
3543 llvm_unreachable("placeholder types should not appear here.");
3544
3545 case BuiltinType::Half:
3546 OS << "Dh";
3547 return;
3548 case BuiltinType::Float:
3549 OS << "f";
3550 return;
3551 case BuiltinType::Double:
3552 OS << "d";
3553 return;
3554 case BuiltinType::LongDouble:
3555 OS << "e";
3556 return;
3557 case BuiltinType::Float16:
3558 OS << "DF16_";
3559 return;
3560 case BuiltinType::Float128:
3561 OS << "g";
3562 return;
3563
3564 case BuiltinType::Void:
3565 OS << "v";
3566 return;
3567
3568 case BuiltinType::ObjCId:
3569 case BuiltinType::ObjCClass:
3570 case BuiltinType::ObjCSel:
3571 case BuiltinType::NullPtr:
3572 OS << "P";
3573 return;
3574
3575 // Don't bother discriminating based on OpenCL types.
3576 case BuiltinType::OCLSampler:
3577 case BuiltinType::OCLEvent:
3578 case BuiltinType::OCLClkEvent:
3579 case BuiltinType::OCLQueue:
3580 case BuiltinType::OCLReserveID:
3581 case BuiltinType::BFloat16:
3582 case BuiltinType::VectorQuad:
3583 case BuiltinType::VectorPair:
3584 case BuiltinType::DMR1024:
3585 case BuiltinType::DMR2048:
3586 OS << "?";
3587 return;
3588
3589 // Don't bother discriminating based on these seldom-used types.
3590 case BuiltinType::Ibm128:
3591 return;
3592#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3593 case BuiltinType::Id: \
3594 return;
3595#include "clang/Basic/OpenCLImageTypes.def"
3596#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3597 case BuiltinType::Id: \
3598 return;
3599#include "clang/Basic/OpenCLExtensionTypes.def"
3600#define SVE_TYPE(Name, Id, SingletonId) \
3601 case BuiltinType::Id: \
3602 return;
3603#include "clang/Basic/AArch64ACLETypes.def"
3604#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3605 case BuiltinType::Id: \
3606 return;
3607#include "clang/Basic/HLSLIntangibleTypes.def"
3608 case BuiltinType::Dependent:
3609 llvm_unreachable("should never get here");
3610#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3611#include "clang/Basic/AMDGPUTypes.def"
3612 case BuiltinType::WasmExternRef:
3613#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3614#include "clang/Basic/RISCVVTypes.def"
3615#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3616#include "clang/Basic/SPIRVTypes.def"
3617 llvm_unreachable("not yet implemented");
3618 }
3619 llvm_unreachable("should never get here");
3620 }
3621 case Type::Record: {
3622 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3623 const IdentifierInfo *II = RD->getIdentifier();
3624
3625 // In C++, an immediate typedef of an anonymous struct or union
3626 // is considered to name it for ODR purposes, but C's specification
3627 // of type compatibility does not have a similar rule. Using the typedef
3628 // name in function type discriminators anyway, as we do here,
3629 // therefore technically violates the C standard: two function pointer
3630 // types defined in terms of two typedef'd anonymous structs with
3631 // different names are formally still compatible, but we are assigning
3632 // them different discriminators and therefore incompatible ABIs.
3633 //
3634 // This is a relatively minor violation that significantly improves
3635 // discrimination in some cases and has not caused problems in
3636 // practice. Regardless, it is now part of the ABI in places where
3637 // function type discrimination is used, and it can no longer be
3638 // changed except on new platforms.
3639
3640 if (!II)
3641 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3642 II = Typedef->getDeclName().getAsIdentifierInfo();
3643
3644 if (!II) {
3645 OS << "<anonymous_record>";
3646 return;
3647 }
3648 OS << II->getLength() << II->getName();
3649 return;
3650 }
3651 case Type::HLSLAttributedResource:
3652 case Type::HLSLInlineSpirv:
3653 llvm_unreachable("should never get here");
3654 break;
3655 case Type::OverflowBehavior:
3656 llvm_unreachable("should never get here");
3657 break;
3658 case Type::DeducedTemplateSpecialization:
3659 case Type::Auto:
3660#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3661#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3662#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3663#define ABSTRACT_TYPE(Class, Base)
3664#define TYPE(Class, Base)
3665#include "clang/AST/TypeNodes.inc"
3666 llvm_unreachable("unexpected non-canonical or dependent type!");
3667 return;
3668 }
3669}
3670
3671uint16_t ASTContext::getPointerAuthTypeDiscriminator(QualType T) {
3672 assert(!T->isDependentType() &&
3673 "cannot compute type discriminator of a dependent type");
3674 SmallString<256> Str;
3675 llvm::raw_svector_ostream Out(Str);
3676
3677 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3678 T = T->getPointeeType();
3679
3680 if (T->isFunctionType()) {
3681 encodeTypeForFunctionPointerAuth(Ctx: *this, OS&: Out, QT: T);
3682 } else {
3683 T = T.getUnqualifiedType();
3684 // Calls to member function pointers don't need to worry about
3685 // language interop or the laxness of the C type compatibility rules.
3686 // We just mangle the member pointer type directly, which is
3687 // implicitly much stricter about type matching. However, we do
3688 // strip any top-level exception specification before this mangling.
3689 // C++23 requires calls to work when the function type is convertible
3690 // to the pointer type by a function pointer conversion, which can
3691 // change the exception specification. This does not technically
3692 // require the exception specification to not affect representation,
3693 // because the function pointer conversion is still always a direct
3694 // value conversion and therefore an opportunity to resign the
3695 // pointer. (This is in contrast to e.g. qualification conversions,
3696 // which can be applied in nested pointer positions, effectively
3697 // requiring qualified and unqualified representations to match.)
3698 // However, it is pragmatic to ignore exception specifications
3699 // because it allows a certain amount of `noexcept` mismatching
3700 // to not become a visible ODR problem. This also leaves some
3701 // room for the committee to add laxness to function pointer
3702 // conversions in future standards.
3703 if (auto *MPT = T->getAs<MemberPointerType>())
3704 if (MPT->isMemberFunctionPointer()) {
3705 QualType PointeeType = MPT->getPointeeType();
3706 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3707 EST_None) {
3708 QualType FT = getFunctionTypeWithExceptionSpec(Orig: PointeeType, ESI: EST_None);
3709 T = getMemberPointerType(T: FT, Qualifier: MPT->getQualifier(),
3710 Cls: MPT->getMostRecentCXXRecordDecl());
3711 }
3712 }
3713 std::unique_ptr<MangleContext> MC(createMangleContext());
3714 MC->mangleCanonicalTypeName(T, Out);
3715 }
3716
3717 return llvm::getPointerAuthStableSipHash(S: Str);
3718}
3719
3720QualType ASTContext::getObjCGCQualType(QualType T,
3721 Qualifiers::GC GCAttr) const {
3722 QualType CanT = getCanonicalType(T);
3723 if (CanT.getObjCGCAttr() == GCAttr)
3724 return T;
3725
3726 if (const auto *ptr = T->getAs<PointerType>()) {
3727 QualType Pointee = ptr->getPointeeType();
3728 if (Pointee->isAnyPointerType()) {
3729 QualType ResultType = getObjCGCQualType(T: Pointee, GCAttr);
3730 return getPointerType(T: ResultType);
3731 }
3732 }
3733
3734 // If we are composing extended qualifiers together, merge together
3735 // into one ExtQuals node.
3736 QualifierCollector Quals;
3737 const Type *TypeNode = Quals.strip(type: T);
3738
3739 // If this type already has an ObjCGC specified, it cannot get
3740 // another one.
3741 assert(!Quals.hasObjCGCAttr() &&
3742 "Type cannot have multiple ObjCGCs!");
3743 Quals.addObjCGCAttr(type: GCAttr);
3744
3745 return getExtQualType(baseType: TypeNode, quals: Quals);
3746}
3747
3748QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3749 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3750 QualType Pointee = Ptr->getPointeeType();
3751 if (isPtrSizeAddressSpace(AS: Pointee.getAddressSpace())) {
3752 return getPointerType(T: removeAddrSpaceQualType(T: Pointee));
3753 }
3754 }
3755 return T;
3756}
3757
3758QualType ASTContext::getCountAttributedType(
3759 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3760 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3761 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3762
3763 llvm::FoldingSetNodeID ID;
3764 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, Nullable: OrNull);
3765
3766 void *InsertPos = nullptr;
3767 CountAttributedType *CATy =
3768 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3769 if (CATy)
3770 return QualType(CATy, 0);
3771
3772 QualType CanonTy = getCanonicalType(T: WrappedTy);
3773 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3774 Counts: DependentDecls.size());
3775 CATy = (CountAttributedType *)Allocate(Size, Align: TypeAlignment);
3776 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3777 OrNull, DependentDecls);
3778 Types.push_back(Elt: CATy);
3779 CountAttributedTypes.InsertNode(N: CATy, InsertPos);
3780
3781 return QualType(CATy, 0);
3782}
3783
3784QualType ASTContext::getLateParsedAttrType(
3785 QualType WrappedTy, LateParsedTypeAttribute *LateParsedAttr) const {
3786 QualType CanonTy = getCanonicalType(T: WrappedTy);
3787
3788 auto *LPATy = new (*this, alignof(LateParsedAttrType))
3789 LateParsedAttrType(WrappedTy, CanonTy, LateParsedAttr);
3790
3791 Types.push_back(Elt: LPATy);
3792 return QualType(LPATy, 0);
3793}
3794
3795QualType
3796ASTContext::adjustType(QualType Orig,
3797 llvm::function_ref<QualType(QualType)> Adjust) const {
3798 switch (Orig->getTypeClass()) {
3799 case Type::Attributed: {
3800 const auto *AT = cast<AttributedType>(Val&: Orig);
3801 return getAttributedType(attrKind: AT->getAttrKind(),
3802 modifiedType: adjustType(Orig: AT->getModifiedType(), Adjust),
3803 equivalentType: adjustType(Orig: AT->getEquivalentType(), Adjust),
3804 attr: AT->getAttr());
3805 }
3806
3807 case Type::BTFTagAttributed: {
3808 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Val&: Orig);
3809 return getBTFTagAttributedType(BTFAttr: BTFT->getAttr(),
3810 Wrapped: adjustType(Orig: BTFT->getWrappedType(), Adjust));
3811 }
3812
3813 case Type::OverflowBehavior: {
3814 const auto *OB = dyn_cast<OverflowBehaviorType>(Val&: Orig);
3815 return getOverflowBehaviorType(Kind: OB->getBehaviorKind(),
3816 Wrapped: adjustType(Orig: OB->getUnderlyingType(), Adjust));
3817 }
3818
3819 case Type::Paren:
3820 return getParenType(
3821 NamedType: adjustType(Orig: cast<ParenType>(Val&: Orig)->getInnerType(), Adjust));
3822
3823 case Type::Adjusted: {
3824 const auto *AT = cast<AdjustedType>(Val&: Orig);
3825 return getAdjustedType(Orig: AT->getOriginalType(),
3826 New: adjustType(Orig: AT->getAdjustedType(), Adjust));
3827 }
3828
3829 case Type::MacroQualified: {
3830 const auto *MQT = cast<MacroQualifiedType>(Val&: Orig);
3831 return getMacroQualifiedType(UnderlyingTy: adjustType(Orig: MQT->getUnderlyingType(), Adjust),
3832 MacroII: MQT->getMacroIdentifier());
3833 }
3834
3835 default:
3836 return Adjust(Orig);
3837 }
3838}
3839
3840const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3841 FunctionType::ExtInfo Info) {
3842 if (T->getExtInfo() == Info)
3843 return T;
3844
3845 QualType Result;
3846 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(Val: T)) {
3847 Result = getFunctionNoProtoType(ResultTy: FNPT->getReturnType(), Info);
3848 } else {
3849 const auto *FPT = cast<FunctionProtoType>(Val: T);
3850 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3851 EPI.ExtInfo = Info;
3852 Result = getFunctionType(ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(), EPI);
3853 }
3854
3855 return cast<FunctionType>(Val: Result.getTypePtr());
3856}
3857
3858QualType ASTContext::adjustFunctionResultType(QualType FunctionType,
3859 QualType ResultType) {
3860 return adjustType(Orig: FunctionType, Adjust: [&](QualType Orig) {
3861 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3862 return getFunctionNoProtoType(ResultTy: ResultType, Info: FNPT->getExtInfo());
3863
3864 const auto *FPT = Orig->castAs<FunctionProtoType>();
3865 return getFunctionType(ResultTy: ResultType, Args: FPT->getParamTypes(),
3866 EPI: FPT->getExtProtoInfo());
3867 });
3868}
3869
3870void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3871 QualType ResultType) {
3872 FD = FD->getMostRecentDecl();
3873 while (true) {
3874 FD->setType(adjustFunctionResultType(FunctionType: FD->getType(), ResultType));
3875 if (FunctionDecl *Next = FD->getPreviousDecl())
3876 FD = Next;
3877 else
3878 break;
3879 }
3880 if (ASTMutationListener *L = getASTMutationListener())
3881 L->DeducedReturnType(FD, ReturnType: ResultType);
3882}
3883
3884/// Get a function type and produce the equivalent function type with the
3885/// specified exception specification. Type sugar that can be present on a
3886/// declaration of a function with an exception specification is permitted
3887/// and preserved. Other type sugar (for instance, typedefs) is not.
3888QualType ASTContext::getFunctionTypeWithExceptionSpec(
3889 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3890 return adjustType(Orig, Adjust: [&](QualType Ty) {
3891 const auto *Proto = Ty->castAs<FunctionProtoType>();
3892 return getFunctionType(ResultTy: Proto->getReturnType(), Args: Proto->getParamTypes(),
3893 EPI: Proto->getExtProtoInfo().withExceptionSpec(ESI));
3894 });
3895}
3896
3897bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3898 QualType U) const {
3899 return hasSameType(T1: T, T2: U) ||
3900 (getLangOpts().CPlusPlus17 &&
3901 hasSameType(T1: getFunctionTypeWithExceptionSpec(Orig: T, ESI: EST_None),
3902 T2: getFunctionTypeWithExceptionSpec(Orig: U, ESI: EST_None)));
3903}
3904
3905QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3906 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3907 QualType RetTy = removePtrSizeAddrSpace(T: Proto->getReturnType());
3908 SmallVector<QualType, 16> Args(Proto->param_types().size());
3909 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3910 Args[i] = removePtrSizeAddrSpace(T: Proto->param_types()[i]);
3911 return getFunctionType(ResultTy: RetTy, Args, EPI: Proto->getExtProtoInfo());
3912 }
3913
3914 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3915 QualType RetTy = removePtrSizeAddrSpace(T: Proto->getReturnType());
3916 return getFunctionNoProtoType(ResultTy: RetTy, Info: Proto->getExtInfo());
3917 }
3918
3919 return T;
3920}
3921
3922bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3923 return hasSameType(T1: T, T2: U) ||
3924 hasSameType(T1: getFunctionTypeWithoutPtrSizes(T),
3925 T2: getFunctionTypeWithoutPtrSizes(T: U));
3926}
3927
3928QualType ASTContext::getFunctionTypeWithoutParamABIs(QualType T) const {
3929 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3930 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3931 EPI.ExtParameterInfos = nullptr;
3932 return getFunctionType(ResultTy: Proto->getReturnType(), Args: Proto->param_types(), EPI);
3933 }
3934 return T;
3935}
3936
3937bool ASTContext::hasSameFunctionTypeIgnoringParamABI(QualType T,
3938 QualType U) const {
3939 return hasSameType(T1: T, T2: U) || hasSameType(T1: getFunctionTypeWithoutParamABIs(T),
3940 T2: getFunctionTypeWithoutParamABIs(T: U));
3941}
3942
3943void ASTContext::adjustExceptionSpec(
3944 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3945 bool AsWritten) {
3946 // Update the type.
3947 QualType Updated =
3948 getFunctionTypeWithExceptionSpec(Orig: FD->getType(), ESI);
3949 FD->setType(Updated);
3950
3951 if (!AsWritten)
3952 return;
3953
3954 // Update the type in the type source information too.
3955 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3956 // If the type and the type-as-written differ, we may need to update
3957 // the type-as-written too.
3958 if (TSInfo->getType() != FD->getType())
3959 Updated = getFunctionTypeWithExceptionSpec(Orig: TSInfo->getType(), ESI);
3960
3961 // FIXME: When we get proper type location information for exceptions,
3962 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3963 // up the TypeSourceInfo;
3964 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3965 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3966 "TypeLoc size mismatch from updating exception specification");
3967 TSInfo->overrideType(T: Updated);
3968 }
3969}
3970
3971/// getComplexType - Return the uniqued reference to the type for a complex
3972/// number with the specified element type.
3973QualType ASTContext::getComplexType(QualType T) const {
3974 // Unique pointers, to guarantee there is only one pointer of a particular
3975 // structure.
3976 llvm::FoldingSetNodeID ID;
3977 ComplexType::Profile(ID, Element: T);
3978
3979 void *InsertPos = nullptr;
3980 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3981 return QualType(CT, 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 = getComplexType(T: getCanonicalType(T));
3988
3989 // Get the new insert position for the node we care about.
3990 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3991 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3992 }
3993 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3994 Types.push_back(Elt: New);
3995 ComplexTypes.InsertNode(N: New, InsertPos);
3996 return QualType(New, 0);
3997}
3998
3999/// getPointerType - Return the uniqued reference to the type for a pointer to
4000/// the specified type.
4001QualType ASTContext::getPointerType(QualType T) const {
4002 // Unique pointers, to guarantee there is only one pointer of a particular
4003 // structure.
4004 llvm::FoldingSetNodeID ID;
4005 PointerType::Profile(ID, Pointee: T);
4006
4007 void *InsertPos = nullptr;
4008 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4009 return QualType(PT, 0);
4010
4011 // If the pointee type isn't canonical, this won't be a canonical type either,
4012 // so fill in the canonical type field.
4013 QualType Canonical;
4014 if (!T.isCanonical()) {
4015 Canonical = getPointerType(T: getCanonicalType(T));
4016
4017 // Get the new insert position for the node we care about.
4018 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4019 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4020 }
4021 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
4022 Types.push_back(Elt: New);
4023 PointerTypes.InsertNode(N: New, InsertPos);
4024 return QualType(New, 0);
4025}
4026
4027QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
4028 llvm::FoldingSetNodeID ID;
4029 AdjustedType::Profile(ID, Orig, New);
4030 void *InsertPos = nullptr;
4031 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4032 if (AT)
4033 return QualType(AT, 0);
4034
4035 QualType Canonical = getCanonicalType(T: New);
4036
4037 // Get the new insert position for the node we care about.
4038 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4039 assert(!AT && "Shouldn't be in the map!");
4040
4041 AT = new (*this, alignof(AdjustedType))
4042 AdjustedType(Type::Adjusted, Orig, New, Canonical);
4043 Types.push_back(Elt: AT);
4044 AdjustedTypes.InsertNode(N: AT, InsertPos);
4045 return QualType(AT, 0);
4046}
4047
4048QualType ASTContext::getDecayedType(QualType Orig, QualType Decayed) const {
4049 llvm::FoldingSetNodeID ID;
4050 AdjustedType::Profile(ID, Orig, New: Decayed);
4051 void *InsertPos = nullptr;
4052 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4053 if (AT)
4054 return QualType(AT, 0);
4055
4056 QualType Canonical = getCanonicalType(T: Decayed);
4057
4058 // Get the new insert position for the node we care about.
4059 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4060 assert(!AT && "Shouldn't be in the map!");
4061
4062 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
4063 Types.push_back(Elt: AT);
4064 AdjustedTypes.InsertNode(N: AT, InsertPos);
4065 return QualType(AT, 0);
4066}
4067
4068QualType ASTContext::getDecayedType(QualType T) const {
4069 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
4070
4071 QualType Decayed;
4072
4073 // C99 6.7.5.3p7:
4074 // A declaration of a parameter as "array of type" shall be
4075 // adjusted to "qualified pointer to type", where the type
4076 // qualifiers (if any) are those specified within the [ and ] of
4077 // the array type derivation.
4078 if (T->isArrayType())
4079 Decayed = getArrayDecayedType(T);
4080
4081 // C99 6.7.5.3p8:
4082 // A declaration of a parameter as "function returning type"
4083 // shall be adjusted to "pointer to function returning type", as
4084 // in 6.3.2.1.
4085 if (T->isFunctionType())
4086 Decayed = getPointerType(T);
4087
4088 return getDecayedType(Orig: T, Decayed);
4089}
4090
4091QualType ASTContext::getArrayParameterType(QualType Ty) const {
4092 if (Ty->isArrayParameterType())
4093 return Ty;
4094 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4095 QualType DTy = Ty.getDesugaredType(Context: *this);
4096 const auto *ATy = cast<ConstantArrayType>(Val&: DTy);
4097 llvm::FoldingSetNodeID ID;
4098 ATy->Profile(ID, Ctx: *this, ET: ATy->getElementType(), ArraySize: ATy->getZExtSize(),
4099 SizeExpr: ATy->getSizeExpr(), SizeMod: ATy->getSizeModifier(),
4100 TypeQuals: ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4101 void *InsertPos = nullptr;
4102 ArrayParameterType *AT =
4103 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4104 if (AT)
4105 return QualType(AT, 0);
4106
4107 QualType Canonical;
4108 if (!DTy.isCanonical()) {
4109 Canonical = getArrayParameterType(Ty: getCanonicalType(T: Ty));
4110
4111 // Get the new insert position for the node we care about.
4112 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4113 assert(!AT && "Shouldn't be in the map!");
4114 }
4115
4116 AT = new (*this, alignof(ArrayParameterType))
4117 ArrayParameterType(ATy, Canonical);
4118 Types.push_back(Elt: AT);
4119 ArrayParameterTypes.InsertNode(N: AT, InsertPos);
4120 return QualType(AT, 0);
4121}
4122
4123/// getBlockPointerType - Return the uniqued reference to the type for
4124/// a pointer to the specified block.
4125QualType ASTContext::getBlockPointerType(QualType T) const {
4126 assert(T->isFunctionType() && "block of function types only");
4127 // Unique pointers, to guarantee there is only one block of a particular
4128 // structure.
4129 llvm::FoldingSetNodeID ID;
4130 BlockPointerType::Profile(ID, Pointee: T);
4131
4132 void *InsertPos = nullptr;
4133 if (BlockPointerType *PT =
4134 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4135 return QualType(PT, 0);
4136
4137 // If the block pointee type isn't canonical, this won't be a canonical
4138 // type either so fill in the canonical type field.
4139 QualType Canonical;
4140 if (!T.isCanonical()) {
4141 Canonical = getBlockPointerType(T: getCanonicalType(T));
4142
4143 // Get the new insert position for the node we care about.
4144 BlockPointerType *NewIP =
4145 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4146 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4147 }
4148 auto *New =
4149 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4150 Types.push_back(Elt: New);
4151 BlockPointerTypes.InsertNode(N: New, InsertPos);
4152 return QualType(New, 0);
4153}
4154
4155/// getLValueReferenceType - Return the uniqued reference to the type for an
4156/// lvalue reference to the specified type.
4157QualType
4158ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4159 assert((!T->isPlaceholderType() ||
4160 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4161 "Unresolved placeholder type");
4162
4163 // Unique pointers, to guarantee there is only one pointer of a particular
4164 // structure.
4165 llvm::FoldingSetNodeID ID;
4166 ReferenceType::Profile(ID, Referencee: T, SpelledAsLValue);
4167
4168 void *InsertPos = nullptr;
4169 if (LValueReferenceType *RT =
4170 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4171 return QualType(RT, 0);
4172
4173 const auto *InnerRef = T->getAs<ReferenceType>();
4174
4175 // If the referencee type isn't canonical, this won't be a canonical type
4176 // either, so fill in the canonical type field.
4177 QualType Canonical;
4178 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4179 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4180 Canonical = getLValueReferenceType(T: getCanonicalType(T: PointeeType));
4181
4182 // Get the new insert position for the node we care about.
4183 LValueReferenceType *NewIP =
4184 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4185 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4186 }
4187
4188 auto *New = new (*this, alignof(LValueReferenceType))
4189 LValueReferenceType(T, Canonical, SpelledAsLValue);
4190 Types.push_back(Elt: New);
4191 LValueReferenceTypes.InsertNode(N: New, InsertPos);
4192
4193 return QualType(New, 0);
4194}
4195
4196/// getRValueReferenceType - Return the uniqued reference to the type for an
4197/// rvalue reference to the specified type.
4198QualType ASTContext::getRValueReferenceType(QualType T) const {
4199 assert((!T->isPlaceholderType() ||
4200 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4201 "Unresolved placeholder type");
4202
4203 // Unique pointers, to guarantee there is only one pointer of a particular
4204 // structure.
4205 llvm::FoldingSetNodeID ID;
4206 ReferenceType::Profile(ID, Referencee: T, SpelledAsLValue: false);
4207
4208 void *InsertPos = nullptr;
4209 if (RValueReferenceType *RT =
4210 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4211 return QualType(RT, 0);
4212
4213 const auto *InnerRef = T->getAs<ReferenceType>();
4214
4215 // If the referencee type isn't canonical, this won't be a canonical type
4216 // either, so fill in the canonical type field.
4217 QualType Canonical;
4218 if (InnerRef || !T.isCanonical()) {
4219 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4220 Canonical = getRValueReferenceType(T: getCanonicalType(T: PointeeType));
4221
4222 // Get the new insert position for the node we care about.
4223 RValueReferenceType *NewIP =
4224 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4225 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4226 }
4227
4228 auto *New = new (*this, alignof(RValueReferenceType))
4229 RValueReferenceType(T, Canonical);
4230 Types.push_back(Elt: New);
4231 RValueReferenceTypes.InsertNode(N: New, InsertPos);
4232 return QualType(New, 0);
4233}
4234
4235QualType ASTContext::getMemberPointerType(QualType T,
4236 NestedNameSpecifier Qualifier,
4237 const CXXRecordDecl *Cls) const {
4238 if (!Qualifier) {
4239 assert(Cls && "At least one of Qualifier or Cls must be provided");
4240 Qualifier = NestedNameSpecifier(getCanonicalTagType(TD: Cls).getTypePtr());
4241 } else if (!Cls) {
4242 Cls = Qualifier.getAsRecordDecl();
4243 }
4244 // Unique pointers, to guarantee there is only one pointer of a particular
4245 // structure.
4246 llvm::FoldingSetNodeID ID;
4247 MemberPointerType::Profile(ID, Pointee: T, Qualifier, Cls);
4248
4249 void *InsertPos = nullptr;
4250 if (MemberPointerType *PT =
4251 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4252 return QualType(PT, 0);
4253
4254 NestedNameSpecifier CanonicalQualifier = [&] {
4255 if (!Cls)
4256 return Qualifier.getCanonical();
4257 NestedNameSpecifier R(getCanonicalTagType(TD: Cls).getTypePtr());
4258 assert(R.isCanonical());
4259 return R;
4260 }();
4261 // If the pointee or class type isn't canonical, this won't be a canonical
4262 // type either, so fill in the canonical type field.
4263 QualType Canonical;
4264 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4265 Canonical =
4266 getMemberPointerType(T: getCanonicalType(T), Qualifier: CanonicalQualifier, Cls);
4267 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4268 // Get the new insert position for the node we care about.
4269 [[maybe_unused]] MemberPointerType *NewIP =
4270 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4271 assert(!NewIP && "Shouldn't be in the map!");
4272 }
4273 auto *New = new (*this, alignof(MemberPointerType))
4274 MemberPointerType(T, Qualifier, Canonical);
4275 Types.push_back(Elt: New);
4276 MemberPointerTypes.InsertNode(N: New, InsertPos);
4277 return QualType(New, 0);
4278}
4279
4280/// getConstantArrayType - Return the unique reference to the type for an
4281/// array of the specified element type.
4282QualType ASTContext::getConstantArrayType(QualType EltTy,
4283 const llvm::APInt &ArySizeIn,
4284 const Expr *SizeExpr,
4285 ArraySizeModifier ASM,
4286 unsigned IndexTypeQuals) const {
4287 assert((EltTy->isDependentType() ||
4288 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4289 "Constant array of VLAs is illegal!");
4290
4291 // We only need the size as part of the type if it's instantiation-dependent.
4292 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4293 SizeExpr = nullptr;
4294
4295 // Convert the array size into a canonical width matching the pointer size for
4296 // the target.
4297 llvm::APInt ArySize(ArySizeIn);
4298 ArySize = ArySize.zextOrTrunc(width: Target->getMaxPointerWidth());
4299
4300 llvm::FoldingSetNodeID ID;
4301 ConstantArrayType::Profile(ID, Ctx: *this, ET: EltTy, ArraySize: ArySize.getZExtValue(), SizeExpr,
4302 SizeMod: ASM, TypeQuals: IndexTypeQuals);
4303
4304 void *InsertPos = nullptr;
4305 if (ConstantArrayType *ATP =
4306 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4307 return QualType(ATP, 0);
4308
4309 // If the element type isn't canonical or has qualifiers, or the array bound
4310 // is instantiation-dependent, this won't be a canonical type either, so fill
4311 // in the canonical type field.
4312 QualType Canon;
4313 // FIXME: Check below should look for qualifiers behind sugar.
4314 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4315 SplitQualType canonSplit = getCanonicalType(T: EltTy).split();
4316 Canon = getConstantArrayType(EltTy: QualType(canonSplit.Ty, 0), ArySizeIn: ArySize, SizeExpr: nullptr,
4317 ASM, IndexTypeQuals);
4318 Canon = getQualifiedType(T: Canon, Qs: canonSplit.Quals);
4319
4320 // Get the new insert position for the node we care about.
4321 ConstantArrayType *NewIP =
4322 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4323 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4324 }
4325
4326 auto *New = ConstantArrayType::Create(Ctx: *this, ET: EltTy, Can: Canon, Sz: ArySize, SzExpr: SizeExpr,
4327 SzMod: ASM, Qual: IndexTypeQuals);
4328 ConstantArrayTypes.InsertNode(N: New, InsertPos);
4329 Types.push_back(Elt: New);
4330 return QualType(New, 0);
4331}
4332
4333/// getVariableArrayDecayedType - Turns the given type, which may be
4334/// variably-modified, into the corresponding type with all the known
4335/// sizes replaced with [*].
4336QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
4337 // Vastly most common case.
4338 if (!type->isVariablyModifiedType()) return type;
4339
4340 QualType result;
4341
4342 SplitQualType split = type.getSplitDesugaredType();
4343 const Type *ty = split.Ty;
4344 switch (ty->getTypeClass()) {
4345#define TYPE(Class, Base)
4346#define ABSTRACT_TYPE(Class, Base)
4347#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4348#include "clang/AST/TypeNodes.inc"
4349 llvm_unreachable("didn't desugar past all non-canonical types?");
4350
4351 // These types should never be variably-modified.
4352 case Type::Builtin:
4353 case Type::Complex:
4354 case Type::Vector:
4355 case Type::DependentVector:
4356 case Type::ExtVector:
4357 case Type::DependentSizedExtVector:
4358 case Type::ConstantMatrix:
4359 case Type::DependentSizedMatrix:
4360 case Type::DependentAddressSpace:
4361 case Type::ObjCObject:
4362 case Type::ObjCInterface:
4363 case Type::ObjCObjectPointer:
4364 case Type::Record:
4365 case Type::Enum:
4366 case Type::UnresolvedUsing:
4367 case Type::TypeOfExpr:
4368 case Type::TypeOf:
4369 case Type::Decltype:
4370 case Type::UnaryTransform:
4371 case Type::DependentName:
4372 case Type::InjectedClassName:
4373 case Type::TemplateSpecialization:
4374 case Type::TemplateTypeParm:
4375 case Type::SubstTemplateTypeParmPack:
4376 case Type::SubstBuiltinTemplatePack:
4377 case Type::Auto:
4378 case Type::DeducedTemplateSpecialization:
4379 case Type::PackExpansion:
4380 case Type::PackIndexing:
4381 case Type::BitInt:
4382 case Type::DependentBitInt:
4383 case Type::ArrayParameter:
4384 case Type::HLSLAttributedResource:
4385 case Type::HLSLInlineSpirv:
4386 case Type::OverflowBehavior:
4387 llvm_unreachable("type should never be variably-modified");
4388
4389 // These types can be variably-modified but should never need to
4390 // further decay.
4391 case Type::FunctionNoProto:
4392 case Type::FunctionProto:
4393 case Type::BlockPointer:
4394 case Type::MemberPointer:
4395 case Type::Pipe:
4396 return type;
4397
4398 // These types can be variably-modified. All these modifications
4399 // preserve structure except as noted by comments.
4400 // TODO: if we ever care about optimizing VLAs, there are no-op
4401 // optimizations available here.
4402 case Type::Pointer:
4403 result = getPointerType(T: getVariableArrayDecayedType(
4404 type: cast<PointerType>(Val: ty)->getPointeeType()));
4405 break;
4406
4407 case Type::LValueReference: {
4408 const auto *lv = cast<LValueReferenceType>(Val: ty);
4409 result = getLValueReferenceType(
4410 T: getVariableArrayDecayedType(type: lv->getPointeeType()),
4411 SpelledAsLValue: lv->isSpelledAsLValue());
4412 break;
4413 }
4414
4415 case Type::RValueReference: {
4416 const auto *lv = cast<RValueReferenceType>(Val: ty);
4417 result = getRValueReferenceType(
4418 T: getVariableArrayDecayedType(type: lv->getPointeeType()));
4419 break;
4420 }
4421
4422 case Type::Atomic: {
4423 const auto *at = cast<AtomicType>(Val: ty);
4424 result = getAtomicType(T: getVariableArrayDecayedType(type: at->getValueType()));
4425 break;
4426 }
4427
4428 case Type::ConstantArray: {
4429 const auto *cat = cast<ConstantArrayType>(Val: ty);
4430 result = getConstantArrayType(
4431 EltTy: getVariableArrayDecayedType(type: cat->getElementType()),
4432 ArySizeIn: cat->getSize(),
4433 SizeExpr: cat->getSizeExpr(),
4434 ASM: cat->getSizeModifier(),
4435 IndexTypeQuals: cat->getIndexTypeCVRQualifiers());
4436 break;
4437 }
4438
4439 case Type::DependentSizedArray: {
4440 const auto *dat = cast<DependentSizedArrayType>(Val: ty);
4441 result = getDependentSizedArrayType(
4442 EltTy: getVariableArrayDecayedType(type: dat->getElementType()), NumElts: dat->getSizeExpr(),
4443 ASM: dat->getSizeModifier(), IndexTypeQuals: dat->getIndexTypeCVRQualifiers());
4444 break;
4445 }
4446
4447 // Turn incomplete types into [*] types.
4448 case Type::IncompleteArray: {
4449 const auto *iat = cast<IncompleteArrayType>(Val: ty);
4450 result =
4451 getVariableArrayType(EltTy: getVariableArrayDecayedType(type: iat->getElementType()),
4452 /*size*/ NumElts: nullptr, ASM: ArraySizeModifier::Normal,
4453 IndexTypeQuals: iat->getIndexTypeCVRQualifiers());
4454 break;
4455 }
4456
4457 // Turn VLA types into [*] types.
4458 case Type::VariableArray: {
4459 const auto *vat = cast<VariableArrayType>(Val: ty);
4460 result =
4461 getVariableArrayType(EltTy: getVariableArrayDecayedType(type: vat->getElementType()),
4462 /*size*/ NumElts: nullptr, ASM: ArraySizeModifier::Star,
4463 IndexTypeQuals: vat->getIndexTypeCVRQualifiers());
4464 break;
4465 }
4466 }
4467
4468 // Apply the top-level qualifiers from the original.
4469 return getQualifiedType(T: result, Qs: split.Quals);
4470}
4471
4472/// getVariableArrayType - Returns a non-unique reference to the type for a
4473/// variable array of the specified element type.
4474QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
4475 ArraySizeModifier ASM,
4476 unsigned IndexTypeQuals) const {
4477 // Since we don't unique expressions, it isn't possible to unique VLA's
4478 // that have an expression provided for their size.
4479 QualType Canon;
4480
4481 // Be sure to pull qualifiers off the element type.
4482 // FIXME: Check below should look for qualifiers behind sugar.
4483 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4484 SplitQualType canonSplit = getCanonicalType(T: EltTy).split();
4485 Canon = getVariableArrayType(EltTy: QualType(canonSplit.Ty, 0), NumElts, ASM,
4486 IndexTypeQuals);
4487 Canon = getQualifiedType(T: Canon, Qs: canonSplit.Quals);
4488 }
4489
4490 auto *New = new (*this, alignof(VariableArrayType))
4491 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4492
4493 VariableArrayTypes.push_back(x: New);
4494 Types.push_back(Elt: New);
4495 return QualType(New, 0);
4496}
4497
4498/// getDependentSizedArrayType - Returns a non-unique reference to
4499/// the type for a dependently-sized array of the specified element
4500/// type.
4501QualType
4502ASTContext::getDependentSizedArrayType(QualType elementType, Expr *numElements,
4503 ArraySizeModifier ASM,
4504 unsigned elementTypeQuals) const {
4505 assert((!numElements || numElements->isTypeDependent() ||
4506 numElements->isValueDependent()) &&
4507 "Size must be type- or value-dependent!");
4508
4509 SplitQualType canonElementType = getCanonicalType(T: elementType).split();
4510
4511 void *insertPos = nullptr;
4512 llvm::FoldingSetNodeID ID;
4513 DependentSizedArrayType::Profile(
4514 ID, Context: *this, ET: numElements ? QualType(canonElementType.Ty, 0) : elementType,
4515 SizeMod: ASM, TypeQuals: elementTypeQuals, E: numElements);
4516
4517 // Look for an existing type with these properties.
4518 DependentSizedArrayType *canonTy =
4519 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos&: insertPos);
4520
4521 // Dependently-sized array types that do not have a specified number
4522 // of elements will have their sizes deduced from a dependent
4523 // initializer.
4524 if (!numElements) {
4525 if (canonTy)
4526 return QualType(canonTy, 0);
4527
4528 auto *newType = new (*this, alignof(DependentSizedArrayType))
4529 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4530 elementTypeQuals);
4531 DependentSizedArrayTypes.InsertNode(N: newType, InsertPos: insertPos);
4532 Types.push_back(Elt: newType);
4533 return QualType(newType, 0);
4534 }
4535
4536 // If we don't have one, build one.
4537 if (!canonTy) {
4538 canonTy = new (*this, alignof(DependentSizedArrayType))
4539 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4540 numElements, ASM, elementTypeQuals);
4541 DependentSizedArrayTypes.InsertNode(N: canonTy, InsertPos: insertPos);
4542 Types.push_back(Elt: canonTy);
4543 }
4544
4545 // Apply qualifiers from the element type to the array.
4546 QualType canon = getQualifiedType(T: QualType(canonTy,0),
4547 Qs: canonElementType.Quals);
4548
4549 // If we didn't need extra canonicalization for the element type or the size
4550 // expression, then just use that as our result.
4551 if (QualType(canonElementType.Ty, 0) == elementType &&
4552 canonTy->getSizeExpr() == numElements)
4553 return canon;
4554
4555 // Otherwise, we need to build a type which follows the spelling
4556 // of the element type.
4557 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4558 DependentSizedArrayType(elementType, canon, numElements, ASM,
4559 elementTypeQuals);
4560 Types.push_back(Elt: sugaredType);
4561 return QualType(sugaredType, 0);
4562}
4563
4564QualType ASTContext::getIncompleteArrayType(QualType elementType,
4565 ArraySizeModifier ASM,
4566 unsigned elementTypeQuals) const {
4567 llvm::FoldingSetNodeID ID;
4568 IncompleteArrayType::Profile(ID, ET: elementType, SizeMod: ASM, TypeQuals: elementTypeQuals);
4569
4570 void *insertPos = nullptr;
4571 if (IncompleteArrayType *iat =
4572 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos&: insertPos))
4573 return QualType(iat, 0);
4574
4575 // If the element type isn't canonical, this won't be a canonical type
4576 // either, so fill in the canonical type field. We also have to pull
4577 // qualifiers off the element type.
4578 QualType canon;
4579
4580 // FIXME: Check below should look for qualifiers behind sugar.
4581 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4582 SplitQualType canonSplit = getCanonicalType(T: elementType).split();
4583 canon = getIncompleteArrayType(elementType: QualType(canonSplit.Ty, 0),
4584 ASM, elementTypeQuals);
4585 canon = getQualifiedType(T: canon, Qs: canonSplit.Quals);
4586
4587 // Get the new insert position for the node we care about.
4588 IncompleteArrayType *existing =
4589 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos&: insertPos);
4590 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4591 }
4592
4593 auto *newType = new (*this, alignof(IncompleteArrayType))
4594 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4595
4596 IncompleteArrayTypes.InsertNode(N: newType, InsertPos: insertPos);
4597 Types.push_back(Elt: newType);
4598 return QualType(newType, 0);
4599}
4600
4601ASTContext::BuiltinVectorTypeInfo
4602ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
4603#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4604 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4605 NUMVECTORS};
4606
4607#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4608 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4609
4610 switch (Ty->getKind()) {
4611 default:
4612 llvm_unreachable("Unsupported builtin vector type");
4613
4614#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4615 ElBits, NF, IsSigned) \
4616 case BuiltinType::Id: \
4617 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4618 llvm::ElementCount::getScalable(NumEls), NF};
4619#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4620 ElBits, NF) \
4621 case BuiltinType::Id: \
4622 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4623 llvm::ElementCount::getScalable(NumEls), NF};
4624#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4625 ElBits, NF) \
4626 case BuiltinType::Id: \
4627 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4628#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4629 ElBits, NF) \
4630 case BuiltinType::Id: \
4631 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4632#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4633 case BuiltinType::Id: \
4634 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4635#include "clang/Basic/AArch64ACLETypes.def"
4636
4637#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4638 IsSigned) \
4639 case BuiltinType::Id: \
4640 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4641 llvm::ElementCount::getScalable(NumEls), NF};
4642#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4643 case BuiltinType::Id: \
4644 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4645 llvm::ElementCount::getScalable(NumEls), NF};
4646#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4647 case BuiltinType::Id: \
4648 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4649#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4650 case BuiltinType::Id: \
4651 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4652#include "clang/Basic/RISCVVTypes.def"
4653 }
4654}
4655
4656/// getExternrefType - Return a WebAssembly externref type, which represents an
4657/// opaque reference to a host value.
4658QualType ASTContext::getWebAssemblyExternrefType() const {
4659 if (Target->getTriple().isWasm() && Target->hasFeature(Feature: "reference-types")) {
4660#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4661 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4662 return SingletonId;
4663#include "clang/Basic/WebAssemblyReferenceTypes.def"
4664 }
4665 llvm_unreachable(
4666 "shouldn't try to generate type externref outside WebAssembly target");
4667}
4668
4669/// getScalableVectorType - Return the unique reference to a scalable vector
4670/// type of the specified element type and size. VectorType must be a built-in
4671/// type.
4672QualType ASTContext::getScalableVectorType(QualType EltTy, unsigned NumElts,
4673 unsigned NumFields) const {
4674 auto K = llvm::ScalableVecTyKey{.EltTy: EltTy, .NumElts: NumElts, .NumFields: NumFields};
4675 if (auto It = ScalableVecTyMap.find(Val: K); It != ScalableVecTyMap.end())
4676 return It->second;
4677
4678 if (Target->hasAArch64ACLETypes()) {
4679 uint64_t EltTySize = getTypeSize(T: EltTy);
4680
4681#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4682 ElBits, NF, IsSigned) \
4683 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4684 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4685 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4686 return ScalableVecTyMap[K] = SingletonId; \
4687 }
4688#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4689 ElBits, NF) \
4690 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4691 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4692 return ScalableVecTyMap[K] = SingletonId; \
4693 }
4694#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4695 ElBits, NF) \
4696 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4697 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4698 return ScalableVecTyMap[K] = SingletonId; \
4699 }
4700#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4701 ElBits, NF) \
4702 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4703 NumElts == (NumEls * NF) && NumFields == 1) { \
4704 return ScalableVecTyMap[K] = SingletonId; \
4705 }
4706#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4707 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4708 return ScalableVecTyMap[K] = SingletonId;
4709#include "clang/Basic/AArch64ACLETypes.def"
4710 } else if (Target->hasRISCVVTypes()) {
4711 uint64_t EltTySize = getTypeSize(T: EltTy);
4712#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4713 IsFP, IsBF) \
4714 if (!EltTy->isBooleanType() && \
4715 ((EltTy->hasIntegerRepresentation() && \
4716 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4717 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4718 IsFP && !IsBF) || \
4719 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4720 IsBF && !IsFP)) && \
4721 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4722 return ScalableVecTyMap[K] = SingletonId;
4723#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4724 if (EltTy->isBooleanType() && NumElts == NumEls) \
4725 return ScalableVecTyMap[K] = SingletonId;
4726#include "clang/Basic/RISCVVTypes.def"
4727 }
4728 return QualType();
4729}
4730
4731/// getVectorType - Return the unique reference to a vector type of
4732/// the specified element type and size. VectorType must be a built-in type.
4733QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
4734 VectorKind VecKind) const {
4735 assert(vecType->isBuiltinType() ||
4736 (vecType->isBitIntType() &&
4737 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4738 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4739
4740 // Check if we've already instantiated a vector of this type.
4741 llvm::FoldingSetNodeID ID;
4742 VectorType::Profile(ID, ElementType: vecType, NumElements: NumElts, TypeClass: Type::Vector, VecKind);
4743
4744 void *InsertPos = nullptr;
4745 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4746 return QualType(VTP, 0);
4747
4748 // If the element type isn't canonical, this won't be a canonical type either,
4749 // so fill in the canonical type field.
4750 QualType Canonical;
4751 if (!vecType.isCanonical()) {
4752 Canonical = getVectorType(vecType: getCanonicalType(T: vecType), NumElts, VecKind);
4753
4754 // Get the new insert position for the node we care about.
4755 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4756 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4757 }
4758 auto *New = new (*this, alignof(VectorType))
4759 VectorType(vecType, NumElts, Canonical, VecKind);
4760 VectorTypes.InsertNode(N: New, InsertPos);
4761 Types.push_back(Elt: New);
4762 return QualType(New, 0);
4763}
4764
4765QualType ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
4766 SourceLocation AttrLoc,
4767 VectorKind VecKind) const {
4768 llvm::FoldingSetNodeID ID;
4769 DependentVectorType::Profile(ID, Context: *this, ElementType: getCanonicalType(T: VecType), SizeExpr,
4770 VecKind);
4771 void *InsertPos = nullptr;
4772 DependentVectorType *Canon =
4773 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4774 DependentVectorType *New;
4775
4776 if (Canon) {
4777 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4778 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4779 } else {
4780 QualType CanonVecTy = getCanonicalType(T: VecType);
4781 if (CanonVecTy == VecType) {
4782 New = new (*this, alignof(DependentVectorType))
4783 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4784
4785 DependentVectorType *CanonCheck =
4786 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4787 assert(!CanonCheck &&
4788 "Dependent-sized vector_size canonical type broken");
4789 (void)CanonCheck;
4790 DependentVectorTypes.InsertNode(N: New, InsertPos);
4791 } else {
4792 QualType CanonTy = getDependentVectorType(VecType: CanonVecTy, SizeExpr,
4793 AttrLoc: SourceLocation(), VecKind);
4794 New = new (*this, alignof(DependentVectorType))
4795 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4796 }
4797 }
4798
4799 Types.push_back(Elt: New);
4800 return QualType(New, 0);
4801}
4802
4803/// getExtVectorType - Return the unique reference to an extended vector type of
4804/// the specified element type and size. VectorType must be a built-in type.
4805QualType ASTContext::getExtVectorType(QualType vecType,
4806 unsigned NumElts) const {
4807 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4808 (vecType->isBitIntType() &&
4809 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4810 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4811
4812 // Check if we've already instantiated a vector of this type.
4813 llvm::FoldingSetNodeID ID;
4814 VectorType::Profile(ID, ElementType: vecType, NumElements: NumElts, TypeClass: Type::ExtVector,
4815 VecKind: VectorKind::Generic);
4816 void *InsertPos = nullptr;
4817 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4818 return QualType(VTP, 0);
4819
4820 // If the element type isn't canonical, this won't be a canonical type either,
4821 // so fill in the canonical type field.
4822 QualType Canonical;
4823 if (!vecType.isCanonical()) {
4824 Canonical = getExtVectorType(vecType: getCanonicalType(T: vecType), NumElts);
4825
4826 // Get the new insert position for the node we care about.
4827 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4828 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4829 }
4830 auto *New = new (*this, alignof(ExtVectorType))
4831 ExtVectorType(vecType, NumElts, Canonical);
4832 VectorTypes.InsertNode(N: New, InsertPos);
4833 Types.push_back(Elt: New);
4834 return QualType(New, 0);
4835}
4836
4837QualType
4838ASTContext::getDependentSizedExtVectorType(QualType vecType,
4839 Expr *SizeExpr,
4840 SourceLocation AttrLoc) const {
4841 llvm::FoldingSetNodeID ID;
4842 DependentSizedExtVectorType::Profile(ID, Context: *this, ElementType: getCanonicalType(T: vecType),
4843 SizeExpr);
4844
4845 void *InsertPos = nullptr;
4846 DependentSizedExtVectorType *Canon
4847 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4848 DependentSizedExtVectorType *New;
4849 if (Canon) {
4850 // We already have a canonical version of this array type; use it as
4851 // the canonical type for a newly-built type.
4852 New = new (*this, alignof(DependentSizedExtVectorType))
4853 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4854 AttrLoc);
4855 } else {
4856 QualType CanonVecTy = getCanonicalType(T: vecType);
4857 if (CanonVecTy == vecType) {
4858 New = new (*this, alignof(DependentSizedExtVectorType))
4859 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4860
4861 DependentSizedExtVectorType *CanonCheck
4862 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4863 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4864 (void)CanonCheck;
4865 DependentSizedExtVectorTypes.InsertNode(N: New, InsertPos);
4866 } else {
4867 QualType CanonExtTy = getDependentSizedExtVectorType(vecType: CanonVecTy, SizeExpr,
4868 AttrLoc: SourceLocation());
4869 New = new (*this, alignof(DependentSizedExtVectorType))
4870 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4871 }
4872 }
4873
4874 Types.push_back(Elt: New);
4875 return QualType(New, 0);
4876}
4877
4878QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
4879 unsigned NumColumns) const {
4880 llvm::FoldingSetNodeID ID;
4881 ConstantMatrixType::Profile(ID, ElementType: ElementTy, NumRows, NumColumns,
4882 TypeClass: Type::ConstantMatrix);
4883
4884 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4885 "need a valid element type");
4886 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4887 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4888 "need valid matrix dimensions");
4889 void *InsertPos = nullptr;
4890 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4891 return QualType(MTP, 0);
4892
4893 QualType Canonical;
4894 if (!ElementTy.isCanonical()) {
4895 Canonical =
4896 getConstantMatrixType(ElementTy: getCanonicalType(T: ElementTy), NumRows, NumColumns);
4897
4898 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4899 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4900 (void)NewIP;
4901 }
4902
4903 auto *New = new (*this, alignof(ConstantMatrixType))
4904 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4905 MatrixTypes.InsertNode(N: New, InsertPos);
4906 Types.push_back(Elt: New);
4907 return QualType(New, 0);
4908}
4909
4910QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4911 Expr *RowExpr,
4912 Expr *ColumnExpr,
4913 SourceLocation AttrLoc) const {
4914 QualType CanonElementTy = getCanonicalType(T: ElementTy);
4915 llvm::FoldingSetNodeID ID;
4916 DependentSizedMatrixType::Profile(ID, Context: *this, ElementType: CanonElementTy, RowExpr,
4917 ColumnExpr);
4918
4919 void *InsertPos = nullptr;
4920 DependentSizedMatrixType *Canon =
4921 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4922
4923 if (!Canon) {
4924 Canon = new (*this, alignof(DependentSizedMatrixType))
4925 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4926 ColumnExpr, AttrLoc);
4927#ifndef NDEBUG
4928 DependentSizedMatrixType *CanonCheck =
4929 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4930 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4931#endif
4932 DependentSizedMatrixTypes.InsertNode(N: Canon, InsertPos);
4933 Types.push_back(Elt: Canon);
4934 }
4935
4936 // Already have a canonical version of the matrix type
4937 //
4938 // If it exactly matches the requested type, use it directly.
4939 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4940 Canon->getRowExpr() == ColumnExpr)
4941 return QualType(Canon, 0);
4942
4943 // Use Canon as the canonical type for newly-built type.
4944 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4945 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4946 ColumnExpr, AttrLoc);
4947 Types.push_back(Elt: New);
4948 return QualType(New, 0);
4949}
4950
4951QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4952 Expr *AddrSpaceExpr,
4953 SourceLocation AttrLoc) const {
4954 assert(AddrSpaceExpr->isInstantiationDependent());
4955
4956 QualType canonPointeeType = getCanonicalType(T: PointeeType);
4957
4958 void *insertPos = nullptr;
4959 llvm::FoldingSetNodeID ID;
4960 DependentAddressSpaceType::Profile(ID, Context: *this, PointeeType: canonPointeeType,
4961 AddrSpaceExpr);
4962
4963 DependentAddressSpaceType *canonTy =
4964 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, InsertPos&: insertPos);
4965
4966 if (!canonTy) {
4967 canonTy = new (*this, alignof(DependentAddressSpaceType))
4968 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4969 AttrLoc);
4970 DependentAddressSpaceTypes.InsertNode(N: canonTy, InsertPos: insertPos);
4971 Types.push_back(Elt: canonTy);
4972 }
4973
4974 if (canonPointeeType == PointeeType &&
4975 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4976 return QualType(canonTy, 0);
4977
4978 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4979 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4980 AddrSpaceExpr, AttrLoc);
4981 Types.push_back(Elt: sugaredType);
4982 return QualType(sugaredType, 0);
4983}
4984
4985/// Determine whether \p T is canonical as the result type of a function.
4986static bool isCanonicalResultType(QualType T) {
4987 return T.isCanonical() &&
4988 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4989 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4990}
4991
4992/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4993QualType
4994ASTContext::getFunctionNoProtoType(QualType ResultTy,
4995 const FunctionType::ExtInfo &Info) const {
4996 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4997 // functionality creates a function without a prototype regardless of
4998 // language mode (so it makes them even in C++). Once the rewriter has been
4999 // fixed, this assertion can be enabled again.
5000 //assert(!LangOpts.requiresStrictPrototypes() &&
5001 // "strict prototypes are disabled");
5002
5003 // Unique functions, to guarantee there is only one function of a particular
5004 // structure.
5005 llvm::FoldingSetNodeID ID;
5006 FunctionNoProtoType::Profile(ID, ResultType: ResultTy, Info);
5007
5008 void *InsertPos = nullptr;
5009 if (FunctionNoProtoType *FT =
5010 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
5011 return QualType(FT, 0);
5012
5013 QualType Canonical;
5014 if (!isCanonicalResultType(T: ResultTy)) {
5015 Canonical =
5016 getFunctionNoProtoType(ResultTy: getCanonicalFunctionResultType(ResultType: ResultTy), Info);
5017
5018 // Get the new insert position for the node we care about.
5019 FunctionNoProtoType *NewIP =
5020 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5021 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5022 }
5023
5024 auto *New = new (*this, alignof(FunctionNoProtoType))
5025 FunctionNoProtoType(ResultTy, Canonical, Info);
5026 Types.push_back(Elt: New);
5027 FunctionNoProtoTypes.InsertNode(N: New, InsertPos);
5028 return QualType(New, 0);
5029}
5030
5031CanQualType
5032ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
5033 CanQualType CanResultType = getCanonicalType(T: ResultType);
5034
5035 // Canonical result types do not have ARC lifetime qualifiers.
5036 if (CanResultType.getQualifiers().hasObjCLifetime()) {
5037 Qualifiers Qs = CanResultType.getQualifiers();
5038 Qs.removeObjCLifetime();
5039 return CanQualType::CreateUnsafe(
5040 Other: getQualifiedType(T: CanResultType.getUnqualifiedType(), Qs));
5041 }
5042
5043 return CanResultType;
5044}
5045
5046static bool isCanonicalExceptionSpecification(
5047 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
5048 if (ESI.Type == EST_None)
5049 return true;
5050 if (!NoexceptInType)
5051 return false;
5052
5053 // C++17 onwards: exception specification is part of the type, as a simple
5054 // boolean "can this function type throw".
5055 if (ESI.Type == EST_BasicNoexcept)
5056 return true;
5057
5058 // A noexcept(expr) specification is (possibly) canonical if expr is
5059 // value-dependent.
5060 if (ESI.Type == EST_DependentNoexcept)
5061 return true;
5062
5063 // A dynamic exception specification is canonical if it only contains pack
5064 // expansions (so we can't tell whether it's non-throwing) and all its
5065 // contained types are canonical.
5066 if (ESI.Type == EST_Dynamic) {
5067 bool AnyPackExpansions = false;
5068 for (QualType ET : ESI.Exceptions) {
5069 if (!ET.isCanonical())
5070 return false;
5071 if (ET->getAs<PackExpansionType>())
5072 AnyPackExpansions = true;
5073 }
5074 return AnyPackExpansions;
5075 }
5076
5077 return false;
5078}
5079
5080QualType ASTContext::getFunctionTypeInternal(
5081 QualType ResultTy, ArrayRef<QualType> ArgArray,
5082 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
5083 size_t NumArgs = ArgArray.size();
5084
5085 // Unique functions, to guarantee there is only one function of a particular
5086 // structure.
5087 llvm::FoldingSetNodeID ID;
5088 FunctionProtoType::Profile(ID, Result: ResultTy, ArgTys: ArgArray.begin(), NumArgs, EPI,
5089 Context: *this, Canonical: true);
5090
5091 QualType Canonical;
5092 bool Unique = false;
5093
5094 void *InsertPos = nullptr;
5095 if (FunctionProtoType *FPT =
5096 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5097 QualType Existing = QualType(FPT, 0);
5098
5099 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5100 // it so long as our exception specification doesn't contain a dependent
5101 // noexcept expression, or we're just looking for a canonical type.
5102 // Otherwise, we're going to need to create a type
5103 // sugar node to hold the concrete expression.
5104 if (OnlyWantCanonical || !isComputedNoexcept(ESpecType: EPI.ExceptionSpec.Type) ||
5105 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5106 return Existing;
5107
5108 // We need a new type sugar node for this one, to hold the new noexcept
5109 // expression. We do no canonicalization here, but that's OK since we don't
5110 // expect to see the same noexcept expression much more than once.
5111 Canonical = getCanonicalType(T: Existing);
5112 Unique = true;
5113 }
5114
5115 bool NoexceptInType = getLangOpts().CPlusPlus17;
5116 bool IsCanonicalExceptionSpec =
5117 isCanonicalExceptionSpecification(ESI: EPI.ExceptionSpec, NoexceptInType);
5118
5119 // Determine whether the type being created is already canonical or not.
5120 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5121 isCanonicalResultType(T: ResultTy) && !EPI.HasTrailingReturn;
5122 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5123 if (!ArgArray[i].isCanonicalAsParam())
5124 isCanonical = false;
5125
5126 if (OnlyWantCanonical)
5127 assert(isCanonical &&
5128 "given non-canonical parameters constructing canonical type");
5129
5130 // If this type isn't canonical, get the canonical version of it if we don't
5131 // already have it. The exception spec is only partially part of the
5132 // canonical type, and only in C++17 onwards.
5133 if (!isCanonical && Canonical.isNull()) {
5134 SmallVector<QualType, 16> CanonicalArgs;
5135 CanonicalArgs.reserve(N: NumArgs);
5136 for (unsigned i = 0; i != NumArgs; ++i)
5137 CanonicalArgs.push_back(Elt: getCanonicalParamType(T: ArgArray[i]));
5138
5139 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5140 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5141 CanonicalEPI.HasTrailingReturn = false;
5142
5143 if (IsCanonicalExceptionSpec) {
5144 // Exception spec is already OK.
5145 } else if (NoexceptInType) {
5146 switch (EPI.ExceptionSpec.Type) {
5147 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
5148 // We don't know yet. It shouldn't matter what we pick here; no-one
5149 // should ever look at this.
5150 [[fallthrough]];
5151 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5152 CanonicalEPI.ExceptionSpec.Type = EST_None;
5153 break;
5154
5155 // A dynamic exception specification is almost always "not noexcept",
5156 // with the exception that a pack expansion might expand to no types.
5157 case EST_Dynamic: {
5158 bool AnyPacks = false;
5159 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5160 if (ET->getAs<PackExpansionType>())
5161 AnyPacks = true;
5162 ExceptionTypeStorage.push_back(Elt: getCanonicalType(T: ET));
5163 }
5164 if (!AnyPacks)
5165 CanonicalEPI.ExceptionSpec.Type = EST_None;
5166 else {
5167 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5168 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5169 }
5170 break;
5171 }
5172
5173 case EST_DynamicNone:
5174 case EST_BasicNoexcept:
5175 case EST_NoexceptTrue:
5176 case EST_NoThrow:
5177 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5178 break;
5179
5180 case EST_DependentNoexcept:
5181 llvm_unreachable("dependent noexcept is already canonical");
5182 }
5183 } else {
5184 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5185 }
5186
5187 // Adjust the canonical function result type.
5188 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultType: ResultTy);
5189 Canonical =
5190 getFunctionTypeInternal(ResultTy: CanResultTy, ArgArray: CanonicalArgs, EPI: CanonicalEPI, OnlyWantCanonical: true);
5191
5192 // Get the new insert position for the node we care about.
5193 FunctionProtoType *NewIP =
5194 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5195 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5196 }
5197
5198 // Compute the needed size to hold this FunctionProtoType and the
5199 // various trailing objects.
5200 auto ESH = FunctionProtoType::getExceptionSpecSize(
5201 EST: EPI.ExceptionSpec.Type, NumExceptions: EPI.ExceptionSpec.Exceptions.size());
5202 size_t Size = FunctionProtoType::totalSizeToAlloc<
5203 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5204 FunctionType::FunctionTypeExtraAttributeInfo,
5205 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5206 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5207 FunctionEffect, EffectConditionExpr>(
5208 Counts: NumArgs, Counts: EPI.Variadic, Counts: EPI.requiresFunctionProtoTypeExtraBitfields(),
5209 Counts: EPI.requiresFunctionProtoTypeExtraAttributeInfo(),
5210 Counts: EPI.requiresFunctionProtoTypeArmAttributes(), Counts: ESH.NumExceptionType,
5211 Counts: ESH.NumExprPtr, Counts: ESH.NumFunctionDeclPtr,
5212 Counts: EPI.ExtParameterInfos ? NumArgs : 0,
5213 Counts: EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0, Counts: EPI.FunctionEffects.size(),
5214 Counts: EPI.FunctionEffects.conditions().size());
5215
5216 auto *FTP = (FunctionProtoType *)Allocate(Size, Align: alignof(FunctionProtoType));
5217 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5218 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5219 Types.push_back(Elt: FTP);
5220 if (!Unique)
5221 FunctionProtoTypes.InsertNode(N: FTP, InsertPos);
5222 if (!EPI.FunctionEffects.empty())
5223 AnyFunctionEffects = true;
5224 return QualType(FTP, 0);
5225}
5226
5227QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5228 llvm::FoldingSetNodeID ID;
5229 PipeType::Profile(ID, T, isRead: ReadOnly);
5230
5231 void *InsertPos = nullptr;
5232 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5233 return QualType(PT, 0);
5234
5235 // If the pipe element type isn't canonical, this won't be a canonical type
5236 // either, so fill in the canonical type field.
5237 QualType Canonical;
5238 if (!T.isCanonical()) {
5239 Canonical = getPipeType(T: getCanonicalType(T), ReadOnly);
5240
5241 // Get the new insert position for the node we care about.
5242 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5243 assert(!NewIP && "Shouldn't be in the map!");
5244 (void)NewIP;
5245 }
5246 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5247 Types.push_back(Elt: New);
5248 PipeTypes.InsertNode(N: New, InsertPos);
5249 return QualType(New, 0);
5250}
5251
5252QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
5253 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5254 return LangOpts.OpenCL ? getAddrSpaceQualType(T: Ty, AddressSpace: LangAS::opencl_constant)
5255 : Ty;
5256}
5257
5258QualType ASTContext::getReadPipeType(QualType T) const {
5259 return getPipeType(T, ReadOnly: true);
5260}
5261
5262QualType ASTContext::getWritePipeType(QualType T) const {
5263 return getPipeType(T, ReadOnly: false);
5264}
5265
5266QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5267 llvm::FoldingSetNodeID ID;
5268 BitIntType::Profile(ID, IsUnsigned, NumBits);
5269
5270 void *InsertPos = nullptr;
5271 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5272 return QualType(EIT, 0);
5273
5274 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5275 BitIntTypes.InsertNode(N: New, InsertPos);
5276 Types.push_back(Elt: New);
5277 return QualType(New, 0);
5278}
5279
5280QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
5281 Expr *NumBitsExpr) const {
5282 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5283 llvm::FoldingSetNodeID ID;
5284 DependentBitIntType::Profile(ID, Context: *this, IsUnsigned, NumBitsExpr);
5285
5286 void *InsertPos = nullptr;
5287 if (DependentBitIntType *Existing =
5288 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5289 return QualType(Existing, 0);
5290
5291 auto *New = new (*this, alignof(DependentBitIntType))
5292 DependentBitIntType(IsUnsigned, NumBitsExpr);
5293 DependentBitIntTypes.InsertNode(N: New, InsertPos);
5294
5295 Types.push_back(Elt: New);
5296 return QualType(New, 0);
5297}
5298
5299QualType
5300ASTContext::getPredefinedSugarType(PredefinedSugarType::Kind KD) const {
5301 using Kind = PredefinedSugarType::Kind;
5302
5303 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(E: KD)];
5304 Target != nullptr)
5305 return QualType(Target, 0);
5306
5307 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5308 switch (KDI) {
5309 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5310 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5311 // are part of the core language and are widely used. Using
5312 // PredefinedSugarType makes these types as named sugar types rather than
5313 // standard integer types, enabling better hints and diagnostics.
5314 case Kind::SizeT:
5315 return Ctx.getFromTargetType(Type: Ctx.Target->getSizeType());
5316 case Kind::SignedSizeT:
5317 return Ctx.getFromTargetType(Type: Ctx.Target->getSignedSizeType());
5318 case Kind::PtrdiffT:
5319 return Ctx.getFromTargetType(Type: Ctx.Target->getPtrDiffType(AddrSpace: LangAS::Default));
5320 }
5321 llvm_unreachable("unexpected kind");
5322 };
5323 auto *New = new (*this, alignof(PredefinedSugarType))
5324 PredefinedSugarType(KD, &Idents.get(Name: PredefinedSugarType::getName(KD)),
5325 getCanonicalType(*this, static_cast<Kind>(KD)));
5326 Types.push_back(Elt: New);
5327 PredefinedSugarTypes[llvm::to_underlying(E: KD)] = New;
5328 return QualType(New, 0);
5329}
5330
5331QualType ASTContext::getTypeDeclType(ElaboratedTypeKeyword Keyword,
5332 NestedNameSpecifier Qualifier,
5333 const TypeDecl *Decl) const {
5334 if (auto *Tag = dyn_cast<TagDecl>(Val: Decl))
5335 return getTagType(Keyword, Qualifier, TD: Tag,
5336 /*OwnsTag=*/false);
5337 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Val: Decl))
5338 return getTypedefType(Keyword, Qualifier, Decl: Typedef);
5339 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: Decl))
5340 return getUnresolvedUsingType(Keyword, Qualifier, D: UD);
5341
5342 assert(Keyword == ElaboratedTypeKeyword::None);
5343 assert(!Qualifier);
5344 return QualType(Decl->TypeForDecl, 0);
5345}
5346
5347CanQualType ASTContext::getCanonicalTypeDeclType(const TypeDecl *TD) const {
5348 if (auto *Tag = dyn_cast<TagDecl>(Val: TD))
5349 return getCanonicalTagType(TD: Tag);
5350 if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TD))
5351 return getCanonicalType(T: TN->getUnderlyingType());
5352 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TD))
5353 return getCanonicalUnresolvedUsingType(D: UD);
5354 assert(TD->TypeForDecl);
5355 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5356}
5357
5358QualType ASTContext::getTypeDeclType(const TypeDecl *Decl) const {
5359 if (const auto *TD = dyn_cast<TagDecl>(Val: Decl))
5360 return getCanonicalTagType(TD);
5361 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: Decl);
5362 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(Val: TD))
5363 return getTypedefType(Keyword: ElaboratedTypeKeyword::None,
5364 /*Qualifier=*/std::nullopt, Decl: TD);
5365 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Val: Decl))
5366 return getCanonicalUnresolvedUsingType(D: Using);
5367
5368 assert(Decl->TypeForDecl);
5369 return QualType(Decl->TypeForDecl, 0);
5370}
5371
5372/// getTypedefType - Return the unique reference to the type for the
5373/// specified typedef name decl.
5374QualType
5375ASTContext::getTypedefType(ElaboratedTypeKeyword Keyword,
5376 NestedNameSpecifier Qualifier,
5377 const TypedefNameDecl *Decl, QualType UnderlyingType,
5378 std::optional<bool> TypeMatchesDeclOrNone) const {
5379 if (!TypeMatchesDeclOrNone) {
5380 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5381 assert(!DeclUnderlyingType.isNull());
5382 if (UnderlyingType.isNull())
5383 UnderlyingType = DeclUnderlyingType;
5384 else
5385 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5386 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5387 } else {
5388 // FIXME: This is a workaround for a serialization cycle: assume the decl
5389 // underlying type is not available; don't touch it.
5390 assert(!UnderlyingType.isNull());
5391 }
5392
5393 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5394 *TypeMatchesDeclOrNone) {
5395 if (Decl->TypeForDecl)
5396 return QualType(Decl->TypeForDecl, 0);
5397
5398 auto *NewType = new (*this, alignof(TypedefType))
5399 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5400 !*TypeMatchesDeclOrNone);
5401
5402 Types.push_back(Elt: NewType);
5403 Decl->TypeForDecl = NewType;
5404 return QualType(NewType, 0);
5405 }
5406
5407 llvm::FoldingSetNodeID ID;
5408 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5409 Underlying: *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5410
5411 void *InsertPos = nullptr;
5412 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5413 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5414 return QualType(Placeholder->getType(), 0);
5415
5416 void *Mem =
5417 Allocate(Size: TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5418 NestedNameSpecifier, QualType>(
5419 Counts: 1, Counts: !!Qualifier, Counts: !*TypeMatchesDeclOrNone),
5420 Align: alignof(TypedefType));
5421 auto *NewType =
5422 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5423 UnderlyingType, !*TypeMatchesDeclOrNone);
5424 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5425 FoldingSetPlaceholder<TypedefType>();
5426 TypedefTypes.InsertNode(N: Placeholder, InsertPos);
5427 Types.push_back(Elt: NewType);
5428 return QualType(NewType, 0);
5429}
5430
5431QualType ASTContext::getUsingType(ElaboratedTypeKeyword Keyword,
5432 NestedNameSpecifier Qualifier,
5433 const UsingShadowDecl *D,
5434 QualType UnderlyingType) const {
5435 // FIXME: This is expensive to compute every time!
5436 if (UnderlyingType.isNull()) {
5437 const auto *UD = cast<UsingDecl>(Val: D->getIntroducer());
5438 UnderlyingType =
5439 getTypeDeclType(Keyword: UD->hasTypename() ? ElaboratedTypeKeyword::Typename
5440 : ElaboratedTypeKeyword::None,
5441 Qualifier: UD->getQualifier(), Decl: cast<TypeDecl>(Val: D->getTargetDecl()));
5442 }
5443
5444 llvm::FoldingSetNodeID ID;
5445 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5446
5447 void *InsertPos = nullptr;
5448 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5449 return QualType(T, 0);
5450
5451 assert(!UnderlyingType.hasLocalQualifiers());
5452
5453 assert(
5454 hasSameType(getCanonicalTypeDeclType(cast<TypeDecl>(D->getTargetDecl())),
5455 UnderlyingType));
5456
5457 void *Mem =
5458 Allocate(Size: UsingType::totalSizeToAlloc<NestedNameSpecifier>(Counts: !!Qualifier),
5459 Align: alignof(UsingType));
5460 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5461 Types.push_back(Elt: T);
5462 UsingTypes.InsertNode(N: T, InsertPos);
5463 return QualType(T, 0);
5464}
5465
5466TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5467 NestedNameSpecifier Qualifier,
5468 const TagDecl *TD, bool OwnsTag,
5469 bool IsInjected,
5470 const Type *CanonicalType,
5471 bool WithFoldingSetNode) const {
5472 auto [TC, Size] = [&] {
5473 switch (TD->getDeclKind()) {
5474 case Decl::Enum:
5475 static_assert(alignof(EnumType) == alignof(TagType));
5476 return std::make_tuple(args: Type::Enum, args: sizeof(EnumType));
5477 case Decl::ClassTemplatePartialSpecialization:
5478 case Decl::ClassTemplateSpecialization:
5479 case Decl::CXXRecord:
5480 static_assert(alignof(RecordType) == alignof(TagType));
5481 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5482 if (cast<CXXRecordDecl>(Val: TD)->hasInjectedClassType())
5483 return std::make_tuple(args: Type::InjectedClassName,
5484 args: sizeof(InjectedClassNameType));
5485 [[fallthrough]];
5486 case Decl::Record:
5487 return std::make_tuple(args: Type::Record, args: sizeof(RecordType));
5488 default:
5489 llvm_unreachable("unexpected decl kind");
5490 }
5491 }();
5492
5493 if (Qualifier) {
5494 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5495 Size = llvm::alignTo(Value: Size, Align: alignof(NestedNameSpecifier)) +
5496 sizeof(NestedNameSpecifier);
5497 }
5498 void *Mem;
5499 if (WithFoldingSetNode) {
5500 // FIXME: It would be more profitable to tail allocate the folding set node
5501 // from the type, instead of the other way around, due to the greater
5502 // alignment requirements of the type. But this makes it harder to deal with
5503 // the different type node sizes. This would require either uniquing from
5504 // different folding sets, or having the folding setaccept a
5505 // contextual parameter which is not fixed at construction.
5506 Mem = Allocate(
5507 Size: sizeof(TagTypeFoldingSetPlaceholder) +
5508 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5509 Align: std::max(a: alignof(TagTypeFoldingSetPlaceholder), b: alignof(TagType)));
5510 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5511 Mem = T->getTagType();
5512 } else {
5513 Mem = Allocate(Size, Align: alignof(TagType));
5514 }
5515
5516 auto *T = [&, TC = TC]() -> TagType * {
5517 switch (TC) {
5518 case Type::Enum: {
5519 assert(isa<EnumDecl>(TD));
5520 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5521 IsInjected, CanonicalType);
5522 assert(reinterpret_cast<void *>(T) ==
5523 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5524 "TagType must be the first base of EnumType");
5525 return T;
5526 }
5527 case Type::Record: {
5528 assert(isa<RecordDecl>(TD));
5529 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5530 IsInjected, CanonicalType);
5531 assert(reinterpret_cast<void *>(T) ==
5532 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5533 "TagType must be the first base of RecordType");
5534 return T;
5535 }
5536 case Type::InjectedClassName: {
5537 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5538 IsInjected, CanonicalType);
5539 assert(reinterpret_cast<void *>(T) ==
5540 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5541 "TagType must be the first base of InjectedClassNameType");
5542 return T;
5543 }
5544 default:
5545 llvm_unreachable("unexpected type class");
5546 }
5547 }();
5548 assert(T->getKeyword() == Keyword);
5549 assert(T->getQualifier() == Qualifier);
5550 assert(T->getDecl() == TD);
5551 assert(T->isInjected() == IsInjected);
5552 assert(T->isTagOwned() == OwnsTag);
5553 assert((T->isCanonicalUnqualified()
5554 ? QualType()
5555 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5556 Types.push_back(Elt: T);
5557 return T;
5558}
5559
5560static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5561 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: TD);
5562 RD && RD->isInjectedClassName())
5563 return cast<TagDecl>(Val: RD->getDeclContext());
5564 return TD;
5565}
5566
5567CanQualType ASTContext::getCanonicalTagType(const TagDecl *TD) const {
5568 TD = ::getNonInjectedClassName(TD)->getCanonicalDecl();
5569 if (TD->TypeForDecl)
5570 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5571
5572 const Type *CanonicalType = getTagTypeInternal(
5573 Keyword: ElaboratedTypeKeyword::None,
5574 /*Qualifier=*/std::nullopt, TD,
5575 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5576 /*WithFoldingSetNode=*/false);
5577 TD->TypeForDecl = CanonicalType;
5578 return CanQualType::CreateUnsafe(Other: QualType(CanonicalType, 0));
5579}
5580
5581QualType ASTContext::getTagType(ElaboratedTypeKeyword Keyword,
5582 NestedNameSpecifier Qualifier,
5583 const TagDecl *TD, bool OwnsTag) const {
5584
5585 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5586 bool IsInjected = TD != NonInjectedTD;
5587
5588 ElaboratedTypeKeyword PreferredKeyword =
5589 getLangOpts().CPlusPlus ? ElaboratedTypeKeyword::None
5590 : KeywordHelpers::getKeywordForTagTypeKind(
5591 Tag: NonInjectedTD->getTagKind());
5592
5593 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5594 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5595 return QualType(T, 0);
5596
5597 const Type *CanonicalType = getCanonicalTagType(TD: NonInjectedTD).getTypePtr();
5598 const Type *T =
5599 getTagTypeInternal(Keyword,
5600 /*Qualifier=*/std::nullopt, TD: NonInjectedTD,
5601 /*OwnsTag=*/false, IsInjected, CanonicalType,
5602 /*WithFoldingSetNode=*/false);
5603 TD->TypeForDecl = T;
5604 return QualType(T, 0);
5605 }
5606
5607 llvm::FoldingSetNodeID ID;
5608 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, Tag: NonInjectedTD,
5609 OwnsTag, IsInjected);
5610
5611 void *InsertPos = nullptr;
5612 if (TagTypeFoldingSetPlaceholder *T =
5613 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5614 return QualType(T->getTagType(), 0);
5615
5616 const Type *CanonicalType = getCanonicalTagType(TD: NonInjectedTD).getTypePtr();
5617 TagType *T =
5618 getTagTypeInternal(Keyword, Qualifier, TD: NonInjectedTD, OwnsTag, IsInjected,
5619 CanonicalType, /*WithFoldingSetNode=*/true);
5620 TagTypes.InsertNode(N: TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5621 return QualType(T, 0);
5622}
5623
5624bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5625 unsigned NumPositiveBits,
5626 QualType &BestType,
5627 QualType &BestPromotionType) {
5628 unsigned IntWidth = Target->getIntWidth();
5629 unsigned CharWidth = Target->getCharWidth();
5630 unsigned ShortWidth = Target->getShortWidth();
5631 bool EnumTooLarge = false;
5632 unsigned BestWidth;
5633 if (NumNegativeBits) {
5634 // If there is a negative value, figure out the smallest integer type (of
5635 // int/long/longlong) that fits.
5636 // If it's packed, check also if it fits a char or a short.
5637 if (IsPacked && NumNegativeBits <= CharWidth &&
5638 NumPositiveBits < CharWidth) {
5639 BestType = SignedCharTy;
5640 BestWidth = CharWidth;
5641 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5642 NumPositiveBits < ShortWidth) {
5643 BestType = ShortTy;
5644 BestWidth = ShortWidth;
5645 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5646 BestType = IntTy;
5647 BestWidth = IntWidth;
5648 } else {
5649 BestWidth = Target->getLongWidth();
5650
5651 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5652 BestType = LongTy;
5653 } else {
5654 BestWidth = Target->getLongLongWidth();
5655
5656 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5657 EnumTooLarge = true;
5658 BestType = LongLongTy;
5659 }
5660 }
5661 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5662 } else {
5663 // If there is no negative value, figure out the smallest type that fits
5664 // all of the enumerator values.
5665 // If it's packed, check also if it fits a char or a short.
5666 if (IsPacked && NumPositiveBits <= CharWidth) {
5667 BestType = UnsignedCharTy;
5668 BestPromotionType = IntTy;
5669 BestWidth = CharWidth;
5670 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5671 BestType = UnsignedShortTy;
5672 BestPromotionType = IntTy;
5673 BestWidth = ShortWidth;
5674 } else if (NumPositiveBits <= IntWidth) {
5675 BestType = UnsignedIntTy;
5676 BestWidth = IntWidth;
5677 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5678 ? UnsignedIntTy
5679 : IntTy;
5680 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5681 BestType = UnsignedLongTy;
5682 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5683 ? UnsignedLongTy
5684 : LongTy;
5685 } else {
5686 BestWidth = Target->getLongLongWidth();
5687 if (NumPositiveBits > BestWidth) {
5688 // This can happen with bit-precise integer types, but those are not
5689 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5690 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5691 // a 128-bit integer, we should consider doing the same.
5692 EnumTooLarge = true;
5693 }
5694 BestType = UnsignedLongLongTy;
5695 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5696 ? UnsignedLongLongTy
5697 : LongLongTy;
5698 }
5699 }
5700 return EnumTooLarge;
5701}
5702
5703bool ASTContext::isRepresentableIntegerValue(llvm::APSInt &Value, QualType T) {
5704 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5705 "Integral type required!");
5706 unsigned BitWidth = getIntWidth(T);
5707
5708 if (Value.isUnsigned() || Value.isNonNegative()) {
5709 if (T->isSignedIntegerOrEnumerationType())
5710 --BitWidth;
5711 return Value.getActiveBits() <= BitWidth;
5712 }
5713 return Value.getSignificantBits() <= BitWidth;
5714}
5715
5716UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5717 ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier,
5718 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5719 const Type *CanonicalType) const {
5720 void *Mem = Allocate(
5721 Size: UnresolvedUsingType::totalSizeToAlloc<
5722 FoldingSetPlaceholder<UnresolvedUsingType>, NestedNameSpecifier>(
5723 Counts: !!InsertPos, Counts: !!Qualifier),
5724 Align: alignof(UnresolvedUsingType));
5725 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5726 if (InsertPos) {
5727 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5728 FoldingSetPlaceholder<TypedefType>();
5729 TypedefTypes.InsertNode(N: Placeholder, InsertPos);
5730 }
5731 Types.push_back(Elt: T);
5732 return T;
5733}
5734
5735CanQualType ASTContext::getCanonicalUnresolvedUsingType(
5736 const UnresolvedUsingTypenameDecl *D) const {
5737 D = D->getCanonicalDecl();
5738 if (D->TypeForDecl)
5739 return D->TypeForDecl->getCanonicalTypeUnqualified();
5740
5741 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5742 Keyword: ElaboratedTypeKeyword::None,
5743 /*Qualifier=*/std::nullopt, D,
5744 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5745 D->TypeForDecl = CanonicalType;
5746 return CanQualType::CreateUnsafe(Other: QualType(CanonicalType, 0));
5747}
5748
5749QualType
5750ASTContext::getUnresolvedUsingType(ElaboratedTypeKeyword Keyword,
5751 NestedNameSpecifier Qualifier,
5752 const UnresolvedUsingTypenameDecl *D) const {
5753 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5754 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5755 return QualType(T, 0);
5756
5757 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5758 const Type *T =
5759 getUnresolvedUsingTypeInternal(Keyword: ElaboratedTypeKeyword::None,
5760 /*Qualifier=*/std::nullopt, D,
5761 /*InsertPos=*/nullptr, CanonicalType);
5762 D->TypeForDecl = T;
5763 return QualType(T, 0);
5764 }
5765
5766 llvm::FoldingSetNodeID ID;
5767 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5768
5769 void *InsertPos = nullptr;
5770 if (FoldingSetPlaceholder<UnresolvedUsingType> *Placeholder =
5771 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5772 return QualType(Placeholder->getType(), 0);
5773 assert(InsertPos);
5774
5775 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5776 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5777 InsertPos, CanonicalType);
5778 return QualType(T, 0);
5779}
5780
5781QualType ASTContext::getAttributedType(attr::Kind attrKind,
5782 QualType modifiedType,
5783 QualType equivalentType,
5784 const Attr *attr) const {
5785 llvm::FoldingSetNodeID id;
5786 AttributedType::Profile(ID&: id, Ctx: *this, attrKind, modified: modifiedType, equivalent: equivalentType,
5787 attr);
5788
5789 void *insertPos = nullptr;
5790 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(ID: id, InsertPos&: insertPos);
5791 if (type) return QualType(type, 0);
5792
5793 assert(!attr || attr->getKind() == attrKind);
5794
5795 QualType canon = getCanonicalType(T: equivalentType);
5796 type = new (*this, alignof(AttributedType))
5797 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5798
5799 Types.push_back(Elt: type);
5800 AttributedTypes.InsertNode(N: type, InsertPos: insertPos);
5801
5802 return QualType(type, 0);
5803}
5804
5805QualType ASTContext::getAttributedType(const Attr *attr, QualType modifiedType,
5806 QualType equivalentType) const {
5807 return getAttributedType(attrKind: attr->getKind(), modifiedType, equivalentType, attr);
5808}
5809
5810QualType ASTContext::getAttributedType(NullabilityKind nullability,
5811 QualType modifiedType,
5812 QualType equivalentType) const {
5813 switch (nullability) {
5814 case NullabilityKind::NonNull:
5815 return getAttributedType(attrKind: attr::TypeNonNull, modifiedType, equivalentType);
5816
5817 case NullabilityKind::Nullable:
5818 return getAttributedType(attrKind: attr::TypeNullable, modifiedType, equivalentType);
5819
5820 case NullabilityKind::NullableResult:
5821 return getAttributedType(attrKind: attr::TypeNullableResult, modifiedType,
5822 equivalentType);
5823
5824 case NullabilityKind::Unspecified:
5825 return getAttributedType(attrKind: attr::TypeNullUnspecified, modifiedType,
5826 equivalentType);
5827 }
5828
5829 llvm_unreachable("Unknown nullability kind");
5830}
5831
5832QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5833 QualType Wrapped) const {
5834 llvm::FoldingSetNodeID ID;
5835 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5836
5837 void *InsertPos = nullptr;
5838 BTFTagAttributedType *Ty =
5839 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5840 if (Ty)
5841 return QualType(Ty, 0);
5842
5843 QualType Canon = getCanonicalType(T: Wrapped);
5844 Ty = new (*this, alignof(BTFTagAttributedType))
5845 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5846
5847 Types.push_back(Elt: Ty);
5848 BTFTagAttributedTypes.InsertNode(N: Ty, InsertPos);
5849
5850 return QualType(Ty, 0);
5851}
5852
5853QualType ASTContext::getOverflowBehaviorType(const OverflowBehaviorAttr *Attr,
5854 QualType Underlying) const {
5855 const IdentifierInfo *II = Attr->getBehaviorKind();
5856 StringRef IdentName = II->getName();
5857 OverflowBehaviorType::OverflowBehaviorKind Kind;
5858 if (IdentName == "wrap") {
5859 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5860 } else if (IdentName == "trap") {
5861 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5862 } else {
5863 return Underlying;
5864 }
5865
5866 return getOverflowBehaviorType(Kind, Wrapped: Underlying);
5867}
5868
5869QualType ASTContext::getOverflowBehaviorType(
5870 OverflowBehaviorType::OverflowBehaviorKind Kind,
5871 QualType Underlying) const {
5872 assert(!Underlying->isOverflowBehaviorType() &&
5873 "Cannot have underlying types that are themselves OBTs");
5874 llvm::FoldingSetNodeID ID;
5875 OverflowBehaviorType::Profile(ID, Underlying, Kind);
5876 void *InsertPos = nullptr;
5877
5878 if (OverflowBehaviorType *OBT =
5879 OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5880 return QualType(OBT, 0);
5881 }
5882
5883 QualType Canonical;
5884 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5885 SplitQualType canonSplit = getCanonicalType(T: Underlying).split();
5886 Canonical = getOverflowBehaviorType(Kind, Underlying: QualType(canonSplit.Ty, 0));
5887 Canonical = getQualifiedType(T: Canonical, Qs: canonSplit.Quals);
5888 assert(!OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos) &&
5889 "Shouldn't be in the map");
5890 }
5891
5892 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5893 OverflowBehaviorType(Canonical, Underlying, Kind);
5894
5895 Types.push_back(Elt: Ty);
5896 OverflowBehaviorTypes.InsertNode(N: Ty, InsertPos);
5897 return QualType(Ty, 0);
5898}
5899
5900QualType ASTContext::getHLSLAttributedResourceType(
5901 QualType Wrapped, QualType Contained,
5902 const HLSLAttributedResourceType::Attributes &Attrs) {
5903
5904 llvm::FoldingSetNodeID ID;
5905 HLSLAttributedResourceType::Profile(ID, Ctx: *this, Wrapped, Contained, Attrs);
5906
5907 void *InsertPos = nullptr;
5908 HLSLAttributedResourceType *Ty =
5909 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5910 if (Ty)
5911 return QualType(Ty, 0);
5912
5913 Ty = new (*this, alignof(HLSLAttributedResourceType))
5914 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5915
5916 Types.push_back(Elt: Ty);
5917 HLSLAttributedResourceTypes.InsertNode(N: Ty, InsertPos);
5918
5919 return QualType(Ty, 0);
5920}
5921
5922QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5923 uint32_t Alignment,
5924 ArrayRef<SpirvOperand> Operands) {
5925 llvm::FoldingSetNodeID ID;
5926 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5927
5928 void *InsertPos = nullptr;
5929 HLSLInlineSpirvType *Ty =
5930 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5931 if (Ty)
5932 return QualType(Ty, 0);
5933
5934 void *Mem = Allocate(
5935 Size: HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Counts: Operands.size()),
5936 Align: alignof(HLSLInlineSpirvType));
5937
5938 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5939
5940 Types.push_back(Elt: Ty);
5941 HLSLInlineSpirvTypes.InsertNode(N: Ty, InsertPos);
5942
5943 return QualType(Ty, 0);
5944}
5945
5946/// Retrieve a substitution-result type.
5947QualType ASTContext::getSubstTemplateTypeParmType(QualType Replacement,
5948 Decl *AssociatedDecl,
5949 unsigned Index,
5950 UnsignedOrNone PackIndex,
5951 bool Final) const {
5952 llvm::FoldingSetNodeID ID;
5953 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5954 PackIndex, Final);
5955 void *InsertPos = nullptr;
5956 SubstTemplateTypeParmType *SubstParm =
5957 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5958
5959 if (!SubstParm) {
5960 void *Mem = Allocate(Size: SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5961 Counts: !Replacement.isCanonical()),
5962 Align: alignof(SubstTemplateTypeParmType));
5963 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5964 Index, PackIndex, Final);
5965 Types.push_back(Elt: SubstParm);
5966 SubstTemplateTypeParmTypes.InsertNode(N: SubstParm, InsertPos);
5967 }
5968
5969 return QualType(SubstParm, 0);
5970}
5971
5972QualType
5973ASTContext::getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
5974 unsigned Index, bool Final,
5975 const TemplateArgument &ArgPack) {
5976#ifndef NDEBUG
5977 for (const auto &P : ArgPack.pack_elements())
5978 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5979#endif
5980
5981 llvm::FoldingSetNodeID ID;
5982 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5983 ArgPack);
5984 void *InsertPos = nullptr;
5985 if (SubstTemplateTypeParmPackType *SubstParm =
5986 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5987 return QualType(SubstParm, 0);
5988
5989 QualType Canon;
5990 {
5991 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(Arg: ArgPack);
5992 if (!AssociatedDecl->isCanonicalDecl() ||
5993 !CanonArgPack.structurallyEquals(Other: ArgPack)) {
5994 Canon = getSubstTemplateTypeParmPackType(
5995 AssociatedDecl: AssociatedDecl->getCanonicalDecl(), Index, Final, ArgPack: CanonArgPack);
5996 [[maybe_unused]] const auto *Nothing =
5997 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5998 assert(!Nothing);
5999 }
6000 }
6001
6002 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
6003 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
6004 ArgPack);
6005 Types.push_back(Elt: SubstParm);
6006 SubstTemplateTypeParmPackTypes.InsertNode(N: SubstParm, InsertPos);
6007 return QualType(SubstParm, 0);
6008}
6009
6010QualType
6011ASTContext::getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack) {
6012 assert(llvm::all_of(ArgPack.pack_elements(),
6013 [](const auto &P) {
6014 return P.getKind() == TemplateArgument::Type;
6015 }) &&
6016 "Pack contains a non-type");
6017
6018 llvm::FoldingSetNodeID ID;
6019 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
6020
6021 void *InsertPos = nullptr;
6022 if (auto *T =
6023 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
6024 return QualType(T, 0);
6025
6026 QualType Canon;
6027 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(Arg: ArgPack);
6028 if (!CanonArgPack.structurallyEquals(Other: ArgPack)) {
6029 Canon = getSubstBuiltinTemplatePack(ArgPack: CanonArgPack);
6030 // Refresh InsertPos, in case the recursive call above caused rehashing,
6031 // which would invalidate the bucket pointer.
6032 [[maybe_unused]] const auto *Nothing =
6033 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos);
6034 assert(!Nothing);
6035 }
6036
6037 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
6038 SubstBuiltinTemplatePackType(Canon, ArgPack);
6039 Types.push_back(Elt: PackType);
6040 SubstBuiltinTemplatePackTypes.InsertNode(N: PackType, InsertPos);
6041 return QualType(PackType, 0);
6042}
6043
6044/// Retrieve the template type parameter type for a template
6045/// parameter or parameter pack with the given depth, index, and (optionally)
6046/// name.
6047QualType
6048ASTContext::getTemplateTypeParmType(int Depth, int Index, bool ParameterPack,
6049 TemplateTypeParmDecl *TTPDecl) const {
6050 assert(Depth >= 0 && "Depth must be non-negative");
6051 assert(Index >= 0 && "Index must be non-negative");
6052
6053 llvm::FoldingSetNodeID ID;
6054 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
6055 void *InsertPos = nullptr;
6056 TemplateTypeParmType *TypeParm
6057 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
6058
6059 if (TypeParm)
6060 return QualType(TypeParm, 0);
6061
6062 if (TTPDecl) {
6063 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
6064 TypeParm = new (*this, alignof(TemplateTypeParmType))
6065 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
6066
6067 TemplateTypeParmType *TypeCheck
6068 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
6069 assert(!TypeCheck && "Template type parameter canonical type broken");
6070 (void)TypeCheck;
6071 } else
6072 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
6073 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
6074
6075 Types.push_back(Elt: TypeParm);
6076 TemplateTypeParmTypes.InsertNode(N: TypeParm, InsertPos);
6077
6078 return QualType(TypeParm, 0);
6079}
6080
6081static ElaboratedTypeKeyword
6082getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword) {
6083 switch (Keyword) {
6084 // These are just themselves.
6085 case ElaboratedTypeKeyword::None:
6086 case ElaboratedTypeKeyword::Struct:
6087 case ElaboratedTypeKeyword::Union:
6088 case ElaboratedTypeKeyword::Enum:
6089 case ElaboratedTypeKeyword::Interface:
6090 return Keyword;
6091
6092 // These are equivalent.
6093 case ElaboratedTypeKeyword::Typename:
6094 return ElaboratedTypeKeyword::None;
6095
6096 // These are functionally equivalent, so relying on their equivalence is
6097 // IFNDR. By making them equivalent, we disallow overloading, which at least
6098 // can produce a diagnostic.
6099 case ElaboratedTypeKeyword::Class:
6100 return ElaboratedTypeKeyword::Struct;
6101 }
6102 llvm_unreachable("unexpected keyword kind");
6103}
6104
6105TypeSourceInfo *ASTContext::getTemplateSpecializationTypeInfo(
6106 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6107 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6108 TemplateName Name, SourceLocation NameLoc,
6109 const TemplateArgumentListInfo &SpecifiedArgs,
6110 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6111 QualType TST = getTemplateSpecializationType(
6112 Keyword, T: Name, SpecifiedArgs: SpecifiedArgs.arguments(), CanonicalArgs, Canon: Underlying);
6113
6114 TypeSourceInfo *TSI = CreateTypeSourceInfo(T: TST);
6115 TSI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>().set(
6116 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6117 TAL: SpecifiedArgs);
6118 return TSI;
6119}
6120
6121QualType ASTContext::getTemplateSpecializationType(
6122 ElaboratedTypeKeyword Keyword, TemplateName Template,
6123 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6124 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6125 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6126 SpecifiedArgVec.reserve(N: SpecifiedArgs.size());
6127 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6128 SpecifiedArgVec.push_back(Elt: Arg.getArgument());
6129
6130 return getTemplateSpecializationType(Keyword, T: Template, SpecifiedArgs: SpecifiedArgVec,
6131 CanonicalArgs, Underlying);
6132}
6133
6134[[maybe_unused]] static bool
6135hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
6136 for (const TemplateArgument &Arg : Args)
6137 if (Arg.isPackExpansion())
6138 return true;
6139 return false;
6140}
6141
6142QualType ASTContext::getCanonicalTemplateSpecializationType(
6143 ElaboratedTypeKeyword Keyword, TemplateName Template,
6144 ArrayRef<TemplateArgument> Args) const {
6145 assert(Template ==
6146 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6147 assert((Keyword == ElaboratedTypeKeyword::None ||
6148 Template.getAsDependentTemplateName()));
6149#ifndef NDEBUG
6150 for (const auto &Arg : Args)
6151 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6152#endif
6153
6154 llvm::FoldingSetNodeID ID;
6155 TemplateSpecializationType::Profile(ID, Keyword, T: Template, Args, Underlying: QualType(),
6156 Context: *this);
6157 void *InsertPos = nullptr;
6158 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6159 return QualType(T, 0);
6160
6161 void *Mem = Allocate(Size: sizeof(TemplateSpecializationType) +
6162 sizeof(TemplateArgument) * Args.size(),
6163 Align: alignof(TemplateSpecializationType));
6164 auto *Spec =
6165 new (Mem) TemplateSpecializationType(Keyword, Template,
6166 /*IsAlias=*/false, Args, QualType());
6167 assert(Spec->isDependentType() &&
6168 "canonical template specialization must be dependent");
6169 Types.push_back(Elt: Spec);
6170 TemplateSpecializationTypes.InsertNode(N: Spec, InsertPos);
6171 return QualType(Spec, 0);
6172}
6173
6174QualType ASTContext::getTemplateSpecializationType(
6175 ElaboratedTypeKeyword Keyword, TemplateName Template,
6176 ArrayRef<TemplateArgument> SpecifiedArgs,
6177 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6178 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6179 bool IsTypeAlias = TD && TD->isTypeAlias();
6180 if (Underlying.isNull()) {
6181 TemplateName CanonTemplate =
6182 getCanonicalTemplateName(Name: Template, /*IgnoreDeduced=*/true);
6183 ElaboratedTypeKeyword CanonKeyword =
6184 CanonTemplate.getAsDependentTemplateName()
6185 ? getCanonicalElaboratedTypeKeyword(Keyword)
6186 : ElaboratedTypeKeyword::None;
6187 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6188 SmallVector<TemplateArgument, 4> CanonArgsVec;
6189 if (CanonicalArgs.empty()) {
6190 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6191 NonCanonical |= canonicalizeTemplateArguments(Args: CanonArgsVec);
6192 CanonicalArgs = CanonArgsVec;
6193 } else {
6194 NonCanonical |= !llvm::equal(
6195 LRange&: SpecifiedArgs, RRange&: CanonicalArgs,
6196 P: [](const TemplateArgument &A, const TemplateArgument &B) {
6197 return A.structurallyEquals(Other: B);
6198 });
6199 }
6200
6201 // We can get here with an alias template when the specialization
6202 // contains a pack expansion that does not match up with a parameter
6203 // pack, or a builtin template which cannot be resolved due to dependency.
6204 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6205 hasAnyPackExpansions(CanonicalArgs)) &&
6206 "Caller must compute aliased type");
6207 IsTypeAlias = false;
6208
6209 Underlying = getCanonicalTemplateSpecializationType(
6210 Keyword: CanonKeyword, Template: CanonTemplate, Args: CanonicalArgs);
6211 if (!NonCanonical)
6212 return Underlying;
6213 }
6214 void *Mem = Allocate(Size: sizeof(TemplateSpecializationType) +
6215 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6216 (IsTypeAlias ? sizeof(QualType) : 0),
6217 Align: alignof(TemplateSpecializationType));
6218 auto *Spec = new (Mem) TemplateSpecializationType(
6219 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6220 Types.push_back(Elt: Spec);
6221 return QualType(Spec, 0);
6222}
6223
6224QualType
6225ASTContext::getParenType(QualType InnerType) const {
6226 llvm::FoldingSetNodeID ID;
6227 ParenType::Profile(ID, Inner: InnerType);
6228
6229 void *InsertPos = nullptr;
6230 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6231 if (T)
6232 return QualType(T, 0);
6233
6234 QualType Canon = InnerType;
6235 if (!Canon.isCanonical()) {
6236 Canon = getCanonicalType(T: InnerType);
6237 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6238 assert(!CheckT && "Paren canonical type broken");
6239 (void)CheckT;
6240 }
6241
6242 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6243 Types.push_back(Elt: T);
6244 ParenTypes.InsertNode(N: T, InsertPos);
6245 return QualType(T, 0);
6246}
6247
6248QualType
6249ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
6250 const IdentifierInfo *MacroII) const {
6251 QualType Canon = UnderlyingTy;
6252 if (!Canon.isCanonical())
6253 Canon = getCanonicalType(T: UnderlyingTy);
6254
6255 auto *newType = new (*this, alignof(MacroQualifiedType))
6256 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6257 Types.push_back(Elt: newType);
6258 return QualType(newType, 0);
6259}
6260
6261QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
6262 NestedNameSpecifier NNS,
6263 const IdentifierInfo *Name) const {
6264 llvm::FoldingSetNodeID ID;
6265 DependentNameType::Profile(ID, Keyword, NNS, Name);
6266
6267 void *InsertPos = nullptr;
6268 if (DependentNameType *T =
6269 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6270 return QualType(T, 0);
6271
6272 ElaboratedTypeKeyword CanonKeyword =
6273 getCanonicalElaboratedTypeKeyword(Keyword);
6274 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6275
6276 QualType Canon;
6277 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6278 Canon = getDependentNameType(Keyword: CanonKeyword, NNS: CanonNNS, Name);
6279 [[maybe_unused]] DependentNameType *T =
6280 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6281 assert(!T && "broken canonicalization");
6282 assert(Canon.isCanonical());
6283 }
6284
6285 DependentNameType *T = new (*this, alignof(DependentNameType))
6286 DependentNameType(Keyword, NNS, Name, Canon);
6287 Types.push_back(Elt: T);
6288 DependentNameTypes.InsertNode(N: T, InsertPos);
6289 return QualType(T, 0);
6290}
6291
6292TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) const {
6293 TemplateArgument Arg;
6294 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
6295 QualType ArgType = getTypeDeclType(Decl: TTP);
6296 if (TTP->isParameterPack())
6297 ArgType = getPackExpansionType(Pattern: ArgType, NumExpansions: std::nullopt);
6298
6299 Arg = TemplateArgument(ArgType);
6300 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
6301 QualType T =
6302 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(Context: *this);
6303 // For class NTTPs, ensure we include the 'const' so the type matches that
6304 // of a real template argument.
6305 // FIXME: It would be more faithful to model this as something like an
6306 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6307 ExprValueKind VK;
6308 if (T->isRecordType()) {
6309 // C++ [temp.param]p8: An id-expression naming a non-type
6310 // template-parameter of class type T denotes a static storage duration
6311 // object of type const T.
6312 T.addConst();
6313 VK = VK_LValue;
6314 } else {
6315 VK = Expr::getValueKindForType(T: NTTP->getType());
6316 }
6317 Expr *E = new (*this)
6318 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6319 T, VK, NTTP->getLocation());
6320
6321 if (NTTP->isParameterPack())
6322 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6323 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6324 } else {
6325 auto *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
6326 TemplateName Name = getQualifiedTemplateName(
6327 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6328 Template: TemplateName(TTP));
6329 if (TTP->isParameterPack())
6330 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6331 else
6332 Arg = TemplateArgument(Name);
6333 }
6334
6335 if (Param->isTemplateParameterPack())
6336 Arg =
6337 TemplateArgument::CreatePackCopy(Context&: const_cast<ASTContext &>(*this), Args: Arg);
6338
6339 return Arg;
6340}
6341
6342QualType ASTContext::getPackExpansionType(QualType Pattern,
6343 UnsignedOrNone NumExpansions,
6344 bool ExpectPackInType) const {
6345 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6346 "Pack expansions must expand one or more parameter packs");
6347
6348 llvm::FoldingSetNodeID ID;
6349 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6350
6351 void *InsertPos = nullptr;
6352 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6353 if (T)
6354 return QualType(T, 0);
6355
6356 QualType Canon;
6357 if (!Pattern.isCanonical()) {
6358 Canon = getPackExpansionType(Pattern: getCanonicalType(T: Pattern), NumExpansions,
6359 /*ExpectPackInType=*/false);
6360
6361 // Find the insert position again, in case we inserted an element into
6362 // PackExpansionTypes and invalidated our insert position.
6363 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6364 }
6365
6366 T = new (*this, alignof(PackExpansionType))
6367 PackExpansionType(Pattern, Canon, NumExpansions);
6368 Types.push_back(Elt: T);
6369 PackExpansionTypes.InsertNode(N: T, InsertPos);
6370 return QualType(T, 0);
6371}
6372
6373/// CmpProtocolNames - Comparison predicate for sorting protocols
6374/// alphabetically.
6375static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6376 ObjCProtocolDecl *const *RHS) {
6377 return DeclarationName::compare(LHS: (*LHS)->getDeclName(), RHS: (*RHS)->getDeclName());
6378}
6379
6380static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
6381 if (Protocols.empty()) return true;
6382
6383 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6384 return false;
6385
6386 for (unsigned i = 1; i != Protocols.size(); ++i)
6387 if (CmpProtocolNames(LHS: &Protocols[i - 1], RHS: &Protocols[i]) >= 0 ||
6388 Protocols[i]->getCanonicalDecl() != Protocols[i])
6389 return false;
6390 return true;
6391}
6392
6393static void
6394SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
6395 // Sort protocols, keyed by name.
6396 llvm::array_pod_sort(Start: Protocols.begin(), End: Protocols.end(), Compare: CmpProtocolNames);
6397
6398 // Canonicalize.
6399 for (ObjCProtocolDecl *&P : Protocols)
6400 P = P->getCanonicalDecl();
6401
6402 // Remove duplicates.
6403 auto ProtocolsEnd = llvm::unique(R&: Protocols);
6404 Protocols.erase(CS: ProtocolsEnd, CE: Protocols.end());
6405}
6406
6407QualType ASTContext::getObjCObjectType(QualType BaseType,
6408 ObjCProtocolDecl * const *Protocols,
6409 unsigned NumProtocols) const {
6410 return getObjCObjectType(Base: BaseType, typeArgs: {}, protocols: ArrayRef(Protocols, NumProtocols),
6411 /*isKindOf=*/false);
6412}
6413
6414QualType ASTContext::getObjCObjectType(
6415 QualType baseType,
6416 ArrayRef<QualType> typeArgs,
6417 ArrayRef<ObjCProtocolDecl *> protocols,
6418 bool isKindOf) const {
6419 // If the base type is an interface and there aren't any protocols or
6420 // type arguments to add, then the interface type will do just fine.
6421 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6422 isa<ObjCInterfaceType>(Val: baseType))
6423 return baseType;
6424
6425 // Look in the folding set for an existing type.
6426 llvm::FoldingSetNodeID ID;
6427 ObjCObjectTypeImpl::Profile(ID, Base: baseType, typeArgs, protocols, isKindOf);
6428 void *InsertPos = nullptr;
6429 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6430 return QualType(QT, 0);
6431
6432 // Determine the type arguments to be used for canonicalization,
6433 // which may be explicitly specified here or written on the base
6434 // type.
6435 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6436 if (effectiveTypeArgs.empty()) {
6437 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6438 effectiveTypeArgs = baseObject->getTypeArgs();
6439 }
6440
6441 // Build the canonical type, which has the canonical base type and a
6442 // sorted-and-uniqued list of protocols and the type arguments
6443 // canonicalized.
6444 QualType canonical;
6445 bool typeArgsAreCanonical = llvm::all_of(
6446 Range&: effectiveTypeArgs, P: [&](QualType type) { return type.isCanonical(); });
6447 bool protocolsSorted = areSortedAndUniqued(Protocols: protocols);
6448 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6449 // Determine the canonical type arguments.
6450 ArrayRef<QualType> canonTypeArgs;
6451 SmallVector<QualType, 4> canonTypeArgsVec;
6452 if (!typeArgsAreCanonical) {
6453 canonTypeArgsVec.reserve(N: effectiveTypeArgs.size());
6454 for (auto typeArg : effectiveTypeArgs)
6455 canonTypeArgsVec.push_back(Elt: getCanonicalType(T: typeArg));
6456 canonTypeArgs = canonTypeArgsVec;
6457 } else {
6458 canonTypeArgs = effectiveTypeArgs;
6459 }
6460
6461 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6462 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6463 if (!protocolsSorted) {
6464 canonProtocolsVec.append(in_start: protocols.begin(), in_end: protocols.end());
6465 SortAndUniqueProtocols(Protocols&: canonProtocolsVec);
6466 canonProtocols = canonProtocolsVec;
6467 } else {
6468 canonProtocols = protocols;
6469 }
6470
6471 canonical = getObjCObjectType(baseType: getCanonicalType(T: baseType), typeArgs: canonTypeArgs,
6472 protocols: canonProtocols, isKindOf);
6473
6474 // Regenerate InsertPos.
6475 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6476 }
6477
6478 unsigned size = sizeof(ObjCObjectTypeImpl);
6479 size += typeArgs.size() * sizeof(QualType);
6480 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6481 void *mem = Allocate(Size: size, Align: alignof(ObjCObjectTypeImpl));
6482 auto *T =
6483 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6484 isKindOf);
6485
6486 Types.push_back(Elt: T);
6487 ObjCObjectTypes.InsertNode(N: T, InsertPos);
6488 return QualType(T, 0);
6489}
6490
6491/// Apply Objective-C protocol qualifiers to the given type.
6492/// If this is for the canonical type of a type parameter, we can apply
6493/// protocol qualifiers on the ObjCObjectPointerType.
6494QualType
6495ASTContext::applyObjCProtocolQualifiers(QualType type,
6496 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6497 bool allowOnPointerType) const {
6498 hasError = false;
6499
6500 if (const auto *objT = dyn_cast<ObjCTypeParamType>(Val: type.getTypePtr())) {
6501 return getObjCTypeParamType(Decl: objT->getDecl(), protocols);
6502 }
6503
6504 // Apply protocol qualifiers to ObjCObjectPointerType.
6505 if (allowOnPointerType) {
6506 if (const auto *objPtr =
6507 dyn_cast<ObjCObjectPointerType>(Val: type.getTypePtr())) {
6508 const ObjCObjectType *objT = objPtr->getObjectType();
6509 // Merge protocol lists and construct ObjCObjectType.
6510 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
6511 protocolsVec.append(in_start: objT->qual_begin(),
6512 in_end: objT->qual_end());
6513 protocolsVec.append(in_start: protocols.begin(), in_end: protocols.end());
6514 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6515 type = getObjCObjectType(
6516 baseType: objT->getBaseType(),
6517 typeArgs: objT->getTypeArgsAsWritten(),
6518 protocols,
6519 isKindOf: objT->isKindOfTypeAsWritten());
6520 return getObjCObjectPointerType(OIT: type);
6521 }
6522 }
6523
6524 // Apply protocol qualifiers to ObjCObjectType.
6525 if (const auto *objT = dyn_cast<ObjCObjectType>(Val: type.getTypePtr())){
6526 // FIXME: Check for protocols to which the class type is already
6527 // known to conform.
6528
6529 return getObjCObjectType(baseType: objT->getBaseType(),
6530 typeArgs: objT->getTypeArgsAsWritten(),
6531 protocols,
6532 isKindOf: objT->isKindOfTypeAsWritten());
6533 }
6534
6535 // If the canonical type is ObjCObjectType, ...
6536 if (type->isObjCObjectType()) {
6537 // Silently overwrite any existing protocol qualifiers.
6538 // TODO: determine whether that's the right thing to do.
6539
6540 // FIXME: Check for protocols to which the class type is already
6541 // known to conform.
6542 return getObjCObjectType(baseType: type, typeArgs: {}, protocols, isKindOf: false);
6543 }
6544
6545 // id<protocol-list>
6546 if (type->isObjCIdType()) {
6547 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6548 type = getObjCObjectType(baseType: ObjCBuiltinIdTy, typeArgs: {}, protocols,
6549 isKindOf: objPtr->isKindOfType());
6550 return getObjCObjectPointerType(OIT: type);
6551 }
6552
6553 // Class<protocol-list>
6554 if (type->isObjCClassType()) {
6555 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6556 type = getObjCObjectType(baseType: ObjCBuiltinClassTy, typeArgs: {}, protocols,
6557 isKindOf: objPtr->isKindOfType());
6558 return getObjCObjectPointerType(OIT: type);
6559 }
6560
6561 hasError = true;
6562 return type;
6563}
6564
6565QualType
6566ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
6567 ArrayRef<ObjCProtocolDecl *> protocols) const {
6568 // Look in the folding set for an existing type.
6569 llvm::FoldingSetNodeID ID;
6570 ObjCTypeParamType::Profile(ID, OTPDecl: Decl, CanonicalType: Decl->getUnderlyingType(), protocols);
6571 void *InsertPos = nullptr;
6572 if (ObjCTypeParamType *TypeParam =
6573 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6574 return QualType(TypeParam, 0);
6575
6576 // We canonicalize to the underlying type.
6577 QualType Canonical = getCanonicalType(T: Decl->getUnderlyingType());
6578 if (!protocols.empty()) {
6579 // Apply the protocol qualifers.
6580 bool hasError;
6581 Canonical = getCanonicalType(T: applyObjCProtocolQualifiers(
6582 type: Canonical, protocols, hasError, allowOnPointerType: true /*allowOnPointerType*/));
6583 assert(!hasError && "Error when apply protocol qualifier to bound type");
6584 }
6585
6586 unsigned size = sizeof(ObjCTypeParamType);
6587 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6588 void *mem = Allocate(Size: size, Align: alignof(ObjCTypeParamType));
6589 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6590
6591 Types.push_back(Elt: newType);
6592 ObjCTypeParamTypes.InsertNode(N: newType, InsertPos);
6593 return QualType(newType, 0);
6594}
6595
6596void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
6597 ObjCTypeParamDecl *New) const {
6598 New->setTypeSourceInfo(getTrivialTypeSourceInfo(T: Orig->getUnderlyingType()));
6599 // Update TypeForDecl after updating TypeSourceInfo.
6600 auto *NewTypeParamTy = cast<ObjCTypeParamType>(Val: New->TypeForDecl);
6601 SmallVector<ObjCProtocolDecl *, 8> protocols;
6602 protocols.append(in_start: NewTypeParamTy->qual_begin(), in_end: NewTypeParamTy->qual_end());
6603 QualType UpdatedTy = getObjCTypeParamType(Decl: New, protocols);
6604 New->TypeForDecl = UpdatedTy.getTypePtr();
6605}
6606
6607/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6608/// protocol list adopt all protocols in QT's qualified-id protocol
6609/// list.
6610bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
6611 ObjCInterfaceDecl *IC) {
6612 if (!QT->isObjCQualifiedIdType())
6613 return false;
6614
6615 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6616 // If both the right and left sides have qualifiers.
6617 for (auto *Proto : OPT->quals()) {
6618 if (!IC->ClassImplementsProtocol(lProto: Proto, lookupCategory: false))
6619 return false;
6620 }
6621 return true;
6622 }
6623 return false;
6624}
6625
6626/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6627/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6628/// of protocols.
6629bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
6630 ObjCInterfaceDecl *IDecl) {
6631 if (!QT->isObjCQualifiedIdType())
6632 return false;
6633 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6634 if (!OPT)
6635 return false;
6636 if (!IDecl->hasDefinition())
6637 return false;
6638 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
6639 CollectInheritedProtocols(CDecl: IDecl, Protocols&: InheritedProtocols);
6640 if (InheritedProtocols.empty())
6641 return false;
6642 // Check that if every protocol in list of id<plist> conforms to a protocol
6643 // of IDecl's, then bridge casting is ok.
6644 bool Conforms = false;
6645 for (auto *Proto : OPT->quals()) {
6646 Conforms = false;
6647 for (auto *PI : InheritedProtocols) {
6648 if (ProtocolCompatibleWithProtocol(lProto: Proto, rProto: PI)) {
6649 Conforms = true;
6650 break;
6651 }
6652 }
6653 if (!Conforms)
6654 break;
6655 }
6656 if (Conforms)
6657 return true;
6658
6659 for (auto *PI : InheritedProtocols) {
6660 // If both the right and left sides have qualifiers.
6661 bool Adopts = false;
6662 for (auto *Proto : OPT->quals()) {
6663 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6664 if ((Adopts = ProtocolCompatibleWithProtocol(lProto: PI, rProto: Proto)))
6665 break;
6666 }
6667 if (!Adopts)
6668 return false;
6669 }
6670 return true;
6671}
6672
6673/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6674/// the given object type.
6675QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
6676 llvm::FoldingSetNodeID ID;
6677 ObjCObjectPointerType::Profile(ID, T: ObjectT);
6678
6679 void *InsertPos = nullptr;
6680 if (ObjCObjectPointerType *QT =
6681 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6682 return QualType(QT, 0);
6683
6684 // Find the canonical object type.
6685 QualType Canonical;
6686 if (!ObjectT.isCanonical()) {
6687 Canonical = getObjCObjectPointerType(ObjectT: getCanonicalType(T: ObjectT));
6688
6689 // Regenerate InsertPos.
6690 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6691 }
6692
6693 // No match.
6694 void *Mem =
6695 Allocate(Size: sizeof(ObjCObjectPointerType), Align: alignof(ObjCObjectPointerType));
6696 auto *QType =
6697 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6698
6699 Types.push_back(Elt: QType);
6700 ObjCObjectPointerTypes.InsertNode(N: QType, InsertPos);
6701 return QualType(QType, 0);
6702}
6703
6704/// getObjCInterfaceType - Return the unique reference to the type for the
6705/// specified ObjC interface decl. The list of protocols is optional.
6706QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
6707 ObjCInterfaceDecl *PrevDecl) const {
6708 if (Decl->TypeForDecl)
6709 return QualType(Decl->TypeForDecl, 0);
6710
6711 if (PrevDecl) {
6712 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6713 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6714 return QualType(PrevDecl->TypeForDecl, 0);
6715 }
6716
6717 // Prefer the definition, if there is one.
6718 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6719 Decl = Def;
6720
6721 void *Mem = Allocate(Size: sizeof(ObjCInterfaceType), Align: alignof(ObjCInterfaceType));
6722 auto *T = new (Mem) ObjCInterfaceType(Decl);
6723 Decl->TypeForDecl = T;
6724 Types.push_back(Elt: T);
6725 return QualType(T, 0);
6726}
6727
6728/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6729/// TypeOfExprType AST's (since expression's are never shared). For example,
6730/// multiple declarations that refer to "typeof(x)" all contain different
6731/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6732/// on canonical type's (which are always unique).
6733QualType ASTContext::getTypeOfExprType(Expr *tofExpr, TypeOfKind Kind) const {
6734 TypeOfExprType *toe;
6735 if (tofExpr->isTypeDependent()) {
6736 llvm::FoldingSetNodeID ID;
6737 DependentTypeOfExprType::Profile(ID, Context: *this, E: tofExpr,
6738 IsUnqual: Kind == TypeOfKind::Unqualified);
6739
6740 void *InsertPos = nullptr;
6741 DependentTypeOfExprType *Canon =
6742 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6743 if (Canon) {
6744 // We already have a "canonical" version of an identical, dependent
6745 // typeof(expr) type. Use that as our canonical type.
6746 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6747 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6748 } else {
6749 // Build a new, canonical typeof(expr) type.
6750 Canon = new (*this, alignof(DependentTypeOfExprType))
6751 DependentTypeOfExprType(*this, tofExpr, Kind);
6752 DependentTypeOfExprTypes.InsertNode(N: Canon, InsertPos);
6753 toe = Canon;
6754 }
6755 } else {
6756 QualType Canonical = getCanonicalType(T: tofExpr->getType());
6757 toe = new (*this, alignof(TypeOfExprType))
6758 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6759 }
6760 Types.push_back(Elt: toe);
6761 return QualType(toe, 0);
6762}
6763
6764/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6765/// TypeOfType nodes. The only motivation to unique these nodes would be
6766/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6767/// an issue. This doesn't affect the type checker, since it operates
6768/// on canonical types (which are always unique).
6769QualType ASTContext::getTypeOfType(QualType tofType, TypeOfKind Kind) const {
6770 QualType Canonical = getCanonicalType(T: tofType);
6771 auto *tot = new (*this, alignof(TypeOfType))
6772 TypeOfType(*this, tofType, Canonical, Kind);
6773 Types.push_back(Elt: tot);
6774 return QualType(tot, 0);
6775}
6776
6777/// getReferenceQualifiedType - Given an expr, will return the type for
6778/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6779/// and class member access into account.
6780QualType ASTContext::getReferenceQualifiedType(const Expr *E) const {
6781 // C++11 [dcl.type.simple]p4:
6782 // [...]
6783 QualType T = E->getType();
6784 switch (E->getValueKind()) {
6785 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6786 // type of e;
6787 case VK_XValue:
6788 return getRValueReferenceType(T);
6789 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6790 // type of e;
6791 case VK_LValue:
6792 return getLValueReferenceType(T);
6793 // - otherwise, decltype(e) is the type of e.
6794 case VK_PRValue:
6795 return T;
6796 }
6797 llvm_unreachable("Unknown value kind");
6798}
6799
6800/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6801/// nodes. This would never be helpful, since each such type has its own
6802/// expression, and would not give a significant memory saving, since there
6803/// is an Expr tree under each such type.
6804QualType ASTContext::getDecltypeType(Expr *E, QualType UnderlyingType) const {
6805 // C++11 [temp.type]p2:
6806 // If an expression e involves a template parameter, decltype(e) denotes a
6807 // unique dependent type. Two such decltype-specifiers refer to the same
6808 // type only if their expressions are equivalent (14.5.6.1).
6809 QualType CanonType;
6810 if (!E->isInstantiationDependent()) {
6811 CanonType = getCanonicalType(T: UnderlyingType);
6812 } else if (!UnderlyingType.isNull()) {
6813 CanonType = getDecltypeType(E, UnderlyingType: QualType());
6814 } else {
6815 llvm::FoldingSetNodeID ID;
6816 DependentDecltypeType::Profile(ID, Context: *this, E);
6817
6818 void *InsertPos = nullptr;
6819 if (DependentDecltypeType *Canon =
6820 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6821 return QualType(Canon, 0);
6822
6823 // Build a new, canonical decltype(expr) type.
6824 auto *DT =
6825 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6826 DependentDecltypeTypes.InsertNode(N: DT, InsertPos);
6827 Types.push_back(Elt: DT);
6828 return QualType(DT, 0);
6829 }
6830 auto *DT = new (*this, alignof(DecltypeType))
6831 DecltypeType(E, UnderlyingType, CanonType);
6832 Types.push_back(Elt: DT);
6833 return QualType(DT, 0);
6834}
6835
6836QualType ASTContext::getPackIndexingType(QualType Pattern, Expr *IndexExpr,
6837 bool FullySubstituted,
6838 ArrayRef<QualType> Expansions,
6839 UnsignedOrNone Index) const {
6840 QualType Canonical;
6841 if (FullySubstituted && Index) {
6842 Canonical = getCanonicalType(T: Expansions[*Index]);
6843 } else {
6844 llvm::FoldingSetNodeID ID;
6845 PackIndexingType::Profile(ID, Context: *this, Pattern: Pattern.getCanonicalType(), E: IndexExpr,
6846 FullySubstituted, Expansions);
6847 void *InsertPos = nullptr;
6848 PackIndexingType *Canon =
6849 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6850 if (!Canon) {
6851 void *Mem = Allocate(
6852 Size: PackIndexingType::totalSizeToAlloc<QualType>(Counts: Expansions.size()),
6853 Align: TypeAlignment);
6854 Canon =
6855 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6856 IndexExpr, FullySubstituted, Expansions);
6857 DependentPackIndexingTypes.InsertNode(N: Canon, InsertPos);
6858 }
6859 Canonical = QualType(Canon, 0);
6860 }
6861
6862 void *Mem =
6863 Allocate(Size: PackIndexingType::totalSizeToAlloc<QualType>(Counts: Expansions.size()),
6864 Align: TypeAlignment);
6865 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6866 FullySubstituted, Expansions);
6867 Types.push_back(Elt: T);
6868 return QualType(T, 0);
6869}
6870
6871/// getUnaryTransformationType - We don't unique these, since the memory
6872/// savings are minimal and these are rare.
6873QualType
6874ASTContext::getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
6875 UnaryTransformType::UTTKind Kind) const {
6876
6877 llvm::FoldingSetNodeID ID;
6878 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, UKind: Kind);
6879
6880 void *InsertPos = nullptr;
6881 if (UnaryTransformType *UT =
6882 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6883 return QualType(UT, 0);
6884
6885 QualType CanonType;
6886 if (!BaseType->isDependentType()) {
6887 CanonType = UnderlyingType.getCanonicalType();
6888 } else {
6889 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6890 UnderlyingType = QualType();
6891 if (QualType CanonBase = BaseType.getCanonicalType();
6892 BaseType != CanonBase) {
6893 CanonType = getUnaryTransformType(BaseType: CanonBase, UnderlyingType: QualType(), Kind);
6894 assert(CanonType.isCanonical());
6895
6896 // Find the insertion position again.
6897 [[maybe_unused]] UnaryTransformType *UT =
6898 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6899 assert(!UT && "broken canonicalization");
6900 }
6901 }
6902
6903 auto *UT = new (*this, alignof(UnaryTransformType))
6904 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6905 UnaryTransformTypes.InsertNode(N: UT, InsertPos);
6906 Types.push_back(Elt: UT);
6907 return QualType(UT, 0);
6908}
6909
6910/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6911/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6912/// canonical deduced-but-dependent 'auto' type.
6913QualType
6914ASTContext::getAutoType(DeducedKind DK, QualType DeducedAsType,
6915 AutoTypeKeyword Keyword,
6916 TemplateName TypeConstraintConcept,
6917 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6918 if (DK == DeducedKind::Undeduced && Keyword == AutoTypeKeyword::Auto &&
6919 TypeConstraintConcept.isNull()) {
6920 assert(DeducedAsType.isNull() && "");
6921 assert(TypeConstraintArgs.empty() && "");
6922 return getAutoDeductType();
6923 }
6924
6925 // Look in the folding set for an existing type.
6926 llvm::FoldingSetNodeID ID;
6927 AutoType::Profile(ID, Context: *this, DK, Deduced: DeducedAsType, Keyword,
6928 CD: TypeConstraintConcept, Arguments: TypeConstraintArgs);
6929 if (auto const AT_iter = AutoTypes.find_as(Val: ID); AT_iter != AutoTypes.end())
6930 return QualType(AT_iter->getSecond(), 0);
6931
6932 if (DK == DeducedKind::Deduced) {
6933 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6934 } else {
6935 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6936 if (!TypeConstraintConcept.isNull()) {
6937 bool AnyNonCanonArgs = false;
6938 TemplateName CanonicalConcept =
6939 getCanonicalTemplateName(Name: TypeConstraintConcept);
6940 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6941 C: *this, Args: TypeConstraintArgs, AnyNonCanonArgs);
6942 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6943 DeducedAsType = getAutoType(DK, DeducedAsType: QualType(), Keyword, TypeConstraintConcept: CanonicalConcept,
6944 TypeConstraintArgs: CanonicalConceptArgs);
6945 }
6946 }
6947
6948 void *Mem = Allocate(Size: sizeof(AutoType) +
6949 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6950 Align: alignof(AutoType));
6951 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6952 TypeConstraintConcept, TypeConstraintArgs);
6953#ifndef NDEBUG
6954 llvm::FoldingSetNodeID InsertedID;
6955 AT->Profile(InsertedID, *this);
6956 assert(InsertedID == ID && "ID does not match");
6957#endif
6958 Types.push_back(Elt: AT);
6959 AutoTypes.try_emplace(Key: ID.Intern(Allocator&: BumpAlloc), Args&: AT);
6960 return QualType(AT, 0);
6961}
6962
6963QualType ASTContext::getUnconstrainedType(QualType T) const {
6964 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6965
6966 // Remove a type-constraint from a top-level auto or decltype(auto).
6967 if (auto *AT = CanonT->getAs<AutoType>()) {
6968 if (!AT->isConstrained())
6969 return T;
6970 return getQualifiedType(
6971 T: getAutoType(DK: AT->getDeducedKind(), DeducedAsType: QualType(), Keyword: AT->getKeyword()),
6972 Qs: T.getQualifiers());
6973 }
6974
6975 // FIXME: We only support constrained auto at the top level in the type of a
6976 // non-type template parameter at the moment. Once we lift that restriction,
6977 // we'll need to recursively build types containing auto here.
6978 assert(!CanonT->getContainedAutoType() ||
6979 !CanonT->getContainedAutoType()->isConstrained());
6980 return T;
6981}
6982
6983/// Return the uniqued reference to the deduced template specialization type
6984/// which has been deduced to the given type, or to the canonical undeduced
6985/// such type, or the canonical deduced-but-dependent such type.
6986QualType ASTContext::getDeducedTemplateSpecializationType(
6987 DeducedKind DK, QualType DeducedAsType, ElaboratedTypeKeyword Keyword,
6988 TemplateName Template) const {
6989 // Look in the folding set for an existing type.
6990 void *InsertPos = nullptr;
6991 llvm::FoldingSetNodeID ID;
6992 DeducedTemplateSpecializationType::Profile(ID, DK, Deduced: DeducedAsType, Keyword,
6993 Template);
6994 if (DeducedTemplateSpecializationType *DTST =
6995 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6996 return QualType(DTST, 0);
6997
6998 if (DK == DeducedKind::Deduced) {
6999 assert(!DeducedAsType.isNull() && "deduced type must be provided");
7000 } else {
7001 assert(DeducedAsType.isNull() && "deduced type must not be provided");
7002 TemplateName CanonTemplateName = getCanonicalTemplateName(Name: Template);
7003 // FIXME: Can this be formed from a DependentTemplateName, such that the
7004 // keyword should be part of the canonical type?
7005 if (Keyword != ElaboratedTypeKeyword::None ||
7006 Template != CanonTemplateName) {
7007 DeducedAsType = getDeducedTemplateSpecializationType(
7008 DK, DeducedAsType: QualType(), Keyword: ElaboratedTypeKeyword::None, Template: CanonTemplateName);
7009 // Find the insertion position again.
7010 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
7011 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
7012 assert(!DTST && "broken canonicalization");
7013 }
7014 }
7015
7016 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
7017 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
7018
7019#ifndef NDEBUG
7020 llvm::FoldingSetNodeID TempID;
7021 DTST->Profile(TempID);
7022 assert(ID == TempID && "ID does not match");
7023#endif
7024 Types.push_back(Elt: DTST);
7025 DeducedTemplateSpecializationTypes.InsertNode(N: DTST, InsertPos);
7026 return QualType(DTST, 0);
7027}
7028
7029/// getAtomicType - Return the uniqued reference to the atomic type for
7030/// the given value type.
7031QualType ASTContext::getAtomicType(QualType T) const {
7032 // Unique pointers, to guarantee there is only one pointer of a particular
7033 // structure.
7034 llvm::FoldingSetNodeID ID;
7035 AtomicType::Profile(ID, T);
7036
7037 void *InsertPos = nullptr;
7038 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
7039 return QualType(AT, 0);
7040
7041 // If the atomic value type isn't canonical, this won't be a canonical type
7042 // either, so fill in the canonical type field.
7043 QualType Canonical;
7044 if (!T.isCanonical()) {
7045 Canonical = getAtomicType(T: getCanonicalType(T));
7046
7047 // Get the new insert position for the node we care about.
7048 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
7049 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
7050 }
7051 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
7052 Types.push_back(Elt: New);
7053 AtomicTypes.InsertNode(N: New, InsertPos);
7054 return QualType(New, 0);
7055}
7056
7057/// getAutoDeductType - Get type pattern for deducing against 'auto'.
7058QualType ASTContext::getAutoDeductType() const {
7059 if (AutoDeductTy.isNull())
7060 AutoDeductTy = QualType(
7061 new (*this, alignof(AutoType))
7062 AutoType(DeducedKind::Undeduced, QualType(), AutoTypeKeyword::Auto,
7063 /*TypeConstraintConcept=*/TemplateName(),
7064 /*TypeConstraintArgs=*/{}),
7065 0);
7066 return AutoDeductTy;
7067}
7068
7069/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7070QualType ASTContext::getAutoRRefDeductType() const {
7071 if (AutoRRefDeductTy.isNull())
7072 AutoRRefDeductTy = getRValueReferenceType(T: getAutoDeductType());
7073 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7074 return AutoRRefDeductTy;
7075}
7076
7077/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7078/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7079/// needs to agree with the definition in <stddef.h>.
7080QualType ASTContext::getSizeType() const {
7081 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::SizeT);
7082}
7083
7084CanQualType ASTContext::getCanonicalSizeType() const {
7085 return getFromTargetType(Type: Target->getSizeType());
7086}
7087
7088/// Return the unique signed counterpart of the integer type
7089/// corresponding to size_t.
7090QualType ASTContext::getSignedSizeType() const {
7091 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::SignedSizeT);
7092}
7093
7094/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7095/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7096QualType ASTContext::getPointerDiffType() const {
7097 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::PtrdiffT);
7098}
7099
7100/// Return the unique unsigned counterpart of "ptrdiff_t"
7101/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7102/// in the definition of %tu format specifier.
7103QualType ASTContext::getUnsignedPointerDiffType() const {
7104 return getFromTargetType(Type: Target->getUnsignedPtrDiffType(AddrSpace: LangAS::Default));
7105}
7106
7107/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7108CanQualType ASTContext::getIntMaxType() const {
7109 return getFromTargetType(Type: Target->getIntMaxType());
7110}
7111
7112/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7113CanQualType ASTContext::getUIntMaxType() const {
7114 return getFromTargetType(Type: Target->getUIntMaxType());
7115}
7116
7117/// getSignedWCharType - Return the type of "signed wchar_t".
7118/// Used when in C++, as a GCC extension.
7119QualType ASTContext::getSignedWCharType() const {
7120 // FIXME: derive from "Target" ?
7121 return WCharTy;
7122}
7123
7124/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7125/// Used when in C++, as a GCC extension.
7126QualType ASTContext::getUnsignedWCharType() const {
7127 // FIXME: derive from "Target" ?
7128 return UnsignedIntTy;
7129}
7130
7131QualType ASTContext::getIntPtrType() const {
7132 return getFromTargetType(Type: Target->getIntPtrType());
7133}
7134
7135QualType ASTContext::getUIntPtrType() const {
7136 return getCorrespondingUnsignedType(T: getIntPtrType());
7137}
7138
7139/// Return the unique type for "pid_t" defined in
7140/// <sys/types.h>. We need this to compute the correct type for vfork().
7141QualType ASTContext::getProcessIDType() const {
7142 return getFromTargetType(Type: Target->getProcessIDType());
7143}
7144
7145//===----------------------------------------------------------------------===//
7146// Type Operators
7147//===----------------------------------------------------------------------===//
7148
7149CanQualType ASTContext::getCanonicalParamType(QualType T) const {
7150 // Push qualifiers into arrays, and then discard any remaining
7151 // qualifiers.
7152 T = getCanonicalType(T);
7153 T = getVariableArrayDecayedType(type: T);
7154 const Type *Ty = T.getTypePtr();
7155 QualType Result;
7156 if (getLangOpts().HLSL && isa<ConstantArrayType>(Val: Ty)) {
7157 Result = getArrayParameterType(Ty: QualType(Ty, 0));
7158 } else if (isa<ArrayType>(Val: Ty)) {
7159 Result = getArrayDecayedType(T: QualType(Ty,0));
7160 } else if (isa<FunctionType>(Val: Ty)) {
7161 Result = getPointerType(T: QualType(Ty, 0));
7162 } else {
7163 Result = QualType(Ty, 0);
7164 }
7165
7166 return CanQualType::CreateUnsafe(Other: Result);
7167}
7168
7169QualType ASTContext::getUnqualifiedArrayType(QualType type,
7170 Qualifiers &quals) const {
7171 SplitQualType splitType = type.getSplitUnqualifiedType();
7172
7173 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7174 // the unqualified desugared type and then drops it on the floor.
7175 // We then have to strip that sugar back off with
7176 // getUnqualifiedDesugaredType(), which is silly.
7177 const auto *AT =
7178 dyn_cast<ArrayType>(Val: splitType.Ty->getUnqualifiedDesugaredType());
7179
7180 // If we don't have an array, just use the results in splitType.
7181 if (!AT) {
7182 quals = splitType.Quals;
7183 return QualType(splitType.Ty, 0);
7184 }
7185
7186 // Otherwise, recurse on the array's element type.
7187 QualType elementType = AT->getElementType();
7188 QualType unqualElementType = getUnqualifiedArrayType(type: elementType, quals);
7189
7190 // If that didn't change the element type, AT has no qualifiers, so we
7191 // can just use the results in splitType.
7192 if (elementType == unqualElementType) {
7193 assert(quals.empty()); // from the recursive call
7194 quals = splitType.Quals;
7195 return QualType(splitType.Ty, 0);
7196 }
7197
7198 // Otherwise, add in the qualifiers from the outermost type, then
7199 // build the type back up.
7200 quals.addConsistentQualifiers(qs: splitType.Quals);
7201
7202 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT)) {
7203 return getConstantArrayType(EltTy: unqualElementType, ArySizeIn: CAT->getSize(),
7204 SizeExpr: CAT->getSizeExpr(), ASM: CAT->getSizeModifier(), IndexTypeQuals: 0);
7205 }
7206
7207 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT)) {
7208 return getIncompleteArrayType(elementType: unqualElementType, ASM: IAT->getSizeModifier(), elementTypeQuals: 0);
7209 }
7210
7211 if (const auto *VAT = dyn_cast<VariableArrayType>(Val: AT)) {
7212 return getVariableArrayType(EltTy: unqualElementType, NumElts: VAT->getSizeExpr(),
7213 ASM: VAT->getSizeModifier(),
7214 IndexTypeQuals: VAT->getIndexTypeCVRQualifiers());
7215 }
7216
7217 const auto *DSAT = cast<DependentSizedArrayType>(Val: AT);
7218 return getDependentSizedArrayType(elementType: unqualElementType, numElements: DSAT->getSizeExpr(),
7219 ASM: DSAT->getSizeModifier(), elementTypeQuals: 0);
7220}
7221
7222/// Attempt to unwrap two types that may both be array types with the same bound
7223/// (or both be array types of unknown bound) for the purpose of comparing the
7224/// cv-decomposition of two types per C++ [conv.qual].
7225///
7226/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7227/// C++20 [conv.qual], if permitted by the current language mode.
7228void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
7229 bool AllowPiMismatch) const {
7230 while (true) {
7231 auto *AT1 = getAsArrayType(T: T1);
7232 if (!AT1)
7233 return;
7234
7235 auto *AT2 = getAsArrayType(T: T2);
7236 if (!AT2)
7237 return;
7238
7239 // If we don't have two array types with the same constant bound nor two
7240 // incomplete array types, we've unwrapped everything we can.
7241 // C++20 also permits one type to be a constant array type and the other
7242 // to be an incomplete array type.
7243 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7244 if (auto *CAT1 = dyn_cast<ConstantArrayType>(Val: AT1)) {
7245 auto *CAT2 = dyn_cast<ConstantArrayType>(Val: AT2);
7246 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7247 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7248 isa<IncompleteArrayType>(Val: AT2))))
7249 return;
7250 } else if (isa<IncompleteArrayType>(Val: AT1)) {
7251 if (!(isa<IncompleteArrayType>(Val: AT2) ||
7252 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7253 isa<ConstantArrayType>(Val: AT2))))
7254 return;
7255 } else {
7256 return;
7257 }
7258
7259 T1 = AT1->getElementType();
7260 T2 = AT2->getElementType();
7261 }
7262}
7263
7264/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7265///
7266/// If T1 and T2 are both pointer types of the same kind, or both array types
7267/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7268/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7269///
7270/// This function will typically be called in a loop that successively
7271/// "unwraps" pointer and pointer-to-member types to compare them at each
7272/// level.
7273///
7274/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7275/// C++20 [conv.qual], if permitted by the current language mode.
7276///
7277/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7278/// pair of types that can't be unwrapped further.
7279bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2,
7280 bool AllowPiMismatch) const {
7281 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7282
7283 const auto *T1PtrType = T1->getAs<PointerType>();
7284 const auto *T2PtrType = T2->getAs<PointerType>();
7285 if (T1PtrType && T2PtrType) {
7286 T1 = T1PtrType->getPointeeType();
7287 T2 = T2PtrType->getPointeeType();
7288 return true;
7289 }
7290
7291 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7292 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7293 T1MPType && T2MPType) {
7294 // Compare the qualifiers of the canonical type, as the non-canonical type
7295 // may have qualifiers pointing to a base or derived class.
7296 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7297 return false;
7298 // Get the pointee types of the non-canonical type, in order to preserve
7299 // their sugar.
7300 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7301 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7302 return true;
7303 }
7304
7305 if (getLangOpts().ObjC) {
7306 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7307 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7308 if (T1OPType && T2OPType) {
7309 T1 = T1OPType->getPointeeType();
7310 T2 = T2OPType->getPointeeType();
7311 return true;
7312 }
7313 }
7314
7315 // FIXME: Block pointers, too?
7316
7317 return false;
7318}
7319
7320bool ASTContext::hasSimilarType(QualType T1, QualType T2) const {
7321 while (true) {
7322 Qualifiers Quals;
7323 T1 = getUnqualifiedArrayType(type: T1, quals&: Quals);
7324 T2 = getUnqualifiedArrayType(type: T2, quals&: Quals);
7325 if (hasSameType(T1, T2))
7326 return true;
7327 if (!UnwrapSimilarTypes(T1, T2))
7328 return false;
7329 }
7330}
7331
7332bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
7333 while (true) {
7334 Qualifiers Quals1, Quals2;
7335 T1 = getUnqualifiedArrayType(type: T1, quals&: Quals1);
7336 T2 = getUnqualifiedArrayType(type: T2, quals&: Quals2);
7337
7338 Quals1.removeCVRQualifiers();
7339 Quals2.removeCVRQualifiers();
7340 if (Quals1 != Quals2)
7341 return false;
7342
7343 if (hasSameType(T1, T2))
7344 return true;
7345
7346 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7347 return false;
7348 }
7349}
7350
7351DeclarationNameInfo
7352ASTContext::getNameForTemplate(TemplateName Name,
7353 SourceLocation NameLoc) const {
7354 switch (Name.getKind()) {
7355 case TemplateName::QualifiedTemplate:
7356 case TemplateName::Template:
7357 // DNInfo work in progress: CHECKME: what about DNLoc?
7358 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
7359 NameLoc);
7360
7361 case TemplateName::OverloadedTemplate: {
7362 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
7363 // DNInfo work in progress: CHECKME: what about DNLoc?
7364 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7365 }
7366
7367 case TemplateName::AssumedTemplate: {
7368 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
7369 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7370 }
7371
7372 case TemplateName::DependentTemplate: {
7373 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7374 IdentifierOrOverloadedOperator TN = DTN->getName();
7375 DeclarationName DName;
7376 if (const IdentifierInfo *II = TN.getIdentifier()) {
7377 DName = DeclarationNames.getIdentifier(ID: II);
7378 return DeclarationNameInfo(DName, NameLoc);
7379 } else {
7380 DName = DeclarationNames.getCXXOperatorName(Op: TN.getOperator());
7381 // DNInfo work in progress: FIXME: source locations?
7382 DeclarationNameLoc DNLoc =
7383 DeclarationNameLoc::makeCXXOperatorNameLoc(Range: SourceRange());
7384 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7385 }
7386 }
7387
7388 case TemplateName::SubstTemplateTemplateParm: {
7389 SubstTemplateTemplateParmStorage *subst
7390 = Name.getAsSubstTemplateTemplateParm();
7391 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7392 NameLoc);
7393 }
7394
7395 case TemplateName::SubstTemplateTemplateParmPack: {
7396 SubstTemplateTemplateParmPackStorage *subst
7397 = Name.getAsSubstTemplateTemplateParmPack();
7398 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
7399 NameLoc);
7400 }
7401 case TemplateName::UsingTemplate:
7402 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
7403 NameLoc);
7404 case TemplateName::DeducedTemplate: {
7405 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7406 return getNameForTemplate(Name: DTS->getUnderlying(), NameLoc);
7407 }
7408 case TemplateName::PackIndexingTemplate: {
7409 PackIndexingTemplateStorage *PI = Name.getAsPackIndexingTemplate();
7410 return getNameForTemplate(Name: PI->getPattern(), NameLoc);
7411 }
7412 }
7413
7414 llvm_unreachable("bad template name kind!");
7415}
7416
7417const TemplateArgument *
7418ASTContext::getDefaultTemplateArgumentOrNone(const NamedDecl *P) const {
7419 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7420 if (!TP->hasDefaultArgument())
7421 return nullptr;
7422 return &TP->getDefaultArgument().getArgument();
7423 };
7424 switch (P->getKind()) {
7425 case NamedDecl::TemplateTypeParm:
7426 return handleParam(cast<TemplateTypeParmDecl>(Val: P));
7427 case NamedDecl::NonTypeTemplateParm:
7428 return handleParam(cast<NonTypeTemplateParmDecl>(Val: P));
7429 case NamedDecl::TemplateTemplateParm:
7430 return handleParam(cast<TemplateTemplateParmDecl>(Val: P));
7431 default:
7432 llvm_unreachable("Unexpected template parameter kind");
7433 }
7434}
7435
7436TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name,
7437 bool IgnoreDeduced) const {
7438 while (std::optional<TemplateName> UnderlyingOrNone =
7439 Name.desugar(IgnoreDeduced))
7440 Name = *UnderlyingOrNone;
7441
7442 switch (Name.getKind()) {
7443 case TemplateName::Template: {
7444 TemplateDecl *Template = Name.getAsTemplateDecl();
7445 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: Template))
7446 Template = getCanonicalTemplateTemplateParmDecl(TTP);
7447
7448 // The canonical template name is the canonical template declaration.
7449 return TemplateName(cast<TemplateDecl>(Val: Template->getCanonicalDecl()));
7450 }
7451
7452 case TemplateName::AssumedTemplate:
7453 // An assumed template is just a name, so it is already canonical.
7454 return Name;
7455
7456 case TemplateName::OverloadedTemplate:
7457 llvm_unreachable("cannot canonicalize overloaded template");
7458
7459 case TemplateName::DependentTemplate: {
7460 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7461 assert(DTN && "Non-dependent template names must refer to template decls.");
7462 NestedNameSpecifier Qualifier = DTN->getQualifier();
7463 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7464 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7465 return getDependentTemplateName(Name: {CanonQualifier, DTN->getName(),
7466 /*HasTemplateKeyword=*/true});
7467 return Name;
7468 }
7469
7470 case TemplateName::SubstTemplateTemplateParmPack: {
7471 SubstTemplateTemplateParmPackStorage *subst =
7472 Name.getAsSubstTemplateTemplateParmPack();
7473 TemplateArgument canonArgPack =
7474 getCanonicalTemplateArgument(Arg: subst->getArgumentPack());
7475 return getSubstTemplateTemplateParmPack(
7476 ArgPack: canonArgPack, AssociatedDecl: subst->getAssociatedDecl()->getCanonicalDecl(),
7477 Index: subst->getIndex(), Final: subst->getFinal());
7478 }
7479
7480 case TemplateName::PackIndexingTemplate: {
7481 PackIndexingTemplateStorage *PI = Name.getAsPackIndexingTemplate();
7482 SmallVector<TemplateName, 4> CanonExpansions;
7483 for (TemplateName T : PI->getExpansions())
7484 CanonExpansions.push_back(Elt: getCanonicalTemplateName(Name: T, IgnoreDeduced));
7485 return getPackIndexingTemplateName(
7486 Pattern: getCanonicalTemplateName(Name: PI->getPattern(), IgnoreDeduced),
7487 IndexExpr: PI->getIndexExpr(), FullySubstituted: PI->isFullySubstituted(), Expansions: CanonExpansions);
7488 }
7489 case TemplateName::DeducedTemplate: {
7490 assert(IgnoreDeduced == false);
7491 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7492 DefaultArguments DefArgs = DTS->getDefaultArguments();
7493 TemplateName Underlying = DTS->getUnderlying();
7494
7495 TemplateName CanonUnderlying =
7496 getCanonicalTemplateName(Name: Underlying, /*IgnoreDeduced=*/true);
7497 bool NonCanonical = CanonUnderlying != Underlying;
7498 auto CanonArgs =
7499 getCanonicalTemplateArguments(C: *this, Args: DefArgs.Args, AnyNonCanonArgs&: NonCanonical);
7500
7501 ArrayRef<NamedDecl *> Params =
7502 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7503 assert(CanonArgs.size() <= Params.size());
7504 // A deduced template name which deduces the same default arguments already
7505 // declared in the underlying template is the same template as the
7506 // underlying template. We need need to note any arguments which differ from
7507 // the corresponding declaration. If any argument differs, we must build a
7508 // deduced template name.
7509 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7510 const TemplateArgument *A = getDefaultTemplateArgumentOrNone(P: Params[I]);
7511 if (!A)
7512 break;
7513 auto CanonParamDefArg = getCanonicalTemplateArgument(Arg: *A);
7514 TemplateArgument &CanonDefArg = CanonArgs[I];
7515 if (CanonDefArg.structurallyEquals(Other: CanonParamDefArg))
7516 continue;
7517 // Keep popping from the back any deault arguments which are the same.
7518 if (I == int(CanonArgs.size() - 1))
7519 CanonArgs.pop_back();
7520 NonCanonical = true;
7521 }
7522 return NonCanonical ? getDeducedTemplateName(
7523 Underlying: CanonUnderlying,
7524 /*DefaultArgs=*/{.StartPos: DefArgs.StartPos, .Args: CanonArgs})
7525 : Name;
7526 }
7527 case TemplateName::UsingTemplate:
7528 case TemplateName::QualifiedTemplate:
7529 case TemplateName::SubstTemplateTemplateParm:
7530 llvm_unreachable("always sugar node");
7531 }
7532
7533 llvm_unreachable("bad template name!");
7534}
7535
7536bool ASTContext::hasSameTemplateName(const TemplateName &X,
7537 const TemplateName &Y,
7538 bool IgnoreDeduced) const {
7539 return getCanonicalTemplateName(Name: X, IgnoreDeduced) ==
7540 getCanonicalTemplateName(Name: Y, IgnoreDeduced);
7541}
7542
7543bool ASTContext::isSameAssociatedConstraint(
7544 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7545 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7546 return false;
7547 if (!isSameConstraintExpr(XCE: ACX.ConstraintExpr, YCE: ACY.ConstraintExpr))
7548 return false;
7549 return true;
7550}
7551
7552bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7553 if (!XCE != !YCE)
7554 return false;
7555
7556 if (!XCE)
7557 return true;
7558
7559 llvm::FoldingSetNodeID XCEID, YCEID;
7560 XCE->Profile(ID&: XCEID, Context: *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7561 YCE->Profile(ID&: YCEID, Context: *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7562 return XCEID == YCEID;
7563}
7564
7565bool ASTContext::isSameTypeConstraint(const TypeConstraint *XTC,
7566 const TypeConstraint *YTC) const {
7567 if (!XTC != !YTC)
7568 return false;
7569
7570 if (!XTC)
7571 return true;
7572
7573 TemplateDecl *NCX = XTC->getNamedConcept().getAsTemplateDecl();
7574 TemplateDecl *NCY = YTC->getNamedConcept().getAsTemplateDecl();
7575 if (!NCX || !NCY || !isSameEntity(X: NCX, Y: NCY))
7576 return false;
7577 if (XTC->getConceptReference()->hasExplicitTemplateArgs() !=
7578 YTC->getConceptReference()->hasExplicitTemplateArgs())
7579 return false;
7580 if (XTC->getConceptReference()->hasExplicitTemplateArgs())
7581 if (XTC->getConceptReference()
7582 ->getTemplateArgsAsWritten()
7583 ->NumTemplateArgs !=
7584 YTC->getConceptReference()->getTemplateArgsAsWritten()->NumTemplateArgs)
7585 return false;
7586
7587 // Compare slowly by profiling.
7588 //
7589 // We couldn't compare the profiling result for the template
7590 // args here. Consider the following example in different modules:
7591 //
7592 // template <__integer_like _Tp, C<_Tp> Sentinel>
7593 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7594 // return __t;
7595 // }
7596 //
7597 // When we compare the profiling result for `C<_Tp>` in different
7598 // modules, it will compare the type of `_Tp` in different modules.
7599 // However, the type of `_Tp` in different modules refer to different
7600 // types here naturally. So we couldn't compare the profiling result
7601 // for the template args directly.
7602 return isSameConstraintExpr(XCE: XTC->getImmediatelyDeclaredConstraint(),
7603 YCE: YTC->getImmediatelyDeclaredConstraint());
7604}
7605
7606bool ASTContext::isSameTemplateParameter(const NamedDecl *X,
7607 const NamedDecl *Y) const {
7608 if (X->getKind() != Y->getKind())
7609 return false;
7610
7611 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(Val: X)) {
7612 auto *TY = cast<TemplateTypeParmDecl>(Val: Y);
7613 if (TX->isParameterPack() != TY->isParameterPack())
7614 return false;
7615 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7616 return false;
7617 return isSameTypeConstraint(XTC: TX->getTypeConstraint(),
7618 YTC: TY->getTypeConstraint());
7619 }
7620
7621 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(Val: X)) {
7622 auto *TY = cast<NonTypeTemplateParmDecl>(Val: Y);
7623 return TX->isParameterPack() == TY->isParameterPack() &&
7624 TX->getASTContext().hasSameType(T1: TX->getType(), T2: TY->getType()) &&
7625 isSameConstraintExpr(XCE: TX->getPlaceholderTypeConstraint(),
7626 YCE: TY->getPlaceholderTypeConstraint());
7627 }
7628
7629 auto *TX = cast<TemplateTemplateParmDecl>(Val: X);
7630 auto *TY = cast<TemplateTemplateParmDecl>(Val: Y);
7631 return TX->isParameterPack() == TY->isParameterPack() &&
7632 isSameTemplateParameterList(X: TX->getTemplateParameters(),
7633 Y: TY->getTemplateParameters());
7634}
7635
7636bool ASTContext::isSameTemplateParameterList(
7637 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7638 if (X->size() != Y->size())
7639 return false;
7640
7641 for (unsigned I = 0, N = X->size(); I != N; ++I)
7642 if (!isSameTemplateParameter(X: X->getParam(Idx: I), Y: Y->getParam(Idx: I)))
7643 return false;
7644
7645 return isSameConstraintExpr(XCE: X->getRequiresClause(), YCE: Y->getRequiresClause());
7646}
7647
7648bool ASTContext::isSameDefaultTemplateArgument(const NamedDecl *X,
7649 const NamedDecl *Y) const {
7650 // If the type parameter isn't the same already, we don't need to check the
7651 // default argument further.
7652 if (!isSameTemplateParameter(X, Y))
7653 return false;
7654
7655 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(Val: X)) {
7656 auto *TTPY = cast<TemplateTypeParmDecl>(Val: Y);
7657 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7658 return false;
7659
7660 return hasSameType(T1: TTPX->getDefaultArgument().getArgument().getAsType(),
7661 T2: TTPY->getDefaultArgument().getArgument().getAsType());
7662 }
7663
7664 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(Val: X)) {
7665 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Val: Y);
7666 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7667 return false;
7668
7669 Expr *DefaultArgumentX =
7670 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7671 Expr *DefaultArgumentY =
7672 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7673 llvm::FoldingSetNodeID XID, YID;
7674 DefaultArgumentX->Profile(ID&: XID, Context: *this, /*Canonical=*/true);
7675 DefaultArgumentY->Profile(ID&: YID, Context: *this, /*Canonical=*/true);
7676 return XID == YID;
7677 }
7678
7679 auto *TTPX = cast<TemplateTemplateParmDecl>(Val: X);
7680 auto *TTPY = cast<TemplateTemplateParmDecl>(Val: Y);
7681
7682 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7683 return false;
7684
7685 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7686 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7687 return hasSameTemplateName(X: TAX.getAsTemplate(), Y: TAY.getAsTemplate());
7688}
7689
7690static bool isSameQualifier(const NestedNameSpecifier X,
7691 const NestedNameSpecifier Y) {
7692 if (X == Y)
7693 return true;
7694 if (!X || !Y)
7695 return false;
7696
7697 auto Kind = X.getKind();
7698 if (Kind != Y.getKind())
7699 return false;
7700
7701 // FIXME: For namespaces and types, we're permitted to check that the entity
7702 // is named via the same tokens. We should probably do so.
7703 switch (Kind) {
7704 case NestedNameSpecifier::Kind::Namespace: {
7705 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7706 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7707 if (!declaresSameEntity(D1: NamespaceX->getNamespace(),
7708 D2: NamespaceY->getNamespace()))
7709 return false;
7710 return isSameQualifier(X: PrefixX, Y: PrefixY);
7711 }
7712 case NestedNameSpecifier::Kind::Type: {
7713 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7714 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7715 return false;
7716 return isSameQualifier(X: TX->getPrefix(), Y: TY->getPrefix());
7717 }
7718 case NestedNameSpecifier::Kind::Null:
7719 case NestedNameSpecifier::Kind::Global:
7720 case NestedNameSpecifier::Kind::MicrosoftSuper:
7721 return true;
7722 }
7723 llvm_unreachable("unhandled qualifier kind");
7724}
7725
7726static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7727 if (!A->getASTContext().getLangOpts().CUDA)
7728 return true; // Target attributes are overloadable in CUDA compilation only.
7729 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7730 return false;
7731 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7732 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7733 return true; // unattributed and __host__ functions are the same.
7734}
7735
7736/// Determine whether the attributes we can overload on are identical for A and
7737/// B. Will ignore any overloadable attrs represented in the type of A and B.
7738static bool hasSameOverloadableAttrs(const FunctionDecl *A,
7739 const FunctionDecl *B) {
7740 // Note that pass_object_size attributes are represented in the function's
7741 // ExtParameterInfo, so we don't need to check them here.
7742
7743 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7744 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7745 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7746
7747 for (auto Pair : zip_longest(t&: AEnableIfAttrs, u&: BEnableIfAttrs)) {
7748 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
7749 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
7750
7751 // Return false if the number of enable_if attributes is different.
7752 if (!Cand1A || !Cand2A)
7753 return false;
7754
7755 Cand1ID.clear();
7756 Cand2ID.clear();
7757
7758 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: A->getASTContext(), Canonical: true);
7759 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: B->getASTContext(), Canonical: true);
7760
7761 // Return false if any of the enable_if expressions of A and B are
7762 // different.
7763 if (Cand1ID != Cand2ID)
7764 return false;
7765 }
7766 return hasSameCudaAttrs(A, B);
7767}
7768
7769bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7770 // Caution: this function is called by the AST reader during deserialization,
7771 // so it cannot rely on AST invariants being met. Non-trivial accessors
7772 // should be avoided, along with any traversal of redeclaration chains.
7773
7774 if (X == Y)
7775 return true;
7776
7777 if (X->getDeclName() != Y->getDeclName())
7778 return false;
7779
7780 // Must be in the same context.
7781 //
7782 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7783 // could be two different declarations of the same function. (We will fix the
7784 // semantic DC to refer to the primary definition after merging.)
7785 if (!declaresSameEntity(D1: cast<Decl>(Val: X->getDeclContext()->getRedeclContext()),
7786 D2: cast<Decl>(Val: Y->getDeclContext()->getRedeclContext())))
7787 return false;
7788
7789 // If either X or Y are local to the owning module, they are only possible to
7790 // be the same entity if they are in the same module.
7791 if (X->isModuleLocal() || Y->isModuleLocal())
7792 if (!isInSameModule(M1: X->getOwningModule(), M2: Y->getOwningModule()))
7793 return false;
7794
7795 // Two typedefs refer to the same entity if they have the same underlying
7796 // type.
7797 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(Val: X))
7798 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Val: Y))
7799 return hasSameType(T1: TypedefX->getUnderlyingType(),
7800 T2: TypedefY->getUnderlyingType());
7801
7802 // Must have the same kind.
7803 if (X->getKind() != Y->getKind())
7804 return false;
7805
7806 // Objective-C classes and protocols with the same name always match.
7807 if (isa<ObjCInterfaceDecl>(Val: X) || isa<ObjCProtocolDecl>(Val: X))
7808 return true;
7809
7810 if (isa<ClassTemplateSpecializationDecl>(Val: X)) {
7811 // No need to handle these here: we merge them when adding them to the
7812 // template.
7813 return false;
7814 }
7815
7816 // Compatible tags match.
7817 if (const auto *TagX = dyn_cast<TagDecl>(Val: X)) {
7818 const auto *TagY = cast<TagDecl>(Val: Y);
7819 return (TagX->getTagKind() == TagY->getTagKind()) ||
7820 ((TagX->getTagKind() == TagTypeKind::Struct ||
7821 TagX->getTagKind() == TagTypeKind::Class ||
7822 TagX->getTagKind() == TagTypeKind::Interface) &&
7823 (TagY->getTagKind() == TagTypeKind::Struct ||
7824 TagY->getTagKind() == TagTypeKind::Class ||
7825 TagY->getTagKind() == TagTypeKind::Interface));
7826 }
7827
7828 // Functions with the same type and linkage match.
7829 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7830 // functions, etc.
7831 if (const auto *FuncX = dyn_cast<FunctionDecl>(Val: X)) {
7832 const auto *FuncY = cast<FunctionDecl>(Val: Y);
7833 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(Val: X)) {
7834 const auto *CtorY = cast<CXXConstructorDecl>(Val: Y);
7835 if (CtorX->getInheritedConstructor() &&
7836 !isSameEntity(X: CtorX->getInheritedConstructor().getConstructor(),
7837 Y: CtorY->getInheritedConstructor().getConstructor()))
7838 return false;
7839 }
7840
7841 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7842 return false;
7843
7844 // Multiversioned functions with different feature strings are represented
7845 // as separate declarations.
7846 if (FuncX->isMultiVersion()) {
7847 const auto *TAX = FuncX->getAttr<TargetAttr>();
7848 const auto *TAY = FuncY->getAttr<TargetAttr>();
7849 assert(TAX && TAY && "Multiversion Function without target attribute");
7850
7851 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7852 return false;
7853 }
7854
7855 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7856 // not the same entity if they are constrained.
7857 if ((FuncX->isMemberLikeConstrainedFriend() ||
7858 FuncY->isMemberLikeConstrainedFriend()) &&
7859 !FuncX->getLexicalDeclContext()->Equals(
7860 DC: FuncY->getLexicalDeclContext())) {
7861 return false;
7862 }
7863
7864 if (!isSameAssociatedConstraint(ACX: FuncX->getTrailingRequiresClause(),
7865 ACY: FuncY->getTrailingRequiresClause()))
7866 return false;
7867
7868 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7869 // Map to the first declaration that we've already merged into this one.
7870 // The TSI of redeclarations might not match (due to calling conventions
7871 // being inherited onto the type but not the TSI), but the TSI type of
7872 // the first declaration of the function should match across modules.
7873 FD = FD->getCanonicalDecl();
7874 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7875 : FD->getType();
7876 };
7877 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7878 if (!hasSameType(T1: XT, T2: YT)) {
7879 // We can get functions with different types on the redecl chain in C++17
7880 // if they have differing exception specifications and at least one of
7881 // the excpetion specs is unresolved.
7882 auto *XFPT = XT->getAs<FunctionProtoType>();
7883 auto *YFPT = YT->getAs<FunctionProtoType>();
7884 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7885 (isUnresolvedExceptionSpec(ESpecType: XFPT->getExceptionSpecType()) ||
7886 isUnresolvedExceptionSpec(ESpecType: YFPT->getExceptionSpecType())) &&
7887 hasSameFunctionTypeIgnoringExceptionSpec(T: XT, U: YT))
7888 return true;
7889 return false;
7890 }
7891
7892 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7893 hasSameOverloadableAttrs(A: FuncX, B: FuncY);
7894 }
7895
7896 // Variables with the same type and linkage match.
7897 if (const auto *VarX = dyn_cast<VarDecl>(Val: X)) {
7898 const auto *VarY = cast<VarDecl>(Val: Y);
7899 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7900 // During deserialization, we might compare variables before we load
7901 // their types. Assume the types will end up being the same.
7902 if (VarX->getType().isNull() || VarY->getType().isNull())
7903 return true;
7904
7905 if (hasSameType(T1: VarX->getType(), T2: VarY->getType()))
7906 return true;
7907
7908 // We can get decls with different types on the redecl chain. Eg.
7909 // template <typename T> struct S { static T Var[]; }; // #1
7910 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7911 // Only? happens when completing an incomplete array type. In this case
7912 // when comparing #1 and #2 we should go through their element type.
7913 const ArrayType *VarXTy = getAsArrayType(T: VarX->getType());
7914 const ArrayType *VarYTy = getAsArrayType(T: VarY->getType());
7915 if (!VarXTy || !VarYTy)
7916 return false;
7917 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7918 return hasSameType(T1: VarXTy->getElementType(), T2: VarYTy->getElementType());
7919 }
7920 return false;
7921 }
7922
7923 // Namespaces with the same name and inlinedness match.
7924 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(Val: X)) {
7925 const auto *NamespaceY = cast<NamespaceDecl>(Val: Y);
7926 return NamespaceX->isInline() == NamespaceY->isInline();
7927 }
7928
7929 // Identical template names and kinds match if their template parameter lists
7930 // and patterns match.
7931 if (const auto *TemplateX = dyn_cast<TemplateDecl>(Val: X)) {
7932 const auto *TemplateY = cast<TemplateDecl>(Val: Y);
7933
7934 // ConceptDecl wouldn't be the same if their constraint expression differs.
7935 if (const auto *ConceptX = dyn_cast<ConceptDecl>(Val: X)) {
7936 const auto *ConceptY = cast<ConceptDecl>(Val: Y);
7937 if (!isSameConstraintExpr(XCE: ConceptX->getConstraintExpr(),
7938 YCE: ConceptY->getConstraintExpr()))
7939 return false;
7940 }
7941
7942 return isSameEntity(X: TemplateX->getTemplatedDecl(),
7943 Y: TemplateY->getTemplatedDecl()) &&
7944 isSameTemplateParameterList(X: TemplateX->getTemplateParameters(),
7945 Y: TemplateY->getTemplateParameters());
7946 }
7947
7948 // Fields with the same name and the same type match.
7949 if (const auto *FDX = dyn_cast<FieldDecl>(Val: X)) {
7950 const auto *FDY = cast<FieldDecl>(Val: Y);
7951 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7952 return hasSameType(T1: FDX->getType(), T2: FDY->getType());
7953 }
7954
7955 // Indirect fields with the same target field match.
7956 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(Val: X)) {
7957 const auto *IFDY = cast<IndirectFieldDecl>(Val: Y);
7958 return IFDX->getAnonField()->getCanonicalDecl() ==
7959 IFDY->getAnonField()->getCanonicalDecl();
7960 }
7961
7962 // Enumerators with the same name match.
7963 if (isa<EnumConstantDecl>(Val: X))
7964 // FIXME: Also check the value is odr-equivalent.
7965 return true;
7966
7967 // Using shadow declarations with the same target match.
7968 if (const auto *USX = dyn_cast<UsingShadowDecl>(Val: X)) {
7969 const auto *USY = cast<UsingShadowDecl>(Val: Y);
7970 return declaresSameEntity(D1: USX->getTargetDecl(), D2: USY->getTargetDecl());
7971 }
7972
7973 // Using declarations with the same qualifier match. (We already know that
7974 // the name matches.)
7975 if (const auto *UX = dyn_cast<UsingDecl>(Val: X)) {
7976 const auto *UY = cast<UsingDecl>(Val: Y);
7977 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
7978 UX->hasTypename() == UY->hasTypename() &&
7979 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7980 }
7981 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(Val: X)) {
7982 const auto *UY = cast<UnresolvedUsingValueDecl>(Val: Y);
7983 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
7984 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7985 }
7986 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(Val: X)) {
7987 return isSameQualifier(
7988 X: UX->getQualifier(),
7989 Y: cast<UnresolvedUsingTypenameDecl>(Val: Y)->getQualifier());
7990 }
7991
7992 // Using-pack declarations are only created by instantiation, and match if
7993 // they're instantiated from matching UnresolvedUsing...Decls.
7994 if (const auto *UX = dyn_cast<UsingPackDecl>(Val: X)) {
7995 return declaresSameEntity(
7996 D1: UX->getInstantiatedFromUsingDecl(),
7997 D2: cast<UsingPackDecl>(Val: Y)->getInstantiatedFromUsingDecl());
7998 }
7999
8000 // Namespace alias definitions with the same target match.
8001 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(Val: X)) {
8002 const auto *NAY = cast<NamespaceAliasDecl>(Val: Y);
8003 return NAX->getNamespace()->Equals(DC: NAY->getNamespace());
8004 }
8005
8006 if (const auto *UX = dyn_cast<UsingEnumDecl>(Val: X)) {
8007 const auto *UY = cast<UsingEnumDecl>(Val: Y);
8008 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
8009 declaresSameEntity(D1: UX->getEnumDecl(), D2: UY->getEnumDecl());
8010 }
8011
8012 return false;
8013}
8014
8015TemplateArgument
8016ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
8017 switch (Arg.getKind()) {
8018 case TemplateArgument::Null:
8019 return Arg;
8020
8021 case TemplateArgument::Expression:
8022 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
8023 Arg.getIsDefaulted());
8024
8025 case TemplateArgument::Declaration: {
8026 auto *D = cast<ValueDecl>(Val: Arg.getAsDecl()->getCanonicalDecl());
8027 return TemplateArgument(D, getCanonicalType(T: Arg.getParamTypeForDecl()),
8028 Arg.getIsDefaulted());
8029 }
8030
8031 case TemplateArgument::NullPtr:
8032 return TemplateArgument(getCanonicalType(T: Arg.getNullPtrType()),
8033 /*isNullPtr*/ true, Arg.getIsDefaulted());
8034
8035 case TemplateArgument::Template:
8036 return TemplateArgument(getCanonicalTemplateName(Name: Arg.getAsTemplate()),
8037 Arg.getIsDefaulted());
8038
8039 case TemplateArgument::TemplateExpansion:
8040 return TemplateArgument(
8041 getCanonicalTemplateName(Name: Arg.getAsTemplateOrTemplatePattern()),
8042 Arg.getNumTemplateExpansions(), Arg.getIsDefaulted());
8043
8044 case TemplateArgument::Integral:
8045 return TemplateArgument(Arg, getCanonicalType(T: Arg.getIntegralType()));
8046
8047 case TemplateArgument::StructuralValue:
8048 return TemplateArgument(*this,
8049 getCanonicalType(T: Arg.getStructuralValueType()),
8050 Arg.getAsStructuralValue(), Arg.getIsDefaulted());
8051
8052 case TemplateArgument::Type:
8053 return TemplateArgument(getCanonicalType(T: Arg.getAsType()),
8054 /*isNullPtr*/ false, Arg.getIsDefaulted());
8055
8056 case TemplateArgument::Pack: {
8057 bool AnyNonCanonArgs = false;
8058 auto CanonArgs = ::getCanonicalTemplateArguments(
8059 C: *this, Args: Arg.pack_elements(), AnyNonCanonArgs);
8060 if (!AnyNonCanonArgs)
8061 return Arg;
8062 auto NewArg = TemplateArgument::CreatePackCopy(
8063 Context&: const_cast<ASTContext &>(*this), Args: CanonArgs);
8064 NewArg.setIsDefaulted(Arg.getIsDefaulted());
8065 return NewArg;
8066 }
8067 }
8068
8069 // Silence GCC warning
8070 llvm_unreachable("Unhandled template argument kind");
8071}
8072
8073bool ASTContext::isSameTemplateArgument(const TemplateArgument &Arg1,
8074 const TemplateArgument &Arg2) const {
8075 if (Arg1.getKind() != Arg2.getKind())
8076 return false;
8077
8078 switch (Arg1.getKind()) {
8079 case TemplateArgument::Null:
8080 llvm_unreachable("Comparing NULL template argument");
8081
8082 case TemplateArgument::Type:
8083 return hasSameType(T1: Arg1.getAsType(), T2: Arg2.getAsType());
8084
8085 case TemplateArgument::Declaration:
8086 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
8087 Arg2.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl();
8088
8089 case TemplateArgument::NullPtr:
8090 return hasSameType(T1: Arg1.getNullPtrType(), T2: Arg2.getNullPtrType());
8091
8092 case TemplateArgument::Template:
8093 case TemplateArgument::TemplateExpansion:
8094 return getCanonicalTemplateName(Name: Arg1.getAsTemplateOrTemplatePattern()) ==
8095 getCanonicalTemplateName(Name: Arg2.getAsTemplateOrTemplatePattern());
8096
8097 case TemplateArgument::Integral:
8098 return llvm::APSInt::isSameValue(I1: Arg1.getAsIntegral(),
8099 I2: Arg2.getAsIntegral());
8100
8101 case TemplateArgument::StructuralValue:
8102 return Arg1.structurallyEquals(Other: Arg2);
8103
8104 case TemplateArgument::Expression: {
8105 llvm::FoldingSetNodeID ID1, ID2;
8106 Arg1.getAsExpr()->Profile(ID&: ID1, Context: *this, /*Canonical=*/true);
8107 Arg2.getAsExpr()->Profile(ID&: ID2, Context: *this, /*Canonical=*/true);
8108 return ID1 == ID2;
8109 }
8110
8111 case TemplateArgument::Pack:
8112 return llvm::equal(
8113 LRange: Arg1.getPackAsArray(), RRange: Arg2.getPackAsArray(),
8114 P: [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8115 return isSameTemplateArgument(Arg1, Arg2);
8116 });
8117 }
8118
8119 llvm_unreachable("Unhandled template argument kind");
8120}
8121
8122const ArrayType *ASTContext::getAsArrayType(QualType T) const {
8123 // Handle the non-qualified case efficiently.
8124 if (!T.hasLocalQualifiers()) {
8125 // Handle the common positive case fast.
8126 if (const auto *AT = dyn_cast<ArrayType>(Val&: T))
8127 return AT;
8128 }
8129
8130 // Handle the common negative case fast.
8131 if (!isa<ArrayType>(Val: T.getCanonicalType()))
8132 return nullptr;
8133
8134 // Apply any qualifiers from the array type to the element type. This
8135 // implements C99 6.7.3p8: "If the specification of an array type includes
8136 // any type qualifiers, the element type is so qualified, not the array type."
8137
8138 // If we get here, we either have type qualifiers on the type, or we have
8139 // sugar such as a typedef in the way. If we have type qualifiers on the type
8140 // we must propagate them down into the element type.
8141
8142 SplitQualType split = T.getSplitDesugaredType();
8143 Qualifiers qs = split.Quals;
8144
8145 // If we have a simple case, just return now.
8146 const auto *ATy = dyn_cast<ArrayType>(Val: split.Ty);
8147 if (!ATy || qs.empty())
8148 return ATy;
8149
8150 // Otherwise, we have an array and we have qualifiers on it. Push the
8151 // qualifiers into the array element type and return a new array type.
8152 QualType NewEltTy = getQualifiedType(T: ATy->getElementType(), Qs: qs);
8153
8154 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: ATy))
8155 return cast<ArrayType>(Val: getConstantArrayType(EltTy: NewEltTy, ArySizeIn: CAT->getSize(),
8156 SizeExpr: CAT->getSizeExpr(),
8157 ASM: CAT->getSizeModifier(),
8158 IndexTypeQuals: CAT->getIndexTypeCVRQualifiers()));
8159 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: ATy))
8160 return cast<ArrayType>(Val: getIncompleteArrayType(elementType: NewEltTy,
8161 ASM: IAT->getSizeModifier(),
8162 elementTypeQuals: IAT->getIndexTypeCVRQualifiers()));
8163
8164 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(Val: ATy))
8165 return cast<ArrayType>(Val: getDependentSizedArrayType(
8166 elementType: NewEltTy, numElements: DSAT->getSizeExpr(), ASM: DSAT->getSizeModifier(),
8167 elementTypeQuals: DSAT->getIndexTypeCVRQualifiers()));
8168
8169 const auto *VAT = cast<VariableArrayType>(Val: ATy);
8170 return cast<ArrayType>(
8171 Val: getVariableArrayType(EltTy: NewEltTy, NumElts: VAT->getSizeExpr(), ASM: VAT->getSizeModifier(),
8172 IndexTypeQuals: VAT->getIndexTypeCVRQualifiers()));
8173}
8174
8175QualType ASTContext::getAdjustedParameterType(QualType T) const {
8176 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8177 return getLValueReferenceType(T);
8178 if (getLangOpts().HLSL && T->isConstantArrayType())
8179 return getArrayParameterType(Ty: T);
8180 if (T->isArrayType() || T->isFunctionType())
8181 return getDecayedType(T);
8182 return T;
8183}
8184
8185QualType ASTContext::getSignatureParameterType(QualType T) const {
8186 T = getVariableArrayDecayedType(type: T);
8187 T = getAdjustedParameterType(T);
8188 return T.getUnqualifiedType();
8189}
8190
8191QualType ASTContext::getExceptionObjectType(QualType T) const {
8192 // C++ [except.throw]p3:
8193 // A throw-expression initializes a temporary object, called the exception
8194 // object, the type of which is determined by removing any top-level
8195 // cv-qualifiers from the static type of the operand of throw and adjusting
8196 // the type from "array of T" or "function returning T" to "pointer to T"
8197 // or "pointer to function returning T", [...]
8198 T = getVariableArrayDecayedType(type: T);
8199 if (T->isArrayType() || T->isFunctionType())
8200 T = getDecayedType(T);
8201 return T.getUnqualifiedType();
8202}
8203
8204/// getArrayDecayedType - Return the properly qualified result of decaying the
8205/// specified array type to a pointer. This operation is non-trivial when
8206/// handling typedefs etc. The canonical type of "T" must be an array type,
8207/// this returns a pointer to a properly qualified element of the array.
8208///
8209/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8210QualType ASTContext::getArrayDecayedType(QualType Ty) const {
8211 // Get the element type with 'getAsArrayType' so that we don't lose any
8212 // typedefs in the element type of the array. This also handles propagation
8213 // of type qualifiers from the array type into the element type if present
8214 // (C99 6.7.3p8).
8215 const ArrayType *PrettyArrayType = getAsArrayType(T: Ty);
8216 assert(PrettyArrayType && "Not an array type!");
8217
8218 QualType PtrTy = getPointerType(T: PrettyArrayType->getElementType());
8219
8220 // int x[restrict 4] -> int *restrict
8221 QualType Result = getQualifiedType(T: PtrTy,
8222 Qs: PrettyArrayType->getIndexTypeQualifiers());
8223
8224 // int x[_Nullable] -> int * _Nullable
8225 if (auto Nullability = Ty->getNullability()) {
8226 Result = getAttributedType(nullability: *Nullability, modifiedType: Result, equivalentType: Result);
8227 }
8228 return Result;
8229}
8230
8231QualType ASTContext::getBaseElementType(const ArrayType *array) const {
8232 return getBaseElementType(QT: array->getElementType());
8233}
8234
8235QualType ASTContext::getBaseElementType(QualType type) const {
8236 Qualifiers qs;
8237 while (true) {
8238 SplitQualType split = type.getSplitDesugaredType();
8239 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8240 if (!array) break;
8241
8242 type = array->getElementType();
8243 qs.addConsistentQualifiers(qs: split.Quals);
8244 }
8245
8246 return getQualifiedType(T: type, Qs: qs);
8247}
8248
8249uint64_t ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) {
8250 uint64_t ElementCount = 1;
8251 do {
8252 ElementCount *= CA->getZExtSize();
8253 CA = dyn_cast_if_present<ConstantArrayType>(
8254 Val: CA->getElementType()->getAsArrayTypeUnsafe());
8255 } while (CA);
8256 return ElementCount;
8257}
8258
8259uint64_t
8260ASTContext::getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) {
8261 if (!AILE)
8262 return 0;
8263
8264 uint64_t ElementCount = 1;
8265
8266 do {
8267 ElementCount *= AILE->getArraySize().getZExtValue();
8268 AILE = dyn_cast<ArrayInitLoopExpr>(Val: AILE->getSubExpr());
8269 } while (AILE);
8270
8271 return ElementCount;
8272}
8273
8274/// getFloatingRank - Return a relative rank for floating point types.
8275/// This routine will assert if passed a built-in type that isn't a float.
8276static FloatingRank getFloatingRank(QualType T) {
8277 if (const auto *CT = T->getAs<ComplexType>())
8278 return getFloatingRank(T: CT->getElementType());
8279
8280 switch (T->castAs<BuiltinType>()->getKind()) {
8281 default: llvm_unreachable("getFloatingRank(): not a floating type");
8282 case BuiltinType::Float16: return Float16Rank;
8283 case BuiltinType::Half: return HalfRank;
8284 case BuiltinType::Float: return FloatRank;
8285 case BuiltinType::Double: return DoubleRank;
8286 case BuiltinType::LongDouble: return LongDoubleRank;
8287 case BuiltinType::Float128: return Float128Rank;
8288 case BuiltinType::BFloat16: return BFloat16Rank;
8289 case BuiltinType::Ibm128: return Ibm128Rank;
8290 }
8291}
8292
8293/// getFloatingTypeOrder - Compare the rank of the two specified floating
8294/// point types, ignoring the domain of the type (i.e. 'double' ==
8295/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8296/// LHS < RHS, return -1.
8297int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
8298 FloatingRank LHSR = getFloatingRank(T: LHS);
8299 FloatingRank RHSR = getFloatingRank(T: RHS);
8300
8301 if (LHSR == RHSR)
8302 return 0;
8303 if (LHSR > RHSR)
8304 return 1;
8305 return -1;
8306}
8307
8308int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
8309 if (&getFloatTypeSemantics(T: LHS) == &getFloatTypeSemantics(T: RHS))
8310 return 0;
8311 return getFloatingTypeOrder(LHS, RHS);
8312}
8313
8314/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8315/// routine will assert if passed a built-in type that isn't an integer or enum,
8316/// or if it is not canonicalized.
8317unsigned ASTContext::getIntegerRank(const Type *T) const {
8318 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8319
8320 // Results in this 'losing' to any type of the same size, but winning if
8321 // larger.
8322 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
8323 return 0 + (EIT->getNumBits() << 3);
8324
8325 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
8326 return getIntegerRank(T: OBT->getUnderlyingType().getTypePtr());
8327
8328 switch (cast<BuiltinType>(Val: T)->getKind()) {
8329 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8330 case BuiltinType::Bool:
8331 return 1 + (getIntWidth(T: BoolTy) << 3);
8332 case BuiltinType::Char_S:
8333 case BuiltinType::Char_U:
8334 case BuiltinType::SChar:
8335 case BuiltinType::UChar:
8336 return 2 + (getIntWidth(T: CharTy) << 3);
8337 case BuiltinType::Short:
8338 case BuiltinType::UShort:
8339 return 3 + (getIntWidth(T: ShortTy) << 3);
8340 case BuiltinType::Int:
8341 case BuiltinType::UInt:
8342 return 4 + (getIntWidth(T: IntTy) << 3);
8343 case BuiltinType::Long:
8344 case BuiltinType::ULong:
8345 return 5 + (getIntWidth(T: LongTy) << 3);
8346 case BuiltinType::LongLong:
8347 case BuiltinType::ULongLong:
8348 return 6 + (getIntWidth(T: LongLongTy) << 3);
8349 case BuiltinType::Int128:
8350 case BuiltinType::UInt128:
8351 return 7 + (getIntWidth(T: Int128Ty) << 3);
8352
8353 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8354 // their underlying types" [c++20 conv.rank]
8355 case BuiltinType::Char8:
8356 return getIntegerRank(T: UnsignedCharTy.getTypePtr());
8357 case BuiltinType::Char16:
8358 return getIntegerRank(
8359 T: getFromTargetType(Type: Target->getChar16Type()).getTypePtr());
8360 case BuiltinType::Char32:
8361 return getIntegerRank(
8362 T: getFromTargetType(Type: Target->getChar32Type()).getTypePtr());
8363 case BuiltinType::WChar_S:
8364 case BuiltinType::WChar_U:
8365 return getIntegerRank(
8366 T: getFromTargetType(Type: Target->getWCharType()).getTypePtr());
8367 }
8368}
8369
8370/// Whether this is a promotable bitfield reference according
8371/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8372///
8373/// \returns the type this bit-field will promote to, or NULL if no
8374/// promotion occurs.
8375QualType ASTContext::isPromotableBitField(Expr *E) const {
8376 if (E->isTypeDependent() || E->isValueDependent())
8377 return {};
8378
8379 // C++ [conv.prom]p5:
8380 // If the bit-field has an enumerated type, it is treated as any other
8381 // value of that type for promotion purposes.
8382 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
8383 return {};
8384
8385 // FIXME: We should not do this unless E->refersToBitField() is true. This
8386 // matters in C where getSourceBitField() will find bit-fields for various
8387 // cases where the source expression is not a bit-field designator.
8388
8389 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8390 if (!Field)
8391 return {};
8392
8393 QualType FT = Field->getType();
8394
8395 uint64_t BitWidth = Field->getBitWidthValue();
8396 uint64_t IntSize = getTypeSize(T: IntTy);
8397 // C++ [conv.prom]p5:
8398 // A prvalue for an integral bit-field can be converted to a prvalue of type
8399 // int if int can represent all the values of the bit-field; otherwise, it
8400 // can be converted to unsigned int if unsigned int can represent all the
8401 // values of the bit-field. If the bit-field is larger yet, no integral
8402 // promotion applies to it.
8403 // C11 6.3.1.1/2:
8404 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8405 // If an int can represent all values of the original type (as restricted by
8406 // the width, for a bit-field), the value is converted to an int; otherwise,
8407 // it is converted to an unsigned int.
8408 //
8409 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8410 // We perform that promotion here to match GCC and C++.
8411 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8412 // greater than that of 'int'. We perform that promotion to match GCC.
8413 //
8414 // C23 6.3.1.1p2:
8415 // The value from a bit-field of a bit-precise integer type is converted to
8416 // the corresponding bit-precise integer type. (The rest is the same as in
8417 // C11.)
8418 if (QualType QT = Field->getType(); QT->isBitIntType())
8419 return QT;
8420
8421 if (BitWidth < IntSize)
8422 return IntTy;
8423
8424 if (BitWidth == IntSize)
8425 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8426
8427 // Bit-fields wider than int are not subject to promotions, and therefore act
8428 // like the base type. GCC has some weird bugs in this area that we
8429 // deliberately do not follow (GCC follows a pre-standard resolution to
8430 // C's DR315 which treats bit-width as being part of the type, and this leaks
8431 // into their semantics in some cases).
8432 return {};
8433}
8434
8435/// getPromotedIntegerType - Returns the type that Promotable will
8436/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8437/// integer type.
8438QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
8439 assert(!Promotable.isNull());
8440 assert(isPromotableIntegerType(Promotable));
8441 if (const auto *ED = Promotable->getAsEnumDecl())
8442 return ED->getPromotionType();
8443
8444 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8445 // qualifier.
8446 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8447 QualType PromotedUnderlying =
8448 getPromotedIntegerType(Promotable: OBT->getUnderlyingType());
8449 return getOverflowBehaviorType(Kind: OBT->getBehaviorKind(), Underlying: PromotedUnderlying);
8450 }
8451
8452 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8453 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8454 // (3.9.1) can be converted to a prvalue of the first of the following
8455 // types that can represent all the values of its underlying type:
8456 // int, unsigned int, long int, unsigned long int, long long int, or
8457 // unsigned long long int [...]
8458 // FIXME: Is there some better way to compute this?
8459 if (BT->getKind() == BuiltinType::WChar_S ||
8460 BT->getKind() == BuiltinType::WChar_U ||
8461 BT->getKind() == BuiltinType::Char8 ||
8462 BT->getKind() == BuiltinType::Char16 ||
8463 BT->getKind() == BuiltinType::Char32) {
8464 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8465 uint64_t FromSize = getTypeSize(T: BT);
8466 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8467 LongLongTy, UnsignedLongLongTy };
8468 for (const auto &PT : PromoteTypes) {
8469 uint64_t ToSize = getTypeSize(T: PT);
8470 if (FromSize < ToSize ||
8471 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8472 return PT;
8473 }
8474 llvm_unreachable("char type should fit into long long");
8475 }
8476 }
8477
8478 // At this point, we should have a signed or unsigned integer type.
8479 if (Promotable->isSignedIntegerType())
8480 return IntTy;
8481 uint64_t PromotableSize = getIntWidth(T: Promotable);
8482 uint64_t IntSize = getIntWidth(T: IntTy);
8483 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8484 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8485}
8486
8487/// Recurses in pointer/array types until it finds an objc retainable
8488/// type and returns its ownership.
8489Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
8490 while (!T.isNull()) {
8491 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8492 return T.getObjCLifetime();
8493 if (T->isArrayType())
8494 T = getBaseElementType(type: T);
8495 else if (const auto *PT = T->getAs<PointerType>())
8496 T = PT->getPointeeType();
8497 else if (const auto *RT = T->getAs<ReferenceType>())
8498 T = RT->getPointeeType();
8499 else
8500 break;
8501 }
8502
8503 return Qualifiers::OCL_None;
8504}
8505
8506static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8507 // Incomplete enum types are not treated as integer types.
8508 // FIXME: In C++, enum types are never integer types.
8509 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8510 if (ED->isComplete() && !ED->isScoped())
8511 return ED->getIntegerType().getTypePtr();
8512 return nullptr;
8513}
8514
8515/// getIntegerTypeOrder - Returns the highest ranked integer type:
8516/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8517/// LHS < RHS, return -1.
8518int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
8519 const Type *LHSC = getCanonicalType(T: LHS).getTypePtr();
8520 const Type *RHSC = getCanonicalType(T: RHS).getTypePtr();
8521
8522 // Unwrap enums to their underlying type.
8523 if (const auto *ET = dyn_cast<EnumType>(Val: LHSC))
8524 LHSC = getIntegerTypeForEnum(ET);
8525 if (const auto *ET = dyn_cast<EnumType>(Val: RHSC))
8526 RHSC = getIntegerTypeForEnum(ET);
8527
8528 if (LHSC == RHSC) return 0;
8529
8530 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8531 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8532
8533 unsigned LHSRank = getIntegerRank(T: LHSC);
8534 unsigned RHSRank = getIntegerRank(T: RHSC);
8535
8536 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8537 if (LHSRank == RHSRank) return 0;
8538 return LHSRank > RHSRank ? 1 : -1;
8539 }
8540
8541 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8542 if (LHSUnsigned) {
8543 // If the unsigned [LHS] type is larger, return it.
8544 if (LHSRank >= RHSRank)
8545 return 1;
8546
8547 // If the signed type can represent all values of the unsigned type, it
8548 // wins. Because we are dealing with 2's complement and types that are
8549 // powers of two larger than each other, this is always safe.
8550 return -1;
8551 }
8552
8553 // If the unsigned [RHS] type is larger, return it.
8554 if (RHSRank >= LHSRank)
8555 return -1;
8556
8557 // If the signed type can represent all values of the unsigned type, it
8558 // wins. Because we are dealing with 2's complement and types that are
8559 // powers of two larger than each other, this is always safe.
8560 return 1;
8561}
8562
8563TypedefDecl *ASTContext::getCFConstantStringDecl() const {
8564 if (CFConstantStringTypeDecl)
8565 return CFConstantStringTypeDecl;
8566
8567 assert(!CFConstantStringTagDecl &&
8568 "tag and typedef should be initialized together");
8569 CFConstantStringTagDecl = buildImplicitRecord(Name: "__NSConstantString_tag");
8570 CFConstantStringTagDecl->startDefinition();
8571
8572 struct {
8573 QualType Type;
8574 const char *Name;
8575 } Fields[5];
8576 unsigned Count = 0;
8577
8578 /// Objective-C ABI
8579 ///
8580 /// typedef struct __NSConstantString_tag {
8581 /// const int *isa;
8582 /// int flags;
8583 /// const char *str;
8584 /// long length;
8585 /// } __NSConstantString;
8586 ///
8587 /// Swift ABI (4.1, 4.2)
8588 ///
8589 /// typedef struct __NSConstantString_tag {
8590 /// uintptr_t _cfisa;
8591 /// uintptr_t _swift_rc;
8592 /// _Atomic(uint64_t) _cfinfoa;
8593 /// const char *_ptr;
8594 /// uint32_t _length;
8595 /// } __NSConstantString;
8596 ///
8597 /// Swift ABI (5.0)
8598 ///
8599 /// typedef struct __NSConstantString_tag {
8600 /// uintptr_t _cfisa;
8601 /// uintptr_t _swift_rc;
8602 /// _Atomic(uint64_t) _cfinfoa;
8603 /// const char *_ptr;
8604 /// uintptr_t _length;
8605 /// } __NSConstantString;
8606
8607 const auto CFRuntime = getLangOpts().CFRuntime;
8608 if (static_cast<unsigned>(CFRuntime) <
8609 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8610 Fields[Count++] = { .Type: getPointerType(T: IntTy.withConst()), .Name: "isa" };
8611 Fields[Count++] = { .Type: IntTy, .Name: "flags" };
8612 Fields[Count++] = { .Type: getPointerType(T: CharTy.withConst()), .Name: "str" };
8613 Fields[Count++] = { .Type: LongTy, .Name: "length" };
8614 } else {
8615 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_cfisa" };
8616 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_swift_rc" };
8617 Fields[Count++] = { .Type: getFromTargetType(Type: Target->getUInt64Type()), .Name: "_swift_rc" };
8618 Fields[Count++] = { .Type: getPointerType(T: CharTy.withConst()), .Name: "_ptr" };
8619 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
8620 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
8621 Fields[Count++] = { .Type: IntTy, .Name: "_ptr" };
8622 else
8623 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_ptr" };
8624 }
8625
8626 // Create fields
8627 for (unsigned i = 0; i < Count; ++i) {
8628 FieldDecl *Field =
8629 FieldDecl::Create(C: *this, DC: CFConstantStringTagDecl, StartLoc: SourceLocation(),
8630 IdLoc: SourceLocation(), Id: &Idents.get(Name: Fields[i].Name),
8631 T: Fields[i].Type, /*TInfo=*/nullptr,
8632 /*BitWidth=*/BW: nullptr, /*Mutable=*/false, InitStyle: ICIS_NoInit);
8633 Field->setAccess(AS_public);
8634 CFConstantStringTagDecl->addDecl(D: Field);
8635 }
8636
8637 CFConstantStringTagDecl->completeDefinition();
8638 // This type is designed to be compatible with NSConstantString, but cannot
8639 // use the same name, since NSConstantString is an interface.
8640 CanQualType tagType = getCanonicalTagType(TD: CFConstantStringTagDecl);
8641 CFConstantStringTypeDecl =
8642 buildImplicitTypedef(T: tagType, Name: "__NSConstantString");
8643
8644 return CFConstantStringTypeDecl;
8645}
8646
8647RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
8648 if (!CFConstantStringTagDecl)
8649 getCFConstantStringDecl(); // Build the tag and the typedef.
8650 return CFConstantStringTagDecl;
8651}
8652
8653// getCFConstantStringType - Return the type used for constant CFStrings.
8654QualType ASTContext::getCFConstantStringType() const {
8655 return getTypedefType(Keyword: ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt,
8656 Decl: getCFConstantStringDecl());
8657}
8658
8659QualType ASTContext::getObjCSuperType() const {
8660 if (ObjCSuperType.isNull()) {
8661 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord(Name: "objc_super");
8662 getTranslationUnitDecl()->addDecl(D: ObjCSuperTypeDecl);
8663 ObjCSuperType = getCanonicalTagType(TD: ObjCSuperTypeDecl);
8664 }
8665 return ObjCSuperType;
8666}
8667
8668void ASTContext::setCFConstantStringType(QualType T) {
8669 const auto *TT = T->castAs<TypedefType>();
8670 CFConstantStringTypeDecl = cast<TypedefDecl>(Val: TT->getDecl());
8671 CFConstantStringTagDecl = TT->castAsRecordDecl();
8672}
8673
8674QualType ASTContext::getBlockDescriptorType() const {
8675 if (BlockDescriptorType)
8676 return getCanonicalTagType(TD: BlockDescriptorType);
8677
8678 RecordDecl *RD;
8679 // FIXME: Needs the FlagAppleBlock bit.
8680 RD = buildImplicitRecord(Name: "__block_descriptor");
8681 RD->startDefinition();
8682
8683 QualType FieldTypes[] = {
8684 UnsignedLongTy,
8685 UnsignedLongTy,
8686 };
8687
8688 static const char *const FieldNames[] = {
8689 "reserved",
8690 "Size"
8691 };
8692
8693 for (size_t i = 0; i < 2; ++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, /*Mutable=*/false, InitStyle: ICIS_NoInit);
8698 Field->setAccess(AS_public);
8699 RD->addDecl(D: Field);
8700 }
8701
8702 RD->completeDefinition();
8703
8704 BlockDescriptorType = RD;
8705
8706 return getCanonicalTagType(TD: BlockDescriptorType);
8707}
8708
8709QualType ASTContext::getBlockDescriptorExtendedType() const {
8710 if (BlockDescriptorExtendedType)
8711 return getCanonicalTagType(TD: BlockDescriptorExtendedType);
8712
8713 RecordDecl *RD;
8714 // FIXME: Needs the FlagAppleBlock bit.
8715 RD = buildImplicitRecord(Name: "__block_descriptor_withcopydispose");
8716 RD->startDefinition();
8717
8718 QualType FieldTypes[] = {
8719 UnsignedLongTy,
8720 UnsignedLongTy,
8721 getPointerType(T: VoidPtrTy),
8722 getPointerType(T: VoidPtrTy)
8723 };
8724
8725 static const char *const FieldNames[] = {
8726 "reserved",
8727 "Size",
8728 "CopyFuncPtr",
8729 "DestroyFuncPtr"
8730 };
8731
8732 for (size_t i = 0; i < 4; ++i) {
8733 FieldDecl *Field = FieldDecl::Create(
8734 C: *this, DC: RD, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
8735 Id: &Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
8736 /*BitWidth=*/BW: nullptr,
8737 /*Mutable=*/false, InitStyle: ICIS_NoInit);
8738 Field->setAccess(AS_public);
8739 RD->addDecl(D: Field);
8740 }
8741
8742 RD->completeDefinition();
8743
8744 BlockDescriptorExtendedType = RD;
8745 return getCanonicalTagType(TD: BlockDescriptorExtendedType);
8746}
8747
8748OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
8749 const auto *BT = dyn_cast<BuiltinType>(Val: T);
8750
8751 if (!BT) {
8752 if (isa<PipeType>(Val: T))
8753 return OCLTK_Pipe;
8754
8755 return OCLTK_Default;
8756 }
8757
8758 switch (BT->getKind()) {
8759#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8760 case BuiltinType::Id: \
8761 return OCLTK_Image;
8762#include "clang/Basic/OpenCLImageTypes.def"
8763
8764 case BuiltinType::OCLClkEvent:
8765 return OCLTK_ClkEvent;
8766
8767 case BuiltinType::OCLEvent:
8768 return OCLTK_Event;
8769
8770 case BuiltinType::OCLQueue:
8771 return OCLTK_Queue;
8772
8773 case BuiltinType::OCLReserveID:
8774 return OCLTK_ReserveID;
8775
8776 case BuiltinType::OCLSampler:
8777 return OCLTK_Sampler;
8778
8779 default:
8780 return OCLTK_Default;
8781 }
8782}
8783
8784LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
8785 return Target->getOpenCLTypeAddrSpace(TK: getOpenCLTypeKind(T));
8786}
8787
8788/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8789/// requires copy/dispose. Note that this must match the logic
8790/// in buildByrefHelpers.
8791bool ASTContext::BlockRequiresCopying(QualType Ty,
8792 const VarDecl *D) {
8793 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8794 const Expr *copyExpr = getBlockVarCopyInit(VD: D).getCopyExpr();
8795 if (!copyExpr && record->hasTrivialDestructor()) return false;
8796
8797 return true;
8798 }
8799
8800 if (Ty.hasAddressDiscriminatedPointerAuth())
8801 return true;
8802
8803 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8804 // move or destroy.
8805 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
8806 return true;
8807
8808 if (!Ty->isObjCRetainableType()) return false;
8809
8810 Qualifiers qs = Ty.getQualifiers();
8811
8812 // If we have lifetime, that dominates.
8813 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8814 switch (lifetime) {
8815 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8816
8817 // These are just bits as far as the runtime is concerned.
8818 case Qualifiers::OCL_ExplicitNone:
8819 case Qualifiers::OCL_Autoreleasing:
8820 return false;
8821
8822 // These cases should have been taken care of when checking the type's
8823 // non-triviality.
8824 case Qualifiers::OCL_Weak:
8825 case Qualifiers::OCL_Strong:
8826 llvm_unreachable("impossible");
8827 }
8828 llvm_unreachable("fell out of lifetime switch!");
8829 }
8830 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8831 Ty->isObjCObjectPointerType());
8832}
8833
8834bool ASTContext::getByrefLifetime(QualType Ty,
8835 Qualifiers::ObjCLifetime &LifeTime,
8836 bool &HasByrefExtendedLayout) const {
8837 if (!getLangOpts().ObjC ||
8838 getLangOpts().getGC() != LangOptions::NonGC)
8839 return false;
8840
8841 HasByrefExtendedLayout = false;
8842 if (Ty->isRecordType()) {
8843 HasByrefExtendedLayout = true;
8844 LifeTime = Qualifiers::OCL_None;
8845 } else if ((LifeTime = Ty.getObjCLifetime())) {
8846 // Honor the ARC qualifiers.
8847 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8848 // The MRR rule.
8849 LifeTime = Qualifiers::OCL_ExplicitNone;
8850 } else {
8851 LifeTime = Qualifiers::OCL_None;
8852 }
8853 return true;
8854}
8855
8856CanQualType ASTContext::getNSUIntegerType() const {
8857 assert(Target && "Expected target to be initialized");
8858 const llvm::Triple &T = Target->getTriple();
8859 // Windows is LLP64 rather than LP64
8860 if (T.isOSWindows() && T.isArch64Bit())
8861 return UnsignedLongLongTy;
8862 return UnsignedLongTy;
8863}
8864
8865CanQualType ASTContext::getNSIntegerType() const {
8866 assert(Target && "Expected target to be initialized");
8867 const llvm::Triple &T = Target->getTriple();
8868 // Windows is LLP64 rather than LP64
8869 if (T.isOSWindows() && T.isArch64Bit())
8870 return LongLongTy;
8871 return LongTy;
8872}
8873
8874TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
8875 if (!ObjCInstanceTypeDecl)
8876 ObjCInstanceTypeDecl =
8877 buildImplicitTypedef(T: getObjCIdType(), Name: "instancetype");
8878 return ObjCInstanceTypeDecl;
8879}
8880
8881// This returns true if a type has been typedefed to BOOL:
8882// typedef <type> BOOL;
8883static bool isTypeTypedefedAsBOOL(QualType T) {
8884 if (const auto *TT = dyn_cast<TypedefType>(Val&: T))
8885 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8886 return II->isStr(Str: "BOOL");
8887
8888 return false;
8889}
8890
8891/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8892/// purpose.
8893CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
8894 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8895 return CharUnits::Zero();
8896
8897 CharUnits sz = getTypeSizeInChars(T: type);
8898
8899 // Make all integer and enum types at least as large as an int
8900 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8901 sz = std::max(a: sz, b: getTypeSizeInChars(T: IntTy));
8902 // Treat arrays as pointers, since that's how they're passed in.
8903 else if (type->isArrayType())
8904 sz = getTypeSizeInChars(T: VoidPtrTy);
8905 return sz;
8906}
8907
8908bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
8909 return getTargetInfo().getCXXABI().isMicrosoft() &&
8910 VD->isStaticDataMember() &&
8911 VD->getType()->isIntegralOrEnumerationType() &&
8912 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
8913}
8914
8915ASTContext::InlineVariableDefinitionKind
8916ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
8917 if (!VD->isInline())
8918 return InlineVariableDefinitionKind::None;
8919
8920 // In almost all cases, it's a weak definition.
8921 auto *First = VD->getFirstDecl();
8922 if (First->isInlineSpecified() || !First->isStaticDataMember())
8923 return InlineVariableDefinitionKind::Weak;
8924
8925 // If there's a file-context declaration in this translation unit, it's a
8926 // non-discardable definition.
8927 for (auto *D : VD->redecls())
8928 if (D->getLexicalDeclContext()->isFileContext() &&
8929 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8930 return InlineVariableDefinitionKind::Strong;
8931
8932 // If we've not seen one yet, we don't know.
8933 return InlineVariableDefinitionKind::WeakUnknown;
8934}
8935
8936static std::string charUnitsToString(const CharUnits &CU) {
8937 return llvm::itostr(X: CU.getQuantity());
8938}
8939
8940/// getObjCEncodingForBlock - Return the encoded type for this block
8941/// declaration.
8942std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
8943 std::string S;
8944
8945 const BlockDecl *Decl = Expr->getBlockDecl();
8946 QualType BlockTy =
8947 Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
8948 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8949 // Encode result type.
8950 if (getLangOpts().EncodeExtendedBlockSig)
8951 getObjCEncodingForMethodParameter(QT: Decl::OBJC_TQ_None, T: BlockReturnTy, S,
8952 Extended: true /*Extended*/);
8953 else
8954 getObjCEncodingForType(T: BlockReturnTy, S);
8955 // Compute size of all parameters.
8956 // Start with computing size of a pointer in number of bytes.
8957 // FIXME: There might(should) be a better way of doing this computation!
8958 CharUnits PtrSize = getTypeSizeInChars(T: VoidPtrTy);
8959 CharUnits ParmOffset = PtrSize;
8960 for (auto *PI : Decl->parameters()) {
8961 QualType PType = PI->getType();
8962 CharUnits sz = getObjCEncodingTypeSize(type: PType);
8963 if (sz.isZero())
8964 continue;
8965 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8966 ParmOffset += sz;
8967 }
8968 // Size of the argument frame
8969 S += charUnitsToString(CU: ParmOffset);
8970 // Block pointer and offset.
8971 S += "@?0";
8972
8973 // Argument types.
8974 ParmOffset = PtrSize;
8975 for (auto *PVDecl : Decl->parameters()) {
8976 QualType PType = PVDecl->getOriginalType();
8977 if (const auto *AT =
8978 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
8979 // Use array's original type only if it has known number of
8980 // elements.
8981 if (!isa<ConstantArrayType>(Val: AT))
8982 PType = PVDecl->getType();
8983 } else if (PType->isFunctionType())
8984 PType = PVDecl->getType();
8985 if (getLangOpts().EncodeExtendedBlockSig)
8986 getObjCEncodingForMethodParameter(QT: Decl::OBJC_TQ_None, T: PType,
8987 S, Extended: true /*Extended*/);
8988 else
8989 getObjCEncodingForType(T: PType, S);
8990 S += charUnitsToString(CU: ParmOffset);
8991 ParmOffset += getObjCEncodingTypeSize(type: PType);
8992 }
8993
8994 return S;
8995}
8996
8997std::string
8998ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
8999 std::string S;
9000 // Encode result type.
9001 getObjCEncodingForType(T: Decl->getReturnType(), S);
9002 CharUnits ParmOffset;
9003 // Compute size of all parameters.
9004 for (auto *PI : Decl->parameters()) {
9005 QualType PType = PI->getType();
9006 CharUnits sz = getObjCEncodingTypeSize(type: PType);
9007 if (sz.isZero())
9008 continue;
9009
9010 assert(sz.isPositive() &&
9011 "getObjCEncodingForFunctionDecl - Incomplete param type");
9012 ParmOffset += sz;
9013 }
9014 S += charUnitsToString(CU: ParmOffset);
9015 ParmOffset = CharUnits::Zero();
9016
9017 // Argument types.
9018 for (auto *PVDecl : Decl->parameters()) {
9019 QualType PType = PVDecl->getOriginalType();
9020 if (const auto *AT =
9021 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
9022 // Use array's original type only if it has known number of
9023 // elements.
9024 if (!isa<ConstantArrayType>(Val: AT))
9025 PType = PVDecl->getType();
9026 } else if (PType->isFunctionType())
9027 PType = PVDecl->getType();
9028 getObjCEncodingForType(T: PType, S);
9029 S += charUnitsToString(CU: ParmOffset);
9030 ParmOffset += getObjCEncodingTypeSize(type: PType);
9031 }
9032
9033 return S;
9034}
9035
9036/// getObjCEncodingForMethodParameter - Return the encoded type for a single
9037/// method parameter or return type. If Extended, include class names and
9038/// block object types.
9039void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
9040 QualType T, std::string& S,
9041 bool Extended) const {
9042 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
9043 getObjCEncodingForTypeQualifier(QT, S);
9044 // Encode parameter type.
9045 ObjCEncOptions Options = ObjCEncOptions()
9046 .setExpandPointedToStructures()
9047 .setExpandStructures()
9048 .setIsOutermostType();
9049 if (Extended)
9050 Options.setEncodeBlockParameters().setEncodeClassNames();
9051 getObjCEncodingForTypeImpl(t: T, S, Options, /*Field=*/nullptr);
9052}
9053
9054/// getObjCEncodingForMethodDecl - Return the encoded type for this method
9055/// declaration.
9056std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
9057 bool Extended) const {
9058 // FIXME: This is not very efficient.
9059 // Encode return type.
9060 std::string S;
9061 getObjCEncodingForMethodParameter(QT: Decl->getObjCDeclQualifier(),
9062 T: Decl->getReturnType(), S, Extended);
9063 // Compute size of all parameters.
9064 // Start with computing size of a pointer in number of bytes.
9065 // FIXME: There might(should) be a better way of doing this computation!
9066 CharUnits PtrSize = getTypeSizeInChars(T: VoidPtrTy);
9067 // The first two arguments (self and _cmd) are pointers; account for
9068 // their size.
9069 CharUnits ParmOffset = 2 * PtrSize;
9070 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9071 E = Decl->sel_param_end(); PI != E; ++PI) {
9072 QualType PType = (*PI)->getType();
9073 CharUnits sz = getObjCEncodingTypeSize(type: PType);
9074 if (sz.isZero())
9075 continue;
9076
9077 assert(sz.isPositive() &&
9078 "getObjCEncodingForMethodDecl - Incomplete param type");
9079 ParmOffset += sz;
9080 }
9081 S += charUnitsToString(CU: ParmOffset);
9082 S += "@0:";
9083 S += charUnitsToString(CU: PtrSize);
9084
9085 // Argument types.
9086 ParmOffset = 2 * PtrSize;
9087 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9088 E = Decl->sel_param_end(); PI != E; ++PI) {
9089 const ParmVarDecl *PVDecl = *PI;
9090 QualType PType = PVDecl->getOriginalType();
9091 if (const auto *AT =
9092 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
9093 // Use array's original type only if it has known number of
9094 // elements.
9095 if (!isa<ConstantArrayType>(Val: AT))
9096 PType = PVDecl->getType();
9097 } else if (PType->isFunctionType())
9098 PType = PVDecl->getType();
9099 getObjCEncodingForMethodParameter(QT: PVDecl->getObjCDeclQualifier(),
9100 T: PType, S, Extended);
9101 S += charUnitsToString(CU: ParmOffset);
9102 ParmOffset += getObjCEncodingTypeSize(type: PType);
9103 }
9104
9105 return S;
9106}
9107
9108ObjCPropertyImplDecl *
9109ASTContext::getObjCPropertyImplDeclForPropertyDecl(
9110 const ObjCPropertyDecl *PD,
9111 const Decl *Container) const {
9112 if (!Container)
9113 return nullptr;
9114 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Val: Container)) {
9115 for (auto *PID : CID->property_impls())
9116 if (PID->getPropertyDecl() == PD)
9117 return PID;
9118 } else {
9119 const auto *OID = cast<ObjCImplementationDecl>(Val: Container);
9120 for (auto *PID : OID->property_impls())
9121 if (PID->getPropertyDecl() == PD)
9122 return PID;
9123 }
9124 return nullptr;
9125}
9126
9127/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9128/// property declaration. If non-NULL, Container must be either an
9129/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9130/// NULL when getting encodings for protocol properties.
9131/// Property attributes are stored as a comma-delimited C string. The simple
9132/// attributes readonly and bycopy are encoded as single characters. The
9133/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9134/// encoded as single characters, followed by an identifier. Property types
9135/// are also encoded as a parametrized attribute. The characters used to encode
9136/// these attributes are defined by the following enumeration:
9137/// @code
9138/// enum PropertyAttributes {
9139/// kPropertyReadOnly = 'R', // property is read-only.
9140/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9141/// kPropertyByref = '&', // property is a reference to the value last assigned
9142/// kPropertyDynamic = 'D', // property is dynamic
9143/// kPropertyGetter = 'G', // followed by getter selector name
9144/// kPropertySetter = 'S', // followed by setter selector name
9145/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9146/// kPropertyType = 'T' // followed by old-style type encoding.
9147/// kPropertyWeak = 'W' // 'weak' property
9148/// kPropertyStrong = 'P' // property GC'able
9149/// kPropertyNonAtomic = 'N' // property non-atomic
9150/// kPropertyOptional = '?' // property optional
9151/// };
9152/// @endcode
9153std::string
9154ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
9155 const Decl *Container) const {
9156 // Collect information from the property implementation decl(s).
9157 bool Dynamic = false;
9158 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9159
9160 if (ObjCPropertyImplDecl *PropertyImpDecl =
9161 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
9162 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9163 Dynamic = true;
9164 else
9165 SynthesizePID = PropertyImpDecl;
9166 }
9167
9168 // FIXME: This is not very efficient.
9169 std::string S = "T";
9170
9171 // Encode result type.
9172 // GCC has some special rules regarding encoding of properties which
9173 // closely resembles encoding of ivars.
9174 getObjCEncodingForPropertyType(T: PD->getType(), S);
9175
9176 if (PD->isOptional())
9177 S += ",?";
9178
9179 if (PD->isReadOnly()) {
9180 S += ",R";
9181 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
9182 S += ",C";
9183 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
9184 S += ",&";
9185 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
9186 S += ",W";
9187 } else {
9188 switch (PD->getSetterKind()) {
9189 case ObjCPropertyDecl::Assign: break;
9190 case ObjCPropertyDecl::Copy: S += ",C"; break;
9191 case ObjCPropertyDecl::Retain: S += ",&"; break;
9192 case ObjCPropertyDecl::Weak: S += ",W"; break;
9193 }
9194 }
9195
9196 // It really isn't clear at all what this means, since properties
9197 // are "dynamic by default".
9198 if (Dynamic)
9199 S += ",D";
9200
9201 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
9202 S += ",N";
9203
9204 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
9205 S += ",G";
9206 S += PD->getGetterName().getAsString();
9207 }
9208
9209 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
9210 S += ",S";
9211 S += PD->getSetterName().getAsString();
9212 }
9213
9214 if (SynthesizePID) {
9215 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9216 S += ",V";
9217 S += OID->getNameAsString();
9218 }
9219
9220 // FIXME: OBJCGC: weak & strong
9221 return S;
9222}
9223
9224/// getLegacyIntegralTypeEncoding -
9225/// Another legacy compatibility encoding: 32-bit longs are encoded as
9226/// 'l' or 'L' , but not always. For typedefs, we need to use
9227/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9228void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
9229 if (PointeeTy->getAs<TypedefType>()) {
9230 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9231 if (BT->getKind() == BuiltinType::ULong && getIntWidth(T: PointeeTy) == 32)
9232 PointeeTy = UnsignedIntTy;
9233 else
9234 if (BT->getKind() == BuiltinType::Long && getIntWidth(T: PointeeTy) == 32)
9235 PointeeTy = IntTy;
9236 }
9237 }
9238}
9239
9240void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
9241 const FieldDecl *Field,
9242 QualType *NotEncodedT) const {
9243 // We follow the behavior of gcc, expanding structures which are
9244 // directly pointed to, and expanding embedded structures. Note that
9245 // these rules are sufficient to prevent recursive encoding of the
9246 // same type.
9247 getObjCEncodingForTypeImpl(t: T, S,
9248 Options: ObjCEncOptions()
9249 .setExpandPointedToStructures()
9250 .setExpandStructures()
9251 .setIsOutermostType(),
9252 Field, NotEncodedT);
9253}
9254
9255void ASTContext::getObjCEncodingForPropertyType(QualType T,
9256 std::string& S) const {
9257 // Encode result type.
9258 // GCC has some special rules regarding encoding of properties which
9259 // closely resembles encoding of ivars.
9260 getObjCEncodingForTypeImpl(t: T, S,
9261 Options: ObjCEncOptions()
9262 .setExpandPointedToStructures()
9263 .setExpandStructures()
9264 .setIsOutermostType()
9265 .setEncodingProperty(),
9266 /*Field=*/nullptr);
9267}
9268
9269static char getObjCEncodingForPrimitiveType(const ASTContext *C,
9270 const BuiltinType *BT) {
9271 BuiltinType::Kind kind = BT->getKind();
9272 switch (kind) {
9273 case BuiltinType::Void: return 'v';
9274 case BuiltinType::Bool: return 'B';
9275 case BuiltinType::Char8:
9276 case BuiltinType::Char_U:
9277 case BuiltinType::UChar: return 'C';
9278 case BuiltinType::Char16:
9279 case BuiltinType::UShort: return 'S';
9280 case BuiltinType::Char32:
9281 case BuiltinType::UInt: return 'I';
9282 case BuiltinType::ULong:
9283 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9284 case BuiltinType::UInt128: return 'T';
9285 case BuiltinType::ULongLong: return 'Q';
9286 case BuiltinType::Char_S:
9287 case BuiltinType::SChar: return 'c';
9288 case BuiltinType::Short: return 's';
9289 case BuiltinType::WChar_S:
9290 case BuiltinType::WChar_U:
9291 case BuiltinType::Int: return 'i';
9292 case BuiltinType::Long:
9293 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9294 case BuiltinType::LongLong: return 'q';
9295 case BuiltinType::Int128: return 't';
9296 case BuiltinType::Float: return 'f';
9297 case BuiltinType::Double: return 'd';
9298 case BuiltinType::LongDouble: return 'D';
9299 case BuiltinType::NullPtr: return '*'; // like char*
9300
9301 case BuiltinType::BFloat16:
9302 case BuiltinType::Float16:
9303 case BuiltinType::Float128:
9304 case BuiltinType::Ibm128:
9305 case BuiltinType::Half:
9306 case BuiltinType::ShortAccum:
9307 case BuiltinType::Accum:
9308 case BuiltinType::LongAccum:
9309 case BuiltinType::UShortAccum:
9310 case BuiltinType::UAccum:
9311 case BuiltinType::ULongAccum:
9312 case BuiltinType::ShortFract:
9313 case BuiltinType::Fract:
9314 case BuiltinType::LongFract:
9315 case BuiltinType::UShortFract:
9316 case BuiltinType::UFract:
9317 case BuiltinType::ULongFract:
9318 case BuiltinType::SatShortAccum:
9319 case BuiltinType::SatAccum:
9320 case BuiltinType::SatLongAccum:
9321 case BuiltinType::SatUShortAccum:
9322 case BuiltinType::SatUAccum:
9323 case BuiltinType::SatULongAccum:
9324 case BuiltinType::SatShortFract:
9325 case BuiltinType::SatFract:
9326 case BuiltinType::SatLongFract:
9327 case BuiltinType::SatUShortFract:
9328 case BuiltinType::SatUFract:
9329 case BuiltinType::SatULongFract:
9330 // FIXME: potentially need @encodes for these!
9331 return ' ';
9332
9333#define SVE_TYPE(Name, Id, SingletonId) \
9334 case BuiltinType::Id:
9335#include "clang/Basic/AArch64ACLETypes.def"
9336#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9337#include "clang/Basic/RISCVVTypes.def"
9338#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9339#include "clang/Basic/WebAssemblyReferenceTypes.def"
9340#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9341#include "clang/Basic/AMDGPUTypes.def"
9342#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9343#include "clang/Basic/SPIRVTypes.def"
9344 {
9345 DiagnosticsEngine &Diags = C->getDiagnostics();
9346 Diags.Report(DiagID: diag::err_unsupported_objc_primitive_encoding)
9347 << QualType(BT, 0);
9348 return ' ';
9349 }
9350
9351 case BuiltinType::ObjCId:
9352 case BuiltinType::ObjCClass:
9353 case BuiltinType::ObjCSel:
9354 llvm_unreachable("@encoding ObjC primitive type");
9355
9356 // OpenCL and placeholder types don't need @encodings.
9357#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9358 case BuiltinType::Id:
9359#include "clang/Basic/OpenCLImageTypes.def"
9360#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9361 case BuiltinType::Id:
9362#include "clang/Basic/OpenCLExtensionTypes.def"
9363 case BuiltinType::OCLEvent:
9364 case BuiltinType::OCLClkEvent:
9365 case BuiltinType::OCLQueue:
9366 case BuiltinType::OCLReserveID:
9367 case BuiltinType::OCLSampler:
9368 case BuiltinType::Dependent:
9369#define PPC_VECTOR_TYPE(Name, Id, Size) \
9370 case BuiltinType::Id:
9371#include "clang/Basic/PPCTypes.def"
9372#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9373#include "clang/Basic/HLSLIntangibleTypes.def"
9374#define BUILTIN_TYPE(KIND, ID)
9375#define PLACEHOLDER_TYPE(KIND, ID) \
9376 case BuiltinType::KIND:
9377#include "clang/AST/BuiltinTypes.def"
9378 llvm_unreachable("invalid builtin type for @encode");
9379 }
9380 llvm_unreachable("invalid BuiltinType::Kind value");
9381}
9382
9383static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9384 EnumDecl *Enum = ED->getDefinitionOrSelf();
9385
9386 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9387 if (!Enum->isFixed())
9388 return 'i';
9389
9390 // The encoding of a fixed enum type matches its fixed underlying type.
9391 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9392 return getObjCEncodingForPrimitiveType(C, BT);
9393}
9394
9395static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9396 QualType T, const FieldDecl *FD) {
9397 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9398 S += 'b';
9399 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9400 // The GNU runtime requires more information; bitfields are encoded as b,
9401 // then the offset (in bits) of the first element, then the type of the
9402 // bitfield, then the size in bits. For example, in this structure:
9403 //
9404 // struct
9405 // {
9406 // int integer;
9407 // int flags:2;
9408 // };
9409 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9410 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9411 // information is not especially sensible, but we're stuck with it for
9412 // compatibility with GCC, although providing it breaks anything that
9413 // actually uses runtime introspection and wants to work on both runtimes...
9414 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9415 uint64_t Offset;
9416
9417 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(Val: FD)) {
9418 Offset = Ctx->lookupFieldBitOffset(OID: IVD->getContainingInterface(), Ivar: IVD);
9419 } else {
9420 const RecordDecl *RD = FD->getParent();
9421 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(D: RD);
9422 Offset = RL.getFieldOffset(FieldNo: FD->getFieldIndex());
9423 }
9424
9425 S += llvm::utostr(X: Offset);
9426
9427 if (const auto *ET = T->getAsCanonical<EnumType>())
9428 S += ObjCEncodingForEnumDecl(C: Ctx, ED: ET->getDecl());
9429 else {
9430 const auto *BT = T->castAs<BuiltinType>();
9431 S += getObjCEncodingForPrimitiveType(C: Ctx, BT);
9432 }
9433 }
9434 S += llvm::utostr(X: FD->getBitWidthValue());
9435}
9436
9437// Helper function for determining whether the encoded type string would include
9438// a template specialization type.
9439static bool hasTemplateSpecializationInEncodedString(const Type *T,
9440 bool VisitBasesAndFields) {
9441 T = T->getBaseElementTypeUnsafe();
9442
9443 if (auto *PT = T->getAs<PointerType>())
9444 return hasTemplateSpecializationInEncodedString(
9445 T: PT->getPointeeType().getTypePtr(), VisitBasesAndFields: false);
9446
9447 auto *CXXRD = T->getAsCXXRecordDecl();
9448
9449 if (!CXXRD)
9450 return false;
9451
9452 if (isa<ClassTemplateSpecializationDecl>(Val: CXXRD))
9453 return true;
9454
9455 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9456 return false;
9457
9458 for (const auto &B : CXXRD->bases())
9459 if (hasTemplateSpecializationInEncodedString(T: B.getType().getTypePtr(),
9460 VisitBasesAndFields: true))
9461 return true;
9462
9463 for (auto *FD : CXXRD->fields())
9464 if (hasTemplateSpecializationInEncodedString(T: FD->getType().getTypePtr(),
9465 VisitBasesAndFields: true))
9466 return true;
9467
9468 return false;
9469}
9470
9471// FIXME: Use SmallString for accumulating string.
9472void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9473 const ObjCEncOptions Options,
9474 const FieldDecl *FD,
9475 QualType *NotEncodedT) const {
9476 CanQualType CT = getCanonicalType(T);
9477 switch (CT->getTypeClass()) {
9478 case Type::Builtin:
9479 case Type::Enum:
9480 if (FD && FD->isBitField())
9481 return EncodeBitField(Ctx: this, S, T, FD);
9482 if (const auto *BT = dyn_cast<BuiltinType>(Val&: CT))
9483 S += getObjCEncodingForPrimitiveType(C: this, BT);
9484 else
9485 S += ObjCEncodingForEnumDecl(C: this, ED: cast<EnumType>(Val&: CT)->getDecl());
9486 return;
9487
9488 case Type::Complex:
9489 S += 'j';
9490 getObjCEncodingForTypeImpl(T: T->castAs<ComplexType>()->getElementType(), S,
9491 Options: ObjCEncOptions(),
9492 /*Field=*/FD: nullptr);
9493 return;
9494
9495 case Type::Atomic:
9496 S += 'A';
9497 getObjCEncodingForTypeImpl(T: T->castAs<AtomicType>()->getValueType(), S,
9498 Options: ObjCEncOptions(),
9499 /*Field=*/FD: nullptr);
9500 return;
9501
9502 // encoding for pointer or reference types.
9503 case Type::Pointer:
9504 case Type::LValueReference:
9505 case Type::RValueReference: {
9506 QualType PointeeTy;
9507 if (isa<PointerType>(Val: CT)) {
9508 const auto *PT = T->castAs<PointerType>();
9509 if (PT->isObjCSelType()) {
9510 S += ':';
9511 return;
9512 }
9513 PointeeTy = PT->getPointeeType();
9514 } else {
9515 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9516 }
9517
9518 bool isReadOnly = false;
9519 // For historical/compatibility reasons, the read-only qualifier of the
9520 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9521 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9522 // Also, do not emit the 'r' for anything but the outermost type!
9523 if (T->getAs<TypedefType>()) {
9524 if (Options.IsOutermostType() && T.isConstQualified()) {
9525 isReadOnly = true;
9526 S += 'r';
9527 }
9528 } else if (Options.IsOutermostType()) {
9529 QualType P = PointeeTy;
9530 while (auto PT = P->getAs<PointerType>())
9531 P = PT->getPointeeType();
9532 if (P.isConstQualified()) {
9533 isReadOnly = true;
9534 S += 'r';
9535 }
9536 }
9537 if (isReadOnly) {
9538 // Another legacy compatibility encoding. Some ObjC qualifier and type
9539 // combinations need to be rearranged.
9540 // Rewrite "in const" from "nr" to "rn"
9541 if (StringRef(S).ends_with(Suffix: "nr"))
9542 S.replace(i1: S.end()-2, i2: S.end(), s: "rn");
9543 }
9544
9545 if (PointeeTy->isCharType()) {
9546 // char pointer types should be encoded as '*' unless it is a
9547 // type that has been typedef'd to 'BOOL'.
9548 if (!isTypeTypedefedAsBOOL(T: PointeeTy)) {
9549 S += '*';
9550 return;
9551 }
9552 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9553 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9554 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9555 if (II == &Idents.get(Name: "objc_class")) {
9556 S += '#';
9557 return;
9558 }
9559 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9560 if (II == &Idents.get(Name: "objc_object")) {
9561 S += '@';
9562 return;
9563 }
9564 // If the encoded string for the class includes template names, just emit
9565 // "^v" for pointers to the class.
9566 if (getLangOpts().CPlusPlus &&
9567 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9568 hasTemplateSpecializationInEncodedString(
9569 T: RTy, VisitBasesAndFields: Options.ExpandPointedToStructures()))) {
9570 S += "^v";
9571 return;
9572 }
9573 // fall through...
9574 }
9575 S += '^';
9576 getLegacyIntegralTypeEncoding(PointeeTy);
9577
9578 ObjCEncOptions NewOptions;
9579 if (Options.ExpandPointedToStructures())
9580 NewOptions.setExpandStructures();
9581 getObjCEncodingForTypeImpl(T: PointeeTy, S, Options: NewOptions,
9582 /*Field=*/FD: nullptr, NotEncodedT);
9583 return;
9584 }
9585
9586 case Type::ConstantArray:
9587 case Type::IncompleteArray:
9588 case Type::VariableArray: {
9589 const auto *AT = cast<ArrayType>(Val&: CT);
9590
9591 if (isa<IncompleteArrayType>(Val: AT) && !Options.IsStructField()) {
9592 // Incomplete arrays are encoded as a pointer to the array element.
9593 S += '^';
9594
9595 getObjCEncodingForTypeImpl(
9596 T: AT->getElementType(), S,
9597 Options: Options.keepingOnly(Mask: ObjCEncOptions().setExpandStructures()), FD);
9598 } else {
9599 S += '[';
9600
9601 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT))
9602 S += llvm::utostr(X: CAT->getZExtSize());
9603 else {
9604 //Variable length arrays are encoded as a regular array with 0 elements.
9605 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
9606 "Unknown array type!");
9607 S += '0';
9608 }
9609
9610 getObjCEncodingForTypeImpl(
9611 T: AT->getElementType(), S,
9612 Options: Options.keepingOnly(Mask: ObjCEncOptions().setExpandStructures()), FD,
9613 NotEncodedT);
9614 S += ']';
9615 }
9616 return;
9617 }
9618
9619 case Type::FunctionNoProto:
9620 case Type::FunctionProto:
9621 S += '?';
9622 return;
9623
9624 case Type::Record: {
9625 RecordDecl *RDecl = cast<RecordType>(Val&: CT)->getDecl();
9626 S += RDecl->isUnion() ? '(' : '{';
9627 // Anonymous structures print as '?'
9628 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9629 S += II->getName();
9630 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: RDecl)) {
9631 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9632 llvm::raw_string_ostream OS(S);
9633 printTemplateArgumentList(OS, Args: TemplateArgs.asArray(),
9634 Policy: getPrintingPolicy());
9635 }
9636 } else {
9637 S += '?';
9638 }
9639 if (Options.ExpandStructures()) {
9640 S += '=';
9641 if (!RDecl->isUnion()) {
9642 getObjCEncodingForStructureImpl(RD: RDecl, S, Field: FD, includeVBases: true, NotEncodedT);
9643 } else {
9644 for (const auto *Field : RDecl->fields()) {
9645 if (FD) {
9646 S += '"';
9647 S += Field->getNameAsString();
9648 S += '"';
9649 }
9650
9651 // Special case bit-fields.
9652 if (Field->isBitField()) {
9653 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9654 Options: ObjCEncOptions().setExpandStructures(),
9655 FD: Field);
9656 } else {
9657 QualType qt = Field->getType();
9658 getLegacyIntegralTypeEncoding(PointeeTy&: qt);
9659 getObjCEncodingForTypeImpl(
9660 T: qt, S,
9661 Options: ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9662 NotEncodedT);
9663 }
9664 }
9665 }
9666 }
9667 S += RDecl->isUnion() ? ')' : '}';
9668 return;
9669 }
9670
9671 case Type::BlockPointer: {
9672 const auto *BT = T->castAs<BlockPointerType>();
9673 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9674 if (Options.EncodeBlockParameters()) {
9675 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9676
9677 S += '<';
9678 // Block return type
9679 getObjCEncodingForTypeImpl(T: FT->getReturnType(), S,
9680 Options: Options.forComponentType(), FD, NotEncodedT);
9681 // Block self
9682 S += "@?";
9683 // Block parameters
9684 if (const auto *FPT = dyn_cast<FunctionProtoType>(Val: FT)) {
9685 for (const auto &I : FPT->param_types())
9686 getObjCEncodingForTypeImpl(T: I, S, Options: Options.forComponentType(), FD,
9687 NotEncodedT);
9688 }
9689 S += '>';
9690 }
9691 return;
9692 }
9693
9694 case Type::ObjCObject: {
9695 // hack to match legacy encoding of *id and *Class
9696 QualType Ty = getObjCObjectPointerType(ObjectT: CT);
9697 if (Ty->isObjCIdType()) {
9698 S += "{objc_object=}";
9699 return;
9700 }
9701 else if (Ty->isObjCClassType()) {
9702 S += "{objc_class=}";
9703 return;
9704 }
9705 // TODO: Double check to make sure this intentionally falls through.
9706 [[fallthrough]];
9707 }
9708
9709 case Type::ObjCInterface: {
9710 // Ignore protocol qualifiers when mangling at this level.
9711 // @encode(class_name)
9712 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9713 S += '{';
9714 S += OI->getObjCRuntimeNameAsString();
9715 if (Options.ExpandStructures()) {
9716 S += '=';
9717 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9718 DeepCollectObjCIvars(OI, leafClass: true, Ivars);
9719 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9720 const FieldDecl *Field = Ivars[i];
9721 if (Field->isBitField())
9722 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9723 Options: ObjCEncOptions().setExpandStructures(),
9724 FD: Field);
9725 else
9726 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9727 Options: ObjCEncOptions().setExpandStructures(), FD,
9728 NotEncodedT);
9729 }
9730 }
9731 S += '}';
9732 return;
9733 }
9734
9735 case Type::ObjCObjectPointer: {
9736 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9737 if (OPT->isObjCIdType()) {
9738 S += '@';
9739 return;
9740 }
9741
9742 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9743 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9744 // Since this is a binary compatibility issue, need to consult with
9745 // runtime folks. Fortunately, this is a *very* obscure construct.
9746 S += '#';
9747 return;
9748 }
9749
9750 if (OPT->isObjCQualifiedIdType()) {
9751 getObjCEncodingForTypeImpl(
9752 T: getObjCIdType(), S,
9753 Options: Options.keepingOnly(Mask: ObjCEncOptions()
9754 .setExpandPointedToStructures()
9755 .setExpandStructures()),
9756 FD);
9757 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9758 // Note that we do extended encoding of protocol qualifier list
9759 // Only when doing ivar or property encoding.
9760 S += '"';
9761 for (const auto *I : OPT->quals()) {
9762 S += '<';
9763 S += I->getObjCRuntimeNameAsString();
9764 S += '>';
9765 }
9766 S += '"';
9767 }
9768 return;
9769 }
9770
9771 S += '@';
9772 if (OPT->getInterfaceDecl() &&
9773 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9774 S += '"';
9775 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9776 for (const auto *I : OPT->quals()) {
9777 S += '<';
9778 S += I->getObjCRuntimeNameAsString();
9779 S += '>';
9780 }
9781 S += '"';
9782 }
9783 return;
9784 }
9785
9786 // gcc just blithely ignores member pointers.
9787 // FIXME: we should do better than that. 'M' is available.
9788 case Type::MemberPointer:
9789 // This matches gcc's encoding, even though technically it is insufficient.
9790 //FIXME. We should do a better job than gcc.
9791 case Type::Vector:
9792 case Type::ExtVector:
9793 // Until we have a coherent encoding of these three types, issue warning.
9794 if (NotEncodedT)
9795 *NotEncodedT = T;
9796 return;
9797
9798 case Type::ConstantMatrix:
9799 if (NotEncodedT)
9800 *NotEncodedT = T;
9801 return;
9802
9803 case Type::BitInt:
9804 if (NotEncodedT)
9805 *NotEncodedT = T;
9806 return;
9807
9808 // We could see an undeduced auto type here during error recovery.
9809 // Just ignore it.
9810 case Type::Auto:
9811 case Type::DeducedTemplateSpecialization:
9812 return;
9813
9814 case Type::HLSLAttributedResource:
9815 case Type::HLSLInlineSpirv:
9816 case Type::OverflowBehavior:
9817 llvm_unreachable("unexpected type");
9818
9819 case Type::ArrayParameter:
9820 case Type::Pipe:
9821#define ABSTRACT_TYPE(KIND, BASE)
9822#define TYPE(KIND, BASE)
9823#define DEPENDENT_TYPE(KIND, BASE) \
9824 case Type::KIND:
9825#define NON_CANONICAL_TYPE(KIND, BASE) \
9826 case Type::KIND:
9827#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9828 case Type::KIND:
9829#include "clang/AST/TypeNodes.inc"
9830 llvm_unreachable("@encode for dependent type!");
9831 }
9832 llvm_unreachable("bad type kind!");
9833}
9834
9835void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9836 std::string &S,
9837 const FieldDecl *FD,
9838 bool includeVBases,
9839 QualType *NotEncodedT) const {
9840 assert(RDecl && "Expected non-null RecordDecl");
9841 assert(!RDecl->isUnion() && "Should not be called for unions");
9842 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9843 return;
9844
9845 const auto *CXXRec = dyn_cast<CXXRecordDecl>(Val: RDecl);
9846 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9847 const ASTRecordLayout &layout = getASTRecordLayout(D: RDecl);
9848
9849 if (CXXRec) {
9850 for (const auto &BI : CXXRec->bases()) {
9851 if (!BI.isVirtual()) {
9852 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9853 if (base->isEmpty())
9854 continue;
9855 uint64_t offs = toBits(CharSize: layout.getBaseClassOffset(Base: base));
9856 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9857 x: std::make_pair(x&: offs, y&: base));
9858 }
9859 }
9860 }
9861
9862 for (FieldDecl *Field : RDecl->fields()) {
9863 if (!Field->isZeroLengthBitField() && Field->isZeroSize(Ctx: *this))
9864 continue;
9865 uint64_t offs = layout.getFieldOffset(FieldNo: Field->getFieldIndex());
9866 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9867 x: std::make_pair(x&: offs, y&: Field));
9868 }
9869
9870 if (CXXRec && includeVBases) {
9871 for (const auto &BI : CXXRec->vbases()) {
9872 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9873 if (base->isEmpty())
9874 continue;
9875 uint64_t offs = toBits(CharSize: layout.getVBaseClassOffset(VBase: base));
9876 if (offs >= uint64_t(toBits(CharSize: layout.getNonVirtualSize())) &&
9877 FieldOrBaseOffsets.find(x: offs) == FieldOrBaseOffsets.end())
9878 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.end(),
9879 x: std::make_pair(x&: offs, y&: base));
9880 }
9881 }
9882
9883 CharUnits size;
9884 if (CXXRec) {
9885 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9886 } else {
9887 size = layout.getSize();
9888 }
9889
9890#ifndef NDEBUG
9891 uint64_t CurOffs = 0;
9892#endif
9893 std::multimap<uint64_t, NamedDecl *>::iterator
9894 CurLayObj = FieldOrBaseOffsets.begin();
9895
9896 if (CXXRec && CXXRec->isDynamicClass() &&
9897 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9898 if (FD) {
9899 S += "\"_vptr$";
9900 std::string recname = CXXRec->getNameAsString();
9901 if (recname.empty()) recname = "?";
9902 S += recname;
9903 S += '"';
9904 }
9905 S += "^^?";
9906#ifndef NDEBUG
9907 CurOffs += getTypeSize(VoidPtrTy);
9908#endif
9909 }
9910
9911 if (!RDecl->hasFlexibleArrayMember()) {
9912 // Mark the end of the structure.
9913 uint64_t offs = toBits(CharSize: size);
9914 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9915 x: std::make_pair(x&: offs, y: nullptr));
9916 }
9917
9918 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9919#ifndef NDEBUG
9920 assert(CurOffs <= CurLayObj->first);
9921 if (CurOffs < CurLayObj->first) {
9922 uint64_t padding = CurLayObj->first - CurOffs;
9923 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9924 // packing/alignment of members is different that normal, in which case
9925 // the encoding will be out-of-sync with the real layout.
9926 // If the runtime switches to just consider the size of types without
9927 // taking into account alignment, we could make padding explicit in the
9928 // encoding (e.g. using arrays of chars). The encoding strings would be
9929 // longer then though.
9930 CurOffs += padding;
9931 }
9932#endif
9933
9934 NamedDecl *dcl = CurLayObj->second;
9935 if (!dcl)
9936 break; // reached end of structure.
9937
9938 if (auto *base = dyn_cast<CXXRecordDecl>(Val: dcl)) {
9939 // We expand the bases without their virtual bases since those are going
9940 // in the initial structure. Note that this differs from gcc which
9941 // expands virtual bases each time one is encountered in the hierarchy,
9942 // making the encoding type bigger than it really is.
9943 getObjCEncodingForStructureImpl(RDecl: base, S, FD, /*includeVBases*/false,
9944 NotEncodedT);
9945 assert(!base->isEmpty());
9946#ifndef NDEBUG
9947 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9948#endif
9949 } else {
9950 const auto *field = cast<FieldDecl>(Val: dcl);
9951 if (FD) {
9952 S += '"';
9953 S += field->getNameAsString();
9954 S += '"';
9955 }
9956
9957 if (field->isBitField()) {
9958 EncodeBitField(Ctx: this, S, T: field->getType(), FD: field);
9959#ifndef NDEBUG
9960 CurOffs += field->getBitWidthValue();
9961#endif
9962 } else {
9963 QualType qt = field->getType();
9964 getLegacyIntegralTypeEncoding(PointeeTy&: qt);
9965 getObjCEncodingForTypeImpl(
9966 T: qt, S, Options: ObjCEncOptions().setExpandStructures().setIsStructField(),
9967 FD, NotEncodedT);
9968#ifndef NDEBUG
9969 CurOffs += getTypeSize(field->getType());
9970#endif
9971 }
9972 }
9973 }
9974}
9975
9976void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
9977 std::string& S) const {
9978 if (QT & Decl::OBJC_TQ_In)
9979 S += 'n';
9980 if (QT & Decl::OBJC_TQ_Inout)
9981 S += 'N';
9982 if (QT & Decl::OBJC_TQ_Out)
9983 S += 'o';
9984 if (QT & Decl::OBJC_TQ_Bycopy)
9985 S += 'O';
9986 if (QT & Decl::OBJC_TQ_Byref)
9987 S += 'R';
9988 if (QT & Decl::OBJC_TQ_Oneway)
9989 S += 'V';
9990}
9991
9992TypedefDecl *ASTContext::getObjCIdDecl() const {
9993 if (!ObjCIdDecl) {
9994 QualType T = getObjCObjectType(BaseType: ObjCBuiltinIdTy, Protocols: {}, NumProtocols: {});
9995 T = getObjCObjectPointerType(ObjectT: T);
9996 ObjCIdDecl = buildImplicitTypedef(T, Name: "id");
9997 }
9998 return ObjCIdDecl;
9999}
10000
10001TypedefDecl *ASTContext::getObjCSelDecl() const {
10002 if (!ObjCSelDecl) {
10003 QualType T = getPointerType(T: ObjCBuiltinSelTy);
10004 ObjCSelDecl = buildImplicitTypedef(T, Name: "SEL");
10005 }
10006 return ObjCSelDecl;
10007}
10008
10009TypedefDecl *ASTContext::getObjCClassDecl() const {
10010 if (!ObjCClassDecl) {
10011 QualType T = getObjCObjectType(BaseType: ObjCBuiltinClassTy, Protocols: {}, NumProtocols: {});
10012 T = getObjCObjectPointerType(ObjectT: T);
10013 ObjCClassDecl = buildImplicitTypedef(T, Name: "Class");
10014 }
10015 return ObjCClassDecl;
10016}
10017
10018ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
10019 if (!ObjCProtocolClassDecl) {
10020 ObjCProtocolClassDecl
10021 = ObjCInterfaceDecl::Create(C: *this, DC: getTranslationUnitDecl(),
10022 atLoc: SourceLocation(),
10023 Id: &Idents.get(Name: "Protocol"),
10024 /*typeParamList=*/nullptr,
10025 /*PrevDecl=*/nullptr,
10026 ClassLoc: SourceLocation(), isInternal: true);
10027 }
10028
10029 return ObjCProtocolClassDecl;
10030}
10031
10032PointerAuthQualifier ASTContext::getObjCMemberSelTypePtrAuth() {
10033 if (!getLangOpts().PointerAuthObjcInterfaceSel)
10034 return PointerAuthQualifier();
10035 return PointerAuthQualifier::Create(
10036 Key: getLangOpts().PointerAuthObjcInterfaceSelKey,
10037 /*isAddressDiscriminated=*/IsAddressDiscriminated: true, ExtraDiscriminator: SelPointerConstantDiscriminator,
10038 AuthenticationMode: PointerAuthenticationMode::SignAndAuth,
10039 /*isIsaPointer=*/IsIsaPointer: false,
10040 /*authenticatesNullValues=*/AuthenticatesNullValues: false);
10041}
10042
10043//===----------------------------------------------------------------------===//
10044// __builtin_va_list Construction Functions
10045//===----------------------------------------------------------------------===//
10046
10047static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
10048 StringRef Name) {
10049 // typedef char* __builtin[_ms]_va_list;
10050 QualType T = Context->getPointerType(T: Context->CharTy);
10051 return Context->buildImplicitTypedef(T, Name);
10052}
10053
10054static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
10055 return CreateCharPtrNamedVaListDecl(Context, Name: "__builtin_ms_va_list");
10056}
10057
10058static TypedefDecl *CreateZOSVaListDecl(const ASTContext *Context) {
10059 // typedef char *__builtin_zos_va_list[2];
10060 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 2);
10061 QualType T = Context->getPointerType(T: Context->CharTy);
10062 QualType ArrayType = Context->getConstantArrayType(
10063 EltTy: T, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10064 return Context->buildImplicitTypedef(T: ArrayType, Name: "__builtin_zos_va_list");
10065}
10066
10067static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
10068 return CreateCharPtrNamedVaListDecl(Context, Name: "__builtin_va_list");
10069}
10070
10071static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
10072 // typedef void* __builtin_va_list;
10073 QualType T = Context->getPointerType(T: Context->VoidTy);
10074 return Context->buildImplicitTypedef(T, Name: "__builtin_va_list");
10075}
10076
10077static TypedefDecl *
10078CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
10079 // struct __va_list
10080 RecordDecl *VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list");
10081 if (Context->getLangOpts().CPlusPlus) {
10082 // namespace std { struct __va_list {
10083 auto *NS = NamespaceDecl::Create(
10084 C&: const_cast<ASTContext &>(*Context), DC: Context->getTranslationUnitDecl(),
10085 /*Inline=*/false, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
10086 Id: &Context->Idents.get(Name: "std"),
10087 /*PrevDecl=*/nullptr, /*Nested=*/false);
10088 NS->setImplicit();
10089 VaListTagDecl->setDeclContext(NS);
10090 }
10091
10092 VaListTagDecl->startDefinition();
10093
10094 const size_t NumFields = 5;
10095 QualType FieldTypes[NumFields];
10096 const char *FieldNames[NumFields];
10097
10098 // void *__stack;
10099 FieldTypes[0] = Context->getPointerType(T: Context->VoidTy);
10100 FieldNames[0] = "__stack";
10101
10102 // void *__gr_top;
10103 FieldTypes[1] = Context->getPointerType(T: Context->VoidTy);
10104 FieldNames[1] = "__gr_top";
10105
10106 // void *__vr_top;
10107 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10108 FieldNames[2] = "__vr_top";
10109
10110 // int __gr_offs;
10111 FieldTypes[3] = Context->IntTy;
10112 FieldNames[3] = "__gr_offs";
10113
10114 // int __vr_offs;
10115 FieldTypes[4] = Context->IntTy;
10116 FieldNames[4] = "__vr_offs";
10117
10118 // Create fields
10119 for (unsigned i = 0; i < NumFields; ++i) {
10120 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10121 DC: VaListTagDecl,
10122 StartLoc: SourceLocation(),
10123 IdLoc: SourceLocation(),
10124 Id: &Context->Idents.get(Name: FieldNames[i]),
10125 T: FieldTypes[i], /*TInfo=*/nullptr,
10126 /*BitWidth=*/BW: nullptr,
10127 /*Mutable=*/false,
10128 InitStyle: ICIS_NoInit);
10129 Field->setAccess(AS_public);
10130 VaListTagDecl->addDecl(D: Field);
10131 }
10132 VaListTagDecl->completeDefinition();
10133 Context->VaListTagDecl = VaListTagDecl;
10134 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10135
10136 // } __builtin_va_list;
10137 return Context->buildImplicitTypedef(T: VaListTagType, Name: "__builtin_va_list");
10138}
10139
10140static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
10141 // typedef struct __va_list_tag {
10142 RecordDecl *VaListTagDecl;
10143
10144 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10145 VaListTagDecl->startDefinition();
10146
10147 const size_t NumFields = 5;
10148 QualType FieldTypes[NumFields];
10149 const char *FieldNames[NumFields];
10150
10151 // unsigned char gpr;
10152 FieldTypes[0] = Context->UnsignedCharTy;
10153 FieldNames[0] = "gpr";
10154
10155 // unsigned char fpr;
10156 FieldTypes[1] = Context->UnsignedCharTy;
10157 FieldNames[1] = "fpr";
10158
10159 // unsigned short reserved;
10160 FieldTypes[2] = Context->UnsignedShortTy;
10161 FieldNames[2] = "reserved";
10162
10163 // void* overflow_arg_area;
10164 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10165 FieldNames[3] = "overflow_arg_area";
10166
10167 // void* reg_save_area;
10168 FieldTypes[4] = Context->getPointerType(T: Context->VoidTy);
10169 FieldNames[4] = "reg_save_area";
10170
10171 // Create fields
10172 for (unsigned i = 0; i < NumFields; ++i) {
10173 FieldDecl *Field = FieldDecl::Create(C: *Context, DC: VaListTagDecl,
10174 StartLoc: SourceLocation(),
10175 IdLoc: SourceLocation(),
10176 Id: &Context->Idents.get(Name: FieldNames[i]),
10177 T: FieldTypes[i], /*TInfo=*/nullptr,
10178 /*BitWidth=*/BW: nullptr,
10179 /*Mutable=*/false,
10180 InitStyle: ICIS_NoInit);
10181 Field->setAccess(AS_public);
10182 VaListTagDecl->addDecl(D: Field);
10183 }
10184 VaListTagDecl->completeDefinition();
10185 Context->VaListTagDecl = VaListTagDecl;
10186 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10187
10188 // } __va_list_tag;
10189 TypedefDecl *VaListTagTypedefDecl =
10190 Context->buildImplicitTypedef(T: VaListTagType, Name: "__va_list_tag");
10191
10192 QualType VaListTagTypedefType =
10193 Context->getTypedefType(Keyword: ElaboratedTypeKeyword::None,
10194 /*Qualifier=*/std::nullopt, Decl: VaListTagTypedefDecl);
10195
10196 // typedef __va_list_tag __builtin_va_list[1];
10197 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10198 QualType VaListTagArrayType = Context->getConstantArrayType(
10199 EltTy: VaListTagTypedefType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10200 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10201}
10202
10203static TypedefDecl *
10204CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
10205 // struct __va_list_tag {
10206 RecordDecl *VaListTagDecl;
10207 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10208 VaListTagDecl->startDefinition();
10209
10210 const size_t NumFields = 4;
10211 QualType FieldTypes[NumFields];
10212 const char *FieldNames[NumFields];
10213
10214 // unsigned gp_offset;
10215 FieldTypes[0] = Context->UnsignedIntTy;
10216 FieldNames[0] = "gp_offset";
10217
10218 // unsigned fp_offset;
10219 FieldTypes[1] = Context->UnsignedIntTy;
10220 FieldNames[1] = "fp_offset";
10221
10222 // void* overflow_arg_area;
10223 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10224 FieldNames[2] = "overflow_arg_area";
10225
10226 // void* reg_save_area;
10227 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10228 FieldNames[3] = "reg_save_area";
10229
10230 // Create fields
10231 for (unsigned i = 0; i < NumFields; ++i) {
10232 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10233 DC: VaListTagDecl,
10234 StartLoc: SourceLocation(),
10235 IdLoc: SourceLocation(),
10236 Id: &Context->Idents.get(Name: FieldNames[i]),
10237 T: FieldTypes[i], /*TInfo=*/nullptr,
10238 /*BitWidth=*/BW: nullptr,
10239 /*Mutable=*/false,
10240 InitStyle: ICIS_NoInit);
10241 Field->setAccess(AS_public);
10242 VaListTagDecl->addDecl(D: Field);
10243 }
10244 VaListTagDecl->completeDefinition();
10245 Context->VaListTagDecl = VaListTagDecl;
10246 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10247
10248 // };
10249
10250 // typedef struct __va_list_tag __builtin_va_list[1];
10251 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10252 QualType VaListTagArrayType = Context->getConstantArrayType(
10253 EltTy: VaListTagType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10254 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10255}
10256
10257static TypedefDecl *
10258CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
10259 // struct __va_list
10260 RecordDecl *VaListDecl = Context->buildImplicitRecord(Name: "__va_list");
10261 if (Context->getLangOpts().CPlusPlus) {
10262 // namespace std { struct __va_list {
10263 NamespaceDecl *NS;
10264 NS = NamespaceDecl::Create(C&: const_cast<ASTContext &>(*Context),
10265 DC: Context->getTranslationUnitDecl(),
10266 /*Inline=*/false, StartLoc: SourceLocation(),
10267 IdLoc: SourceLocation(), Id: &Context->Idents.get(Name: "std"),
10268 /*PrevDecl=*/nullptr, /*Nested=*/false);
10269 NS->setImplicit();
10270 VaListDecl->setDeclContext(NS);
10271 }
10272
10273 VaListDecl->startDefinition();
10274
10275 // void * __ap;
10276 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10277 DC: VaListDecl,
10278 StartLoc: SourceLocation(),
10279 IdLoc: SourceLocation(),
10280 Id: &Context->Idents.get(Name: "__ap"),
10281 T: Context->getPointerType(T: Context->VoidTy),
10282 /*TInfo=*/nullptr,
10283 /*BitWidth=*/BW: nullptr,
10284 /*Mutable=*/false,
10285 InitStyle: ICIS_NoInit);
10286 Field->setAccess(AS_public);
10287 VaListDecl->addDecl(D: Field);
10288
10289 // };
10290 VaListDecl->completeDefinition();
10291 Context->VaListTagDecl = VaListDecl;
10292
10293 // typedef struct __va_list __builtin_va_list;
10294 CanQualType T = Context->getCanonicalTagType(TD: VaListDecl);
10295 return Context->buildImplicitTypedef(T, Name: "__builtin_va_list");
10296}
10297
10298static TypedefDecl *
10299CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
10300 // struct __va_list_tag {
10301 RecordDecl *VaListTagDecl;
10302 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10303 VaListTagDecl->startDefinition();
10304
10305 const size_t NumFields = 4;
10306 QualType FieldTypes[NumFields];
10307 const char *FieldNames[NumFields];
10308
10309 // long __gpr;
10310 FieldTypes[0] = Context->LongTy;
10311 FieldNames[0] = "__gpr";
10312
10313 // long __fpr;
10314 FieldTypes[1] = Context->LongTy;
10315 FieldNames[1] = "__fpr";
10316
10317 // void *__overflow_arg_area;
10318 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10319 FieldNames[2] = "__overflow_arg_area";
10320
10321 // void *__reg_save_area;
10322 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10323 FieldNames[3] = "__reg_save_area";
10324
10325 // Create fields
10326 for (unsigned i = 0; i < NumFields; ++i) {
10327 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10328 DC: VaListTagDecl,
10329 StartLoc: SourceLocation(),
10330 IdLoc: SourceLocation(),
10331 Id: &Context->Idents.get(Name: FieldNames[i]),
10332 T: FieldTypes[i], /*TInfo=*/nullptr,
10333 /*BitWidth=*/BW: nullptr,
10334 /*Mutable=*/false,
10335 InitStyle: ICIS_NoInit);
10336 Field->setAccess(AS_public);
10337 VaListTagDecl->addDecl(D: Field);
10338 }
10339 VaListTagDecl->completeDefinition();
10340 Context->VaListTagDecl = VaListTagDecl;
10341 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10342
10343 // };
10344
10345 // typedef __va_list_tag __builtin_va_list[1];
10346 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10347 QualType VaListTagArrayType = Context->getConstantArrayType(
10348 EltTy: VaListTagType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10349
10350 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10351}
10352
10353static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
10354 // typedef struct __va_list_tag {
10355 RecordDecl *VaListTagDecl;
10356 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10357 VaListTagDecl->startDefinition();
10358
10359 const size_t NumFields = 3;
10360 QualType FieldTypes[NumFields];
10361 const char *FieldNames[NumFields];
10362
10363 // void *CurrentSavedRegisterArea;
10364 FieldTypes[0] = Context->getPointerType(T: Context->VoidTy);
10365 FieldNames[0] = "__current_saved_reg_area_pointer";
10366
10367 // void *SavedRegAreaEnd;
10368 FieldTypes[1] = Context->getPointerType(T: Context->VoidTy);
10369 FieldNames[1] = "__saved_reg_area_end_pointer";
10370
10371 // void *OverflowArea;
10372 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10373 FieldNames[2] = "__overflow_area_pointer";
10374
10375 // Create fields
10376 for (unsigned i = 0; i < NumFields; ++i) {
10377 FieldDecl *Field = FieldDecl::Create(
10378 C: const_cast<ASTContext &>(*Context), DC: VaListTagDecl, StartLoc: SourceLocation(),
10379 IdLoc: SourceLocation(), Id: &Context->Idents.get(Name: FieldNames[i]), T: FieldTypes[i],
10380 /*TInfo=*/nullptr,
10381 /*BitWidth=*/BW: nullptr,
10382 /*Mutable=*/false, InitStyle: ICIS_NoInit);
10383 Field->setAccess(AS_public);
10384 VaListTagDecl->addDecl(D: Field);
10385 }
10386 VaListTagDecl->completeDefinition();
10387 Context->VaListTagDecl = VaListTagDecl;
10388 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10389
10390 // } __va_list_tag;
10391 TypedefDecl *VaListTagTypedefDecl =
10392 Context->buildImplicitTypedef(T: VaListTagType, Name: "__va_list_tag");
10393
10394 QualType VaListTagTypedefType =
10395 Context->getTypedefType(Keyword: ElaboratedTypeKeyword::None,
10396 /*Qualifier=*/std::nullopt, Decl: VaListTagTypedefDecl);
10397
10398 // typedef __va_list_tag __builtin_va_list[1];
10399 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10400 QualType VaListTagArrayType = Context->getConstantArrayType(
10401 EltTy: VaListTagTypedefType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10402
10403 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10404}
10405
10406static TypedefDecl *
10407CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context) {
10408 // typedef struct __va_list_tag {
10409 RecordDecl *VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10410
10411 VaListTagDecl->startDefinition();
10412
10413 // int* __va_stk;
10414 // int* __va_reg;
10415 // int __va_ndx;
10416 constexpr size_t NumFields = 3;
10417 QualType FieldTypes[NumFields] = {Context->getPointerType(T: Context->IntTy),
10418 Context->getPointerType(T: Context->IntTy),
10419 Context->IntTy};
10420 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10421
10422 // Create fields
10423 for (unsigned i = 0; i < NumFields; ++i) {
10424 FieldDecl *Field = FieldDecl::Create(
10425 C: *Context, DC: VaListTagDecl, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
10426 Id: &Context->Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
10427 /*BitWidth=*/BW: nullptr,
10428 /*Mutable=*/false, InitStyle: ICIS_NoInit);
10429 Field->setAccess(AS_public);
10430 VaListTagDecl->addDecl(D: Field);
10431 }
10432 VaListTagDecl->completeDefinition();
10433 Context->VaListTagDecl = VaListTagDecl;
10434 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10435
10436 // } __va_list_tag;
10437 TypedefDecl *VaListTagTypedefDecl =
10438 Context->buildImplicitTypedef(T: VaListTagType, Name: "__builtin_va_list");
10439
10440 return VaListTagTypedefDecl;
10441}
10442
10443static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
10444 TargetInfo::BuiltinVaListKind Kind) {
10445 switch (Kind) {
10446 case TargetInfo::CharPtrBuiltinVaList:
10447 return CreateCharPtrBuiltinVaListDecl(Context);
10448 case TargetInfo::VoidPtrBuiltinVaList:
10449 return CreateVoidPtrBuiltinVaListDecl(Context);
10450 case TargetInfo::AArch64ABIBuiltinVaList:
10451 return CreateAArch64ABIBuiltinVaListDecl(Context);
10452 case TargetInfo::PowerABIBuiltinVaList:
10453 return CreatePowerABIBuiltinVaListDecl(Context);
10454 case TargetInfo::X86_64ABIBuiltinVaList:
10455 return CreateX86_64ABIBuiltinVaListDecl(Context);
10456 case TargetInfo::AAPCSABIBuiltinVaList:
10457 return CreateAAPCSABIBuiltinVaListDecl(Context);
10458 case TargetInfo::SystemZBuiltinVaList:
10459 return CreateSystemZBuiltinVaListDecl(Context);
10460 case TargetInfo::HexagonBuiltinVaList:
10461 return CreateHexagonBuiltinVaListDecl(Context);
10462 case TargetInfo::XtensaABIBuiltinVaList:
10463 return CreateXtensaABIBuiltinVaListDecl(Context);
10464 }
10465
10466 llvm_unreachable("Unhandled __builtin_va_list type kind");
10467}
10468
10469TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
10470 if (!BuiltinVaListDecl) {
10471 BuiltinVaListDecl = CreateVaListDecl(Context: this, Kind: Target->getBuiltinVaListKind());
10472 assert(BuiltinVaListDecl->isImplicit());
10473 }
10474
10475 return BuiltinVaListDecl;
10476}
10477
10478Decl *ASTContext::getVaListTagDecl() const {
10479 // Force the creation of VaListTagDecl by building the __builtin_va_list
10480 // declaration.
10481 if (!VaListTagDecl)
10482 (void)getBuiltinVaListDecl();
10483
10484 return VaListTagDecl;
10485}
10486
10487TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
10488 if (!BuiltinMSVaListDecl)
10489 BuiltinMSVaListDecl = CreateMSVaListDecl(Context: this);
10490
10491 return BuiltinMSVaListDecl;
10492}
10493
10494TypedefDecl *ASTContext::getBuiltinZOSVaListDecl() const {
10495 if (!BuiltinZOSVaListDecl)
10496 BuiltinZOSVaListDecl = CreateZOSVaListDecl(Context: this);
10497
10498 return BuiltinZOSVaListDecl;
10499}
10500
10501bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
10502 // Allow redecl custom type checking builtin for HLSL.
10503 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10504 BuiltinInfo.hasCustomTypechecking(ID: FD->getBuiltinID()))
10505 return true;
10506 // Allow redecl custom type checking builtin for SPIR-V.
10507 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10508 BuiltinInfo.isTSBuiltin(ID: FD->getBuiltinID()) &&
10509 BuiltinInfo.hasCustomTypechecking(ID: FD->getBuiltinID()))
10510 return true;
10511 return BuiltinInfo.canBeRedeclared(ID: FD->getBuiltinID());
10512}
10513
10514void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
10515 assert(ObjCConstantStringType.isNull() &&
10516 "'NSConstantString' type already set!");
10517
10518 ObjCConstantStringType = getObjCInterfaceType(Decl);
10519}
10520
10521/// Retrieve the template name that corresponds to a non-empty
10522/// lookup.
10523TemplateName
10524ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
10525 UnresolvedSetIterator End) const {
10526 unsigned size = End - Begin;
10527 assert(size > 1 && "set is not overloaded!");
10528
10529 void *memory = Allocate(Size: sizeof(OverloadedTemplateStorage) +
10530 size * sizeof(FunctionTemplateDecl*));
10531 auto *OT = new (memory) OverloadedTemplateStorage(size);
10532
10533 NamedDecl **Storage = OT->getStorage();
10534 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10535 NamedDecl *D = *I;
10536 assert(isa<FunctionTemplateDecl>(D) ||
10537 isa<UnresolvedUsingValueDecl>(D) ||
10538 (isa<UsingShadowDecl>(D) &&
10539 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
10540 *Storage++ = D;
10541 }
10542
10543 return TemplateName(OT);
10544}
10545
10546/// Retrieve a template name representing an unqualified-id that has been
10547/// assumed to name a template for ADL purposes.
10548TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
10549 auto *OT = new (*this) AssumedTemplateStorage(Name);
10550 return TemplateName(OT);
10551}
10552
10553/// Retrieve the template name that represents a qualified
10554/// template name such as \c std::vector.
10555TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier Qualifier,
10556 bool TemplateKeyword,
10557 TemplateName Template) const {
10558 assert(Template.getKind() == TemplateName::Template ||
10559 Template.getKind() == TemplateName::UsingTemplate);
10560
10561 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10562 assert(!Qualifier && "unexpected qualified template template parameter");
10563 assert(TemplateKeyword == false);
10564 return Template;
10565 }
10566
10567 // FIXME: Canonicalization?
10568 llvm::FoldingSetNodeID ID;
10569 QualifiedTemplateName::Profile(ID, NNS: Qualifier, TemplateKeyword, TN: Template);
10570
10571 void *InsertPos = nullptr;
10572 QualifiedTemplateName *QTN =
10573 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10574 if (!QTN) {
10575 QTN = new (*this, alignof(QualifiedTemplateName))
10576 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10577 QualifiedTemplateNames.InsertNode(N: QTN, InsertPos);
10578 }
10579
10580 return TemplateName(QTN);
10581}
10582
10583/// Retrieve the template name that represents a dependent
10584/// template name such as \c MetaFun::template operator+.
10585TemplateName
10586ASTContext::getDependentTemplateName(const DependentTemplateStorage &S) const {
10587 llvm::FoldingSetNodeID ID;
10588 S.Profile(ID);
10589
10590 void *InsertPos = nullptr;
10591 if (DependentTemplateName *QTN =
10592 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10593 return TemplateName(QTN);
10594
10595 DependentTemplateName *QTN =
10596 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10597 DependentTemplateNames.InsertNode(N: QTN, InsertPos);
10598 return TemplateName(QTN);
10599}
10600
10601TemplateName ASTContext::getSubstTemplateTemplateParm(TemplateName Replacement,
10602 Decl *AssociatedDecl,
10603 unsigned Index,
10604 UnsignedOrNone PackIndex,
10605 bool Final) const {
10606 llvm::FoldingSetNodeID ID;
10607 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10608 Index, PackIndex, Final);
10609
10610 void *insertPos = nullptr;
10611 SubstTemplateTemplateParmStorage *subst
10612 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos&: insertPos);
10613
10614 if (!subst) {
10615 subst = new (*this) SubstTemplateTemplateParmStorage(
10616 Replacement, AssociatedDecl, Index, PackIndex, Final);
10617 SubstTemplateTemplateParms.InsertNode(N: subst, InsertPos: insertPos);
10618 }
10619
10620 return TemplateName(subst);
10621}
10622
10623TemplateName
10624ASTContext::getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
10625 Decl *AssociatedDecl,
10626 unsigned Index, bool Final) const {
10627 auto &Self = const_cast<ASTContext &>(*this);
10628 llvm::FoldingSetNodeID ID;
10629 SubstTemplateTemplateParmPackStorage::Profile(ID, Context&: Self, ArgPack,
10630 AssociatedDecl, Index, Final);
10631
10632 void *InsertPos = nullptr;
10633 SubstTemplateTemplateParmPackStorage *Subst
10634 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10635
10636 if (!Subst) {
10637 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10638 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10639 SubstTemplateTemplateParmPacks.InsertNode(N: Subst, InsertPos);
10640 }
10641
10642 return TemplateName(Subst);
10643}
10644
10645/// Retrieve the template name that represents a template name
10646/// deduced from a specialization.
10647TemplateName
10648ASTContext::getDeducedTemplateName(TemplateName Underlying,
10649 DefaultArguments DefaultArgs) const {
10650 if (!DefaultArgs)
10651 return Underlying;
10652
10653 llvm::FoldingSetNodeID ID;
10654 DeducedTemplateStorage::Profile(ID, Context: *this, Underlying, DefArgs: DefaultArgs);
10655
10656 void *InsertPos = nullptr;
10657 DeducedTemplateStorage *DTS =
10658 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10659 if (!DTS) {
10660 void *Mem = Allocate(Size: sizeof(DeducedTemplateStorage) +
10661 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10662 Align: alignof(DeducedTemplateStorage));
10663 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10664 DeducedTemplates.InsertNode(N: DTS, InsertPos);
10665 }
10666 return TemplateName(DTS);
10667}
10668
10669TemplateName ASTContext::getPackIndexingTemplateName(
10670 TemplateName Pattern, Expr *IndexExpr, bool FullySubstituted,
10671 ArrayRef<TemplateName> Expansions) const {
10672 auto &Self = const_cast<ASTContext &>(*this);
10673 llvm::FoldingSetNodeID ID;
10674 PackIndexingTemplateStorage::Profile(ID, Context: Self, Pattern, IndexExpr,
10675 FullySubstituted, Expansions);
10676
10677 void *InsertPos = nullptr;
10678 PackIndexingTemplateStorage *PI =
10679 PackIndexingTemplates.FindNodeOrInsertPos(ID, InsertPos);
10680 if (!PI) {
10681 void *Mem =
10682 Allocate(Size: PackIndexingTemplateStorage::totalSizeToAlloc<TemplateName>(
10683 Counts: Expansions.size()),
10684 Align: alignof(PackIndexingTemplateStorage));
10685 PI = new (Mem) PackIndexingTemplateStorage(Pattern, IndexExpr,
10686 FullySubstituted, Expansions);
10687 PackIndexingTemplates.InsertNode(N: PI, InsertPos);
10688 }
10689 return TemplateName(PI);
10690}
10691
10692/// getFromTargetType - Given one of the integer types provided by
10693/// TargetInfo, produce the corresponding type. The unsigned @p Type
10694/// is actually a value of type @c TargetInfo::IntType.
10695CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10696 switch (Type) {
10697 case TargetInfo::NoInt: return {};
10698 case TargetInfo::SignedChar: return SignedCharTy;
10699 case TargetInfo::UnsignedChar: return UnsignedCharTy;
10700 case TargetInfo::SignedShort: return ShortTy;
10701 case TargetInfo::UnsignedShort: return UnsignedShortTy;
10702 case TargetInfo::SignedInt: return IntTy;
10703 case TargetInfo::UnsignedInt: return UnsignedIntTy;
10704 case TargetInfo::SignedLong: return LongTy;
10705 case TargetInfo::UnsignedLong: return UnsignedLongTy;
10706 case TargetInfo::SignedLongLong: return LongLongTy;
10707 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
10708 }
10709
10710 llvm_unreachable("Unhandled TargetInfo::IntType value");
10711}
10712
10713//===----------------------------------------------------------------------===//
10714// Type Predicates.
10715//===----------------------------------------------------------------------===//
10716
10717/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10718/// garbage collection attribute.
10719///
10720Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
10721 if (getLangOpts().getGC() == LangOptions::NonGC)
10722 return Qualifiers::GCNone;
10723
10724 assert(getLangOpts().ObjC);
10725 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10726
10727 // Default behaviour under objective-C's gc is for ObjC pointers
10728 // (or pointers to them) be treated as though they were declared
10729 // as __strong.
10730 if (GCAttrs == Qualifiers::GCNone) {
10731 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
10732 return Qualifiers::Strong;
10733 else if (Ty->isPointerType())
10734 return getObjCGCAttrKind(Ty: Ty->castAs<PointerType>()->getPointeeType());
10735 } else {
10736 // It's not valid to set GC attributes on anything that isn't a
10737 // pointer.
10738#ifndef NDEBUG
10739 QualType CT = Ty->getCanonicalTypeInternal();
10740 while (const auto *AT = dyn_cast<ArrayType>(CT))
10741 CT = AT->getElementType();
10742 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10743#endif
10744 }
10745 return GCAttrs;
10746}
10747
10748//===----------------------------------------------------------------------===//
10749// Type Compatibility Testing
10750//===----------------------------------------------------------------------===//
10751
10752/// areCompatVectorTypes - Return true if the two specified vector types are
10753/// compatible.
10754static bool areCompatVectorTypes(const VectorType *LHS,
10755 const VectorType *RHS) {
10756 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10757 return LHS->getElementType() == RHS->getElementType() &&
10758 LHS->getNumElements() == RHS->getNumElements();
10759}
10760
10761/// areCompatMatrixTypes - Return true if the two specified matrix types are
10762/// compatible.
10763static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
10764 const ConstantMatrixType *RHS) {
10765 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10766 return LHS->getElementType() == RHS->getElementType() &&
10767 LHS->getNumRows() == RHS->getNumRows() &&
10768 LHS->getNumColumns() == RHS->getNumColumns();
10769}
10770
10771bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
10772 QualType SecondVec) {
10773 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10774 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10775
10776 if (hasSameUnqualifiedType(T1: FirstVec, T2: SecondVec))
10777 return true;
10778
10779 // Treat Neon vector types and most AltiVec vector types as if they are the
10780 // equivalent GCC vector types.
10781 const auto *First = FirstVec->castAs<VectorType>();
10782 const auto *Second = SecondVec->castAs<VectorType>();
10783 if (First->getNumElements() == Second->getNumElements() &&
10784 hasSameType(T1: First->getElementType(), T2: Second->getElementType()) &&
10785 First->getVectorKind() != VectorKind::AltiVecPixel &&
10786 First->getVectorKind() != VectorKind::AltiVecBool &&
10787 Second->getVectorKind() != VectorKind::AltiVecPixel &&
10788 Second->getVectorKind() != VectorKind::AltiVecBool &&
10789 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10790 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10791 Second->getVectorKind() != VectorKind::SveFixedLengthData &&
10792 Second->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10793 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10794 Second->getVectorKind() != VectorKind::RVVFixedLengthData &&
10795 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10796 Second->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10797 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10798 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10799 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10800 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10801 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10802 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_4)
10803 return true;
10804
10805 // In OpenCL, treat half and _Float16 vector types as compatible.
10806 if (getLangOpts().OpenCL &&
10807 First->getNumElements() == Second->getNumElements()) {
10808 QualType FirstElt = First->getElementType();
10809 QualType SecondElt = Second->getElementType();
10810
10811 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10812 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10813 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10814 First->getVectorKind() != VectorKind::AltiVecBool &&
10815 Second->getVectorKind() != VectorKind::AltiVecPixel &&
10816 Second->getVectorKind() != VectorKind::AltiVecBool)
10817 return true;
10818 }
10819 }
10820 return false;
10821}
10822
10823bool ASTContext::areCompatibleOverflowBehaviorTypes(QualType LHS,
10824 QualType RHS) {
10825 auto Result = checkOBTAssignmentCompatibility(LHS, RHS);
10826 return Result != OBTAssignResult::IncompatibleKinds;
10827}
10828
10829ASTContext::OBTAssignResult
10830ASTContext::checkOBTAssignmentCompatibility(QualType LHS, QualType RHS) {
10831 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10832 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10833
10834 if (!LHSOBT && !RHSOBT)
10835 return OBTAssignResult::Compatible;
10836
10837 if (LHSOBT && RHSOBT) {
10838 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10839 return OBTAssignResult::IncompatibleKinds;
10840 return OBTAssignResult::Compatible;
10841 }
10842
10843 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10844 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10845
10846 if (RHSOBT && !LHSOBT) {
10847 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10848 return OBTAssignResult::Discards;
10849 }
10850
10851 return OBTAssignResult::NotApplicable;
10852}
10853
10854/// getRVVTypeSize - Return RVV vector register size.
10855static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10856 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10857 auto VScale = Context.getTargetInfo().getVScaleRange(
10858 LangOpts: Context.getLangOpts(), Mode: TargetInfo::ArmStreamingKind::NotStreaming);
10859 if (!VScale)
10860 return 0;
10861
10862 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10863
10864 uint64_t EltSize = Context.getTypeSize(T: Info.ElementType);
10865 if (Info.ElementType == Context.BoolTy)
10866 EltSize = 1;
10867
10868 uint64_t MinElts = Info.EC.getKnownMinValue();
10869 return VScale->first * MinElts * EltSize;
10870}
10871
10872bool ASTContext::areCompatibleRVVTypes(QualType FirstType,
10873 QualType SecondType) {
10874 assert(
10875 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10876 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10877 "Expected RVV builtin type and vector type!");
10878
10879 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10880 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10881 if (const auto *VT = SecondType->getAs<VectorType>()) {
10882 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10883 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10884 return FirstType->isRVVVLSBuiltinType() &&
10885 Info.ElementType == BoolTy &&
10886 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)));
10887 }
10888 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10889 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10890 return FirstType->isRVVVLSBuiltinType() &&
10891 Info.ElementType == BoolTy &&
10892 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT) * 8));
10893 }
10894 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10895 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10896 return FirstType->isRVVVLSBuiltinType() &&
10897 Info.ElementType == BoolTy &&
10898 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)) * 4);
10899 }
10900 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10901 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10902 return FirstType->isRVVVLSBuiltinType() &&
10903 Info.ElementType == BoolTy &&
10904 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)) * 2);
10905 }
10906 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10907 VT->getVectorKind() == VectorKind::Generic)
10908 return FirstType->isRVVVLSBuiltinType() &&
10909 getTypeSize(T: SecondType) == getRVVTypeSize(Context&: *this, Ty: BT) &&
10910 hasSameType(T1: VT->getElementType(),
10911 T2: getBuiltinVectorTypeInfo(Ty: BT).ElementType);
10912 }
10913 }
10914 return false;
10915 };
10916
10917 return IsValidCast(FirstType, SecondType) ||
10918 IsValidCast(SecondType, FirstType);
10919}
10920
10921bool ASTContext::areLaxCompatibleRVVTypes(QualType FirstType,
10922 QualType SecondType) {
10923 assert(
10924 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10925 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10926 "Expected RVV builtin type and vector type!");
10927
10928 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10929 const auto *BT = FirstType->getAs<BuiltinType>();
10930 if (!BT)
10931 return false;
10932
10933 if (!BT->isRVVVLSBuiltinType())
10934 return false;
10935
10936 const auto *VecTy = SecondType->getAs<VectorType>();
10937 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10938 const LangOptions::LaxVectorConversionKind LVCKind =
10939 getLangOpts().getLaxVectorConversions();
10940
10941 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10942 if (getTypeSize(T: SecondType) != getRVVTypeSize(Context&: *this, Ty: BT))
10943 return false;
10944
10945 // If -flax-vector-conversions=all is specified, the types are
10946 // certainly compatible.
10947 if (LVCKind == LangOptions::LaxVectorConversionKind::All)
10948 return true;
10949
10950 // If -flax-vector-conversions=integer is specified, the types are
10951 // compatible if the elements are integer types.
10952 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
10953 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10954 FirstType->getRVVEltType(Ctx: *this)->isIntegerType();
10955 }
10956
10957 return false;
10958 };
10959
10960 return IsLaxCompatible(FirstType, SecondType) ||
10961 IsLaxCompatible(SecondType, FirstType);
10962}
10963
10964bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
10965 while (true) {
10966 // __strong id
10967 if (const AttributedType *Attr = dyn_cast<AttributedType>(Val&: Ty)) {
10968 if (Attr->getAttrKind() == attr::ObjCOwnership)
10969 return true;
10970
10971 Ty = Attr->getModifiedType();
10972
10973 // X *__strong (...)
10974 } else if (const ParenType *Paren = dyn_cast<ParenType>(Val&: Ty)) {
10975 Ty = Paren->getInnerType();
10976
10977 // We do not want to look through typedefs, typeof(expr),
10978 // typeof(type), or any other way that the type is somehow
10979 // abstracted.
10980 } else {
10981 return false;
10982 }
10983 }
10984}
10985
10986//===----------------------------------------------------------------------===//
10987// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10988//===----------------------------------------------------------------------===//
10989
10990/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10991/// inheritance hierarchy of 'rProto'.
10992bool
10993ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
10994 ObjCProtocolDecl *rProto) const {
10995 if (declaresSameEntity(D1: lProto, D2: rProto))
10996 return true;
10997 for (auto *PI : rProto->protocols())
10998 if (ProtocolCompatibleWithProtocol(lProto, rProto: PI))
10999 return true;
11000 return false;
11001}
11002
11003/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
11004/// Class<pr1, ...>.
11005bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
11006 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
11007 for (auto *lhsProto : lhs->quals()) {
11008 bool match = false;
11009 for (auto *rhsProto : rhs->quals()) {
11010 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto)) {
11011 match = true;
11012 break;
11013 }
11014 }
11015 if (!match)
11016 return false;
11017 }
11018 return true;
11019}
11020
11021/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
11022/// ObjCQualifiedIDType.
11023bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
11024 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
11025 bool compare) {
11026 // Allow id<P..> and an 'id' in all cases.
11027 if (lhs->isObjCIdType() || rhs->isObjCIdType())
11028 return true;
11029
11030 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
11031 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
11032 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
11033 return false;
11034
11035 if (lhs->isObjCQualifiedIdType()) {
11036 if (rhs->qual_empty()) {
11037 // If the RHS is a unqualified interface pointer "NSString*",
11038 // make sure we check the class hierarchy.
11039 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11040 for (auto *I : lhs->quals()) {
11041 // when comparing an id<P> on lhs with a static type on rhs,
11042 // see if static class implements all of id's protocols, directly or
11043 // through its super class and categories.
11044 if (!rhsID->ClassImplementsProtocol(lProto: I, lookupCategory: true))
11045 return false;
11046 }
11047 }
11048 // If there are no qualifiers and no interface, we have an 'id'.
11049 return true;
11050 }
11051 // Both the right and left sides have qualifiers.
11052 for (auto *lhsProto : lhs->quals()) {
11053 bool match = false;
11054
11055 // when comparing an id<P> on lhs with a static type on rhs,
11056 // see if static class implements all of id's protocols, directly or
11057 // through its super class and categories.
11058 for (auto *rhsProto : rhs->quals()) {
11059 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11060 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11061 match = true;
11062 break;
11063 }
11064 }
11065 // If the RHS is a qualified interface pointer "NSString<P>*",
11066 // make sure we check the class hierarchy.
11067 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11068 for (auto *I : lhs->quals()) {
11069 // when comparing an id<P> on lhs with a static type on rhs,
11070 // see if static class implements all of id's protocols, directly or
11071 // through its super class and categories.
11072 if (rhsID->ClassImplementsProtocol(lProto: I, lookupCategory: true)) {
11073 match = true;
11074 break;
11075 }
11076 }
11077 }
11078 if (!match)
11079 return false;
11080 }
11081
11082 return true;
11083 }
11084
11085 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
11086
11087 if (lhs->getInterfaceType()) {
11088 // If both the right and left sides have qualifiers.
11089 for (auto *lhsProto : lhs->quals()) {
11090 bool match = false;
11091
11092 // when comparing an id<P> on rhs with a static type on lhs,
11093 // see if static class implements all of id's protocols, directly or
11094 // through its super class and categories.
11095 // First, lhs protocols in the qualifier list must be found, direct
11096 // or indirect in rhs's qualifier list or it is a mismatch.
11097 for (auto *rhsProto : rhs->quals()) {
11098 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11099 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11100 match = true;
11101 break;
11102 }
11103 }
11104 if (!match)
11105 return false;
11106 }
11107
11108 // Static class's protocols, or its super class or category protocols
11109 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
11110 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
11111 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
11112 CollectInheritedProtocols(CDecl: lhsID, Protocols&: LHSInheritedProtocols);
11113 // This is rather dubious but matches gcc's behavior. If lhs has
11114 // no type qualifier and its class has no static protocol(s)
11115 // assume that it is mismatch.
11116 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
11117 return false;
11118 for (auto *lhsProto : LHSInheritedProtocols) {
11119 bool match = false;
11120 for (auto *rhsProto : rhs->quals()) {
11121 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11122 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11123 match = true;
11124 break;
11125 }
11126 }
11127 if (!match)
11128 return false;
11129 }
11130 }
11131 return true;
11132 }
11133 return false;
11134}
11135
11136/// canAssignObjCInterfaces - Return true if the two interface types are
11137/// compatible for assignment from RHS to LHS. This handles validation of any
11138/// protocol qualifiers on the LHS or RHS.
11139bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
11140 const ObjCObjectPointerType *RHSOPT) {
11141 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11142 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11143
11144 // If either type represents the built-in 'id' type, return true.
11145 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
11146 return true;
11147
11148 // Function object that propagates a successful result or handles
11149 // __kindof types.
11150 auto finish = [&](bool succeeded) -> bool {
11151 if (succeeded)
11152 return true;
11153
11154 if (!RHS->isKindOfType())
11155 return false;
11156
11157 // Strip off __kindof and protocol qualifiers, then check whether
11158 // we can assign the other way.
11159 return canAssignObjCInterfaces(LHSOPT: RHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11160 RHSOPT: LHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this));
11161 };
11162
11163 // Casts from or to id<P> are allowed when the other side has compatible
11164 // protocols.
11165 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11166 return finish(ObjCQualifiedIdTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT, compare: false));
11167 }
11168
11169 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11170 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11171 return finish(ObjCQualifiedClassTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT));
11172 }
11173
11174 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11175 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11176 return true;
11177 }
11178
11179 // If we have 2 user-defined types, fall into that path.
11180 if (LHS->getInterface() && RHS->getInterface()) {
11181 return finish(canAssignObjCInterfaces(LHS, RHS));
11182 }
11183
11184 return false;
11185}
11186
11187/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11188/// for providing type-safety for objective-c pointers used to pass/return
11189/// arguments in block literals. When passed as arguments, passing 'A*' where
11190/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11191/// not OK. For the return type, the opposite is not OK.
11192bool ASTContext::canAssignObjCInterfacesInBlockPointer(
11193 const ObjCObjectPointerType *LHSOPT,
11194 const ObjCObjectPointerType *RHSOPT,
11195 bool BlockReturnType) {
11196
11197 // Function object that propagates a successful result or handles
11198 // __kindof types.
11199 auto finish = [&](bool succeeded) -> bool {
11200 if (succeeded)
11201 return true;
11202
11203 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11204 if (!Expected->isKindOfType())
11205 return false;
11206
11207 // Strip off __kindof and protocol qualifiers, then check whether
11208 // we can assign the other way.
11209 return canAssignObjCInterfacesInBlockPointer(
11210 LHSOPT: RHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11211 RHSOPT: LHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11212 BlockReturnType);
11213 };
11214
11215 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11216 return true;
11217
11218 if (LHSOPT->isObjCBuiltinType()) {
11219 return finish(RHSOPT->isObjCBuiltinType() ||
11220 RHSOPT->isObjCQualifiedIdType());
11221 }
11222
11223 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11224 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11225 // Use for block parameters previous type checking for compatibility.
11226 return finish(ObjCQualifiedIdTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT, compare: false) ||
11227 // Or corrected type checking as in non-compat mode.
11228 (!BlockReturnType &&
11229 ObjCQualifiedIdTypesAreCompatible(lhs: RHSOPT, rhs: LHSOPT, compare: false)));
11230 else
11231 return finish(ObjCQualifiedIdTypesAreCompatible(
11232 lhs: (BlockReturnType ? LHSOPT : RHSOPT),
11233 rhs: (BlockReturnType ? RHSOPT : LHSOPT), compare: false));
11234 }
11235
11236 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11237 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11238 if (LHS && RHS) { // We have 2 user-defined types.
11239 if (LHS != RHS) {
11240 if (LHS->getDecl()->isSuperClassOf(I: RHS->getDecl()))
11241 return finish(BlockReturnType);
11242 if (RHS->getDecl()->isSuperClassOf(I: LHS->getDecl()))
11243 return finish(!BlockReturnType);
11244 }
11245 else
11246 return true;
11247 }
11248 return false;
11249}
11250
11251/// Comparison routine for Objective-C protocols to be used with
11252/// llvm::array_pod_sort.
11253static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
11254 ObjCProtocolDecl * const *rhs) {
11255 return (*lhs)->getName().compare(RHS: (*rhs)->getName());
11256}
11257
11258/// getIntersectionOfProtocols - This routine finds the intersection of set
11259/// of protocols inherited from two distinct objective-c pointer objects with
11260/// the given common base.
11261/// It is used to build composite qualifier list of the composite type of
11262/// the conditional expression involving two objective-c pointer objects.
11263static
11264void getIntersectionOfProtocols(ASTContext &Context,
11265 const ObjCInterfaceDecl *CommonBase,
11266 const ObjCObjectPointerType *LHSOPT,
11267 const ObjCObjectPointerType *RHSOPT,
11268 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11269
11270 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11271 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11272 assert(LHS->getInterface() && "LHS must have an interface base");
11273 assert(RHS->getInterface() && "RHS must have an interface base");
11274
11275 // Add all of the protocols for the LHS.
11276 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
11277
11278 // Start with the protocol qualifiers.
11279 for (auto *proto : LHS->quals()) {
11280 Context.CollectInheritedProtocols(CDecl: proto, Protocols&: LHSProtocolSet);
11281 }
11282
11283 // Also add the protocols associated with the LHS interface.
11284 Context.CollectInheritedProtocols(CDecl: LHS->getInterface(), Protocols&: LHSProtocolSet);
11285
11286 // Add all of the protocols for the RHS.
11287 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
11288
11289 // Start with the protocol qualifiers.
11290 for (auto *proto : RHS->quals()) {
11291 Context.CollectInheritedProtocols(CDecl: proto, Protocols&: RHSProtocolSet);
11292 }
11293
11294 // Also add the protocols associated with the RHS interface.
11295 Context.CollectInheritedProtocols(CDecl: RHS->getInterface(), Protocols&: RHSProtocolSet);
11296
11297 // Compute the intersection of the collected protocol sets.
11298 for (auto *proto : LHSProtocolSet) {
11299 if (RHSProtocolSet.count(Ptr: proto))
11300 IntersectionSet.push_back(Elt: proto);
11301 }
11302
11303 // Compute the set of protocols that is implied by either the common type or
11304 // the protocols within the intersection.
11305 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
11306 Context.CollectInheritedProtocols(CDecl: CommonBase, Protocols&: ImpliedProtocols);
11307
11308 // Remove any implied protocols from the list of inherited protocols.
11309 if (!ImpliedProtocols.empty()) {
11310 llvm::erase_if(C&: IntersectionSet, P: [&](ObjCProtocolDecl *proto) -> bool {
11311 return ImpliedProtocols.contains(Ptr: proto);
11312 });
11313 }
11314
11315 // Sort the remaining protocols by name.
11316 llvm::array_pod_sort(Start: IntersectionSet.begin(), End: IntersectionSet.end(),
11317 Compare: compareObjCProtocolsByName);
11318}
11319
11320/// Determine whether the first type is a subtype of the second.
11321static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
11322 QualType rhs) {
11323 // Common case: two object pointers.
11324 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11325 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11326 if (lhsOPT && rhsOPT)
11327 return ctx.canAssignObjCInterfaces(LHSOPT: lhsOPT, RHSOPT: rhsOPT);
11328
11329 // Two block pointers.
11330 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11331 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11332 if (lhsBlock && rhsBlock)
11333 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11334
11335 // If either is an unqualified 'id' and the other is a block, it's
11336 // acceptable.
11337 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11338 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11339 return true;
11340
11341 return false;
11342}
11343
11344// Check that the given Objective-C type argument lists are equivalent.
11345static bool sameObjCTypeArgs(ASTContext &ctx,
11346 const ObjCInterfaceDecl *iface,
11347 ArrayRef<QualType> lhsArgs,
11348 ArrayRef<QualType> rhsArgs,
11349 bool stripKindOf) {
11350 if (lhsArgs.size() != rhsArgs.size())
11351 return false;
11352
11353 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11354 if (!typeParams)
11355 return false;
11356
11357 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11358 if (ctx.hasSameType(T1: lhsArgs[i], T2: rhsArgs[i]))
11359 continue;
11360
11361 switch (typeParams->begin()[i]->getVariance()) {
11362 case ObjCTypeParamVariance::Invariant:
11363 if (!stripKindOf ||
11364 !ctx.hasSameType(T1: lhsArgs[i].stripObjCKindOfType(ctx),
11365 T2: rhsArgs[i].stripObjCKindOfType(ctx))) {
11366 return false;
11367 }
11368 break;
11369
11370 case ObjCTypeParamVariance::Covariant:
11371 if (!canAssignObjCObjectTypes(ctx, lhs: lhsArgs[i], rhs: rhsArgs[i]))
11372 return false;
11373 break;
11374
11375 case ObjCTypeParamVariance::Contravariant:
11376 if (!canAssignObjCObjectTypes(ctx, lhs: rhsArgs[i], rhs: lhsArgs[i]))
11377 return false;
11378 break;
11379 }
11380 }
11381
11382 return true;
11383}
11384
11385QualType ASTContext::areCommonBaseCompatible(
11386 const ObjCObjectPointerType *Lptr,
11387 const ObjCObjectPointerType *Rptr) {
11388 const ObjCObjectType *LHS = Lptr->getObjectType();
11389 const ObjCObjectType *RHS = Rptr->getObjectType();
11390 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11391 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11392
11393 if (!LDecl || !RDecl)
11394 return {};
11395
11396 // When either LHS or RHS is a kindof type, we should return a kindof type.
11397 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11398 // kindof(A).
11399 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11400
11401 // Follow the left-hand side up the class hierarchy until we either hit a
11402 // root or find the RHS. Record the ancestors in case we don't find it.
11403 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11404 LHSAncestors;
11405 while (true) {
11406 // Record this ancestor. We'll need this if the common type isn't in the
11407 // path from the LHS to the root.
11408 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11409
11410 if (declaresSameEntity(D1: LHS->getInterface(), D2: RDecl)) {
11411 // Get the type arguments.
11412 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11413 bool anyChanges = false;
11414 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11415 // Both have type arguments, compare them.
11416 if (!sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11417 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHS->getTypeArgs(),
11418 /*stripKindOf=*/true))
11419 return {};
11420 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11421 // If only one has type arguments, the result will not have type
11422 // arguments.
11423 LHSTypeArgs = {};
11424 anyChanges = true;
11425 }
11426
11427 // Compute the intersection of protocols.
11428 SmallVector<ObjCProtocolDecl *, 8> Protocols;
11429 getIntersectionOfProtocols(Context&: *this, CommonBase: LHS->getInterface(), LHSOPT: Lptr, RHSOPT: Rptr,
11430 IntersectionSet&: Protocols);
11431 if (!Protocols.empty())
11432 anyChanges = true;
11433
11434 // If anything in the LHS will have changed, build a new result type.
11435 // If we need to return a kindof type but LHS is not a kindof type, we
11436 // build a new result type.
11437 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11438 QualType Result = getObjCInterfaceType(Decl: LHS->getInterface());
11439 Result = getObjCObjectType(baseType: Result, typeArgs: LHSTypeArgs, protocols: Protocols,
11440 isKindOf: anyKindOf || LHS->isKindOfType());
11441 return getObjCObjectPointerType(ObjectT: Result);
11442 }
11443
11444 return getObjCObjectPointerType(ObjectT: QualType(LHS, 0));
11445 }
11446
11447 // Find the superclass.
11448 QualType LHSSuperType = LHS->getSuperClassType();
11449 if (LHSSuperType.isNull())
11450 break;
11451
11452 LHS = LHSSuperType->castAs<ObjCObjectType>();
11453 }
11454
11455 // We didn't find anything by following the LHS to its root; now check
11456 // the RHS against the cached set of ancestors.
11457 while (true) {
11458 auto KnownLHS = LHSAncestors.find(Val: RHS->getInterface()->getCanonicalDecl());
11459 if (KnownLHS != LHSAncestors.end()) {
11460 LHS = KnownLHS->second;
11461
11462 // Get the type arguments.
11463 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11464 bool anyChanges = false;
11465 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11466 // Both have type arguments, compare them.
11467 if (!sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11468 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHS->getTypeArgs(),
11469 /*stripKindOf=*/true))
11470 return {};
11471 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11472 // If only one has type arguments, the result will not have type
11473 // arguments.
11474 RHSTypeArgs = {};
11475 anyChanges = true;
11476 }
11477
11478 // Compute the intersection of protocols.
11479 SmallVector<ObjCProtocolDecl *, 8> Protocols;
11480 getIntersectionOfProtocols(Context&: *this, CommonBase: RHS->getInterface(), LHSOPT: Lptr, RHSOPT: Rptr,
11481 IntersectionSet&: Protocols);
11482 if (!Protocols.empty())
11483 anyChanges = true;
11484
11485 // If we need to return a kindof type but RHS is not a kindof type, we
11486 // build a new result type.
11487 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11488 QualType Result = getObjCInterfaceType(Decl: RHS->getInterface());
11489 Result = getObjCObjectType(baseType: Result, typeArgs: RHSTypeArgs, protocols: Protocols,
11490 isKindOf: anyKindOf || RHS->isKindOfType());
11491 return getObjCObjectPointerType(ObjectT: Result);
11492 }
11493
11494 return getObjCObjectPointerType(ObjectT: QualType(RHS, 0));
11495 }
11496
11497 // Find the superclass of the RHS.
11498 QualType RHSSuperType = RHS->getSuperClassType();
11499 if (RHSSuperType.isNull())
11500 break;
11501
11502 RHS = RHSSuperType->castAs<ObjCObjectType>();
11503 }
11504
11505 return {};
11506}
11507
11508bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
11509 const ObjCObjectType *RHS) {
11510 assert(LHS->getInterface() && "LHS is not an interface type");
11511 assert(RHS->getInterface() && "RHS is not an interface type");
11512
11513 // Verify that the base decls are compatible: the RHS must be a subclass of
11514 // the LHS.
11515 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11516 bool IsSuperClass = LHSInterface->isSuperClassOf(I: RHS->getInterface());
11517 if (!IsSuperClass)
11518 return false;
11519
11520 // If the LHS has protocol qualifiers, determine whether all of them are
11521 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11522 // LHS).
11523 if (LHS->getNumProtocols() > 0) {
11524 // OK if conversion of LHS to SuperClass results in narrowing of types
11525 // ; i.e., SuperClass may implement at least one of the protocols
11526 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11527 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11528 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11529 CollectInheritedProtocols(CDecl: RHS->getInterface(), Protocols&: SuperClassInheritedProtocols);
11530 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11531 // qualifiers.
11532 for (auto *RHSPI : RHS->quals())
11533 CollectInheritedProtocols(CDecl: RHSPI, Protocols&: SuperClassInheritedProtocols);
11534 // If there is no protocols associated with RHS, it is not a match.
11535 if (SuperClassInheritedProtocols.empty())
11536 return false;
11537
11538 for (const auto *LHSProto : LHS->quals()) {
11539 bool SuperImplementsProtocol = false;
11540 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11541 if (SuperClassProto->lookupProtocolNamed(PName: LHSProto->getIdentifier())) {
11542 SuperImplementsProtocol = true;
11543 break;
11544 }
11545 if (!SuperImplementsProtocol)
11546 return false;
11547 }
11548 }
11549
11550 // If the LHS is specialized, we may need to check type arguments.
11551 if (LHS->isSpecialized()) {
11552 // Follow the superclass chain until we've matched the LHS class in the
11553 // hierarchy. This substitutes type arguments through.
11554 const ObjCObjectType *RHSSuper = RHS;
11555 while (!declaresSameEntity(D1: RHSSuper->getInterface(), D2: LHSInterface))
11556 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11557
11558 // If the RHS is specializd, compare type arguments.
11559 if (RHSSuper->isSpecialized() &&
11560 !sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11561 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHSSuper->getTypeArgs(),
11562 /*stripKindOf=*/true)) {
11563 return false;
11564 }
11565 }
11566
11567 return true;
11568}
11569
11570bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
11571 // get the "pointed to" types
11572 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11573 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11574
11575 if (!LHSOPT || !RHSOPT)
11576 return false;
11577
11578 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11579 canAssignObjCInterfaces(LHSOPT: RHSOPT, RHSOPT: LHSOPT);
11580}
11581
11582bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
11583 return canAssignObjCInterfaces(
11584 LHSOPT: getObjCObjectPointerType(ObjectT: To)->castAs<ObjCObjectPointerType>(),
11585 RHSOPT: getObjCObjectPointerType(ObjectT: From)->castAs<ObjCObjectPointerType>());
11586}
11587
11588/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11589/// both shall have the identically qualified version of a compatible type.
11590/// C99 6.2.7p1: Two types have compatible types if their types are the
11591/// same. See 6.7.[2,3,5] for additional rules.
11592bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
11593 bool CompareUnqualified) {
11594 if (getLangOpts().CPlusPlus)
11595 return hasSameType(T1: LHS, T2: RHS);
11596
11597 return !mergeTypes(LHS, RHS, OfBlockPointer: false, Unqualified: CompareUnqualified).isNull();
11598}
11599
11600bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
11601 return typesAreCompatible(LHS, RHS);
11602}
11603
11604bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
11605 return !mergeTypes(LHS, RHS, OfBlockPointer: true).isNull();
11606}
11607
11608/// mergeTransparentUnionType - if T is a transparent union type and a member
11609/// of T is compatible with SubType, return the merged type, else return
11610/// QualType()
11611QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
11612 bool OfBlockPointer,
11613 bool Unqualified) {
11614 if (const RecordType *UT = T->getAsUnionType()) {
11615 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11616 if (UD->hasAttr<TransparentUnionAttr>()) {
11617 for (const auto *I : UD->fields()) {
11618 QualType ET = I->getType().getUnqualifiedType();
11619 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11620 if (!MT.isNull())
11621 return MT;
11622 }
11623 }
11624 }
11625
11626 return {};
11627}
11628
11629/// mergeFunctionParameterTypes - merge two types which appear as function
11630/// parameter types
11631QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
11632 bool OfBlockPointer,
11633 bool Unqualified) {
11634 // GNU extension: two types are compatible if they appear as a function
11635 // argument, one of the types is a transparent union type and the other
11636 // type is compatible with a union member
11637 QualType lmerge = mergeTransparentUnionType(T: lhs, SubType: rhs, OfBlockPointer,
11638 Unqualified);
11639 if (!lmerge.isNull())
11640 return lmerge;
11641
11642 QualType rmerge = mergeTransparentUnionType(T: rhs, SubType: lhs, OfBlockPointer,
11643 Unqualified);
11644 if (!rmerge.isNull())
11645 return rmerge;
11646
11647 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11648}
11649
11650QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
11651 bool OfBlockPointer, bool Unqualified,
11652 bool AllowCXX,
11653 bool IsConditionalOperator) {
11654 const auto *lbase = lhs->castAs<FunctionType>();
11655 const auto *rbase = rhs->castAs<FunctionType>();
11656 const auto *lproto = dyn_cast<FunctionProtoType>(Val: lbase);
11657 const auto *rproto = dyn_cast<FunctionProtoType>(Val: rbase);
11658 bool allLTypes = true;
11659 bool allRTypes = true;
11660
11661 // Check return type
11662 QualType retType;
11663 if (OfBlockPointer) {
11664 QualType RHS = rbase->getReturnType();
11665 QualType LHS = lbase->getReturnType();
11666 bool UnqualifiedResult = Unqualified;
11667 if (!UnqualifiedResult)
11668 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11669 retType = mergeTypes(LHS, RHS, OfBlockPointer: true, Unqualified: UnqualifiedResult, BlockReturnType: true);
11670 }
11671 else
11672 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), OfBlockPointer: false,
11673 Unqualified);
11674 if (retType.isNull())
11675 return {};
11676
11677 if (Unqualified)
11678 retType = retType.getUnqualifiedType();
11679
11680 CanQualType LRetType = getCanonicalType(T: lbase->getReturnType());
11681 CanQualType RRetType = getCanonicalType(T: rbase->getReturnType());
11682 if (Unqualified) {
11683 LRetType = LRetType.getUnqualifiedType();
11684 RRetType = RRetType.getUnqualifiedType();
11685 }
11686
11687 if (getCanonicalType(T: retType) != LRetType)
11688 allLTypes = false;
11689 if (getCanonicalType(T: retType) != RRetType)
11690 allRTypes = false;
11691
11692 // FIXME: double check this
11693 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11694 // rbase->getRegParmAttr() != 0 &&
11695 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11696 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11697 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11698
11699 // Compatible functions must have compatible calling conventions
11700 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11701 return {};
11702
11703 // Regparm is part of the calling convention.
11704 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11705 return {};
11706 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11707 return {};
11708
11709 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11710 return {};
11711 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11712 return {};
11713 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11714 return {};
11715
11716 // When merging declarations, it's common for supplemental information like
11717 // attributes to only be present in one of the declarations, and we generally
11718 // want type merging to preserve the union of information. So a merged
11719 // function type should be noreturn if it was noreturn in *either* operand
11720 // type.
11721 //
11722 // But for the conditional operator, this is backwards. The result of the
11723 // operator could be either operand, and its type should conservatively
11724 // reflect that. So a function type in a composite type is noreturn only
11725 // if it's noreturn in *both* operand types.
11726 //
11727 // Arguably, noreturn is a kind of subtype, and the conditional operator
11728 // ought to produce the most specific common supertype of its operand types.
11729 // That would differ from this rule in contravariant positions. However,
11730 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11731 // as a practical matter, it would only affect C code that does abstraction of
11732 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11733 // say the least. So we use the simpler rule.
11734 bool NoReturn = IsConditionalOperator
11735 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11736 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11737 if (lbaseInfo.getNoReturn() != NoReturn)
11738 allLTypes = false;
11739 if (rbaseInfo.getNoReturn() != NoReturn)
11740 allRTypes = false;
11741
11742 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(noReturn: NoReturn);
11743
11744 std::optional<FunctionEffectSet> MergedFX;
11745
11746 if (lproto && rproto) { // two C99 style function prototypes
11747 assert((AllowCXX ||
11748 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11749 "C++ shouldn't be here");
11750 // Compatible functions must have the same number of parameters
11751 if (lproto->getNumParams() != rproto->getNumParams())
11752 return {};
11753
11754 // Variadic and non-variadic functions aren't compatible
11755 if (lproto->isVariadic() != rproto->isVariadic())
11756 return {};
11757
11758 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11759 return {};
11760
11761 // Function protos with different 'cfi_salt' values aren't compatible.
11762 if (lproto->getExtraAttributeInfo().CFISalt !=
11763 rproto->getExtraAttributeInfo().CFISalt)
11764 return {};
11765
11766 // Function effects are handled similarly to noreturn, see above.
11767 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11768 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11769 if (LHSFX != RHSFX) {
11770 if (IsConditionalOperator)
11771 MergedFX = FunctionEffectSet::getIntersection(LHS: LHSFX, RHS: RHSFX);
11772 else {
11773 FunctionEffectSet::Conflicts Errs;
11774 MergedFX = FunctionEffectSet::getUnion(LHS: LHSFX, RHS: RHSFX, Errs);
11775 // Here we're discarding a possible error due to conflicts in the effect
11776 // sets. But we're not in a context where we can report it. The
11777 // operation does however guarantee maintenance of invariants.
11778 }
11779 if (*MergedFX != LHSFX)
11780 allLTypes = false;
11781 if (*MergedFX != RHSFX)
11782 allRTypes = false;
11783 }
11784
11785 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
11786 bool canUseLeft, canUseRight;
11787 if (!mergeExtParameterInfo(FirstFnType: lproto, SecondFnType: rproto, CanUseFirst&: canUseLeft, CanUseSecond&: canUseRight,
11788 NewParamInfos&: newParamInfos))
11789 return {};
11790
11791 if (!canUseLeft)
11792 allLTypes = false;
11793 if (!canUseRight)
11794 allRTypes = false;
11795
11796 // Check parameter type compatibility
11797 SmallVector<QualType, 10> types;
11798 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11799 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11800 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11801 QualType paramType = mergeFunctionParameterTypes(
11802 lhs: lParamType, rhs: rParamType, OfBlockPointer, Unqualified);
11803 if (paramType.isNull())
11804 return {};
11805
11806 if (Unqualified)
11807 paramType = paramType.getUnqualifiedType();
11808
11809 types.push_back(Elt: paramType);
11810 if (Unqualified) {
11811 lParamType = lParamType.getUnqualifiedType();
11812 rParamType = rParamType.getUnqualifiedType();
11813 }
11814
11815 if (getCanonicalType(T: paramType) != getCanonicalType(T: lParamType))
11816 allLTypes = false;
11817 if (getCanonicalType(T: paramType) != getCanonicalType(T: rParamType))
11818 allRTypes = false;
11819 }
11820
11821 if (allLTypes) return lhs;
11822 if (allRTypes) return rhs;
11823
11824 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11825 EPI.ExtInfo = einfo;
11826 EPI.ExtParameterInfos =
11827 newParamInfos.empty() ? nullptr : newParamInfos.data();
11828 if (MergedFX)
11829 EPI.FunctionEffects = *MergedFX;
11830 return getFunctionType(ResultTy: retType, Args: types, EPI);
11831 }
11832
11833 if (lproto) allRTypes = false;
11834 if (rproto) allLTypes = false;
11835
11836 const FunctionProtoType *proto = lproto ? lproto : rproto;
11837 if (proto) {
11838 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11839 if (proto->isVariadic())
11840 return {};
11841 // Check that the types are compatible with the types that
11842 // would result from default argument promotions (C99 6.7.5.3p15).
11843 // The only types actually affected are promotable integer
11844 // types and floats, which would be passed as a different
11845 // type depending on whether the prototype is visible.
11846 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11847 QualType paramTy = proto->getParamType(i);
11848
11849 // Look at the converted type of enum types, since that is the type used
11850 // to pass enum values.
11851 if (const auto *ED = paramTy->getAsEnumDecl()) {
11852 paramTy = ED->getIntegerType();
11853 if (paramTy.isNull())
11854 return {};
11855 }
11856
11857 if (isPromotableIntegerType(T: paramTy) ||
11858 getCanonicalType(T: paramTy).getUnqualifiedType() == FloatTy)
11859 return {};
11860 }
11861
11862 if (allLTypes) return lhs;
11863 if (allRTypes) return rhs;
11864
11865 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
11866 EPI.ExtInfo = einfo;
11867 if (MergedFX)
11868 EPI.FunctionEffects = *MergedFX;
11869 return getFunctionType(ResultTy: retType, Args: proto->getParamTypes(), EPI);
11870 }
11871
11872 if (allLTypes) return lhs;
11873 if (allRTypes) return rhs;
11874 return getFunctionNoProtoType(ResultTy: retType, Info: einfo);
11875}
11876
11877/// Given that we have an enum type and a non-enum type, try to merge them.
11878static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11879 QualType other, bool isBlockReturnType) {
11880 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11881 // a signed integer type, or an unsigned integer type.
11882 // Compatibility is based on the underlying type, not the promotion
11883 // type.
11884 QualType underlyingType =
11885 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11886 if (underlyingType.isNull())
11887 return {};
11888 if (Context.hasSameType(T1: underlyingType, T2: other))
11889 return other;
11890
11891 // In block return types, we're more permissive and accept any
11892 // integral type of the same size.
11893 if (isBlockReturnType && other->isIntegerType() &&
11894 Context.getTypeSize(T: underlyingType) == Context.getTypeSize(T: other))
11895 return other;
11896
11897 return {};
11898}
11899
11900QualType ASTContext::mergeTagDefinitions(QualType LHS, QualType RHS) {
11901 // C17 and earlier and C++ disallow two tag definitions within the same TU
11902 // from being compatible.
11903 if (LangOpts.CPlusPlus || !LangOpts.C23)
11904 return {};
11905
11906 // Nameless tags are comparable only within outer definitions. At the top
11907 // level they are not comparable.
11908 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11909 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11910 return {};
11911
11912 // C23, on the other hand, requires the members to be "the same enough", so
11913 // we use a structural equivalence check.
11914 StructuralEquivalenceContext::NonEquivalentDeclSet NonEquivalentDecls;
11915 StructuralEquivalenceContext Ctx(
11916 getLangOpts(), *this, *this, NonEquivalentDecls,
11917 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11918 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11919 return Ctx.IsEquivalent(T1: LHS, T2: RHS) ? LHS : QualType{};
11920}
11921
11922std::optional<QualType> ASTContext::tryMergeOverflowBehaviorTypes(
11923 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11924 bool BlockReturnType, bool IsConditionalOperator) {
11925 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11926 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11927
11928 if (!LHSOBT && !RHSOBT)
11929 return std::nullopt;
11930
11931 if (LHSOBT) {
11932 if (RHSOBT) {
11933 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11934 return QualType();
11935
11936 QualType MergedUnderlying = mergeTypes(
11937 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11938 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11939
11940 if (MergedUnderlying.isNull())
11941 return QualType();
11942
11943 if (getCanonicalType(T: LHSOBT) == getCanonicalType(T: RHSOBT)) {
11944 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11945 return getCommonSugaredType(X: LHS, Y: RHS);
11946 return getOverflowBehaviorType(
11947 Kind: LHSOBT->getBehaviorKind(),
11948 Underlying: getCanonicalType(T: LHSOBT->getUnderlyingType()));
11949 }
11950
11951 // For different underlying types that successfully merge, wrap the
11952 // merged underlying type with the common overflow behavior
11953 return getOverflowBehaviorType(Kind: LHSOBT->getBehaviorKind(),
11954 Underlying: MergedUnderlying);
11955 }
11956 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11957 Unqualified, BlockReturnType, IsConditionalOperator);
11958 }
11959
11960 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11961 Unqualified, BlockReturnType, IsConditionalOperator);
11962}
11963
11964QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11965 bool Unqualified, bool BlockReturnType,
11966 bool IsConditionalOperator) {
11967 // For C++ we will not reach this code with reference types (see below),
11968 // for OpenMP variant call overloading we might.
11969 //
11970 // C++ [expr]: If an expression initially has the type "reference to T", the
11971 // type is adjusted to "T" prior to any further analysis, the expression
11972 // designates the object or function denoted by the reference, and the
11973 // expression is an lvalue unless the reference is an rvalue reference and
11974 // the expression is a function call (possibly inside parentheses).
11975 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11976 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11977 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11978 LHS->getTypeClass() == RHS->getTypeClass())
11979 return mergeTypes(LHS: LHSRefTy->getPointeeType(), RHS: RHSRefTy->getPointeeType(),
11980 OfBlockPointer, Unqualified, BlockReturnType);
11981 if (LHSRefTy || RHSRefTy)
11982 return {};
11983
11984 if (std::optional<QualType> MergedOBT =
11985 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11986 BlockReturnType, IsConditionalOperator))
11987 return *MergedOBT;
11988
11989 if (Unqualified) {
11990 LHS = LHS.getUnqualifiedType();
11991 RHS = RHS.getUnqualifiedType();
11992 }
11993
11994 QualType LHSCan = getCanonicalType(T: LHS),
11995 RHSCan = getCanonicalType(T: RHS);
11996
11997 // If two types are identical, they are compatible.
11998 if (LHSCan == RHSCan)
11999 return LHS;
12000
12001 // If the qualifiers are different, the types aren't compatible... mostly.
12002 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12003 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12004 if (LQuals != RQuals) {
12005 // If any of these qualifiers are different, we have a type
12006 // mismatch.
12007 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12008 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
12009 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
12010 !LQuals.getPointerAuth().isEquivalent(Other: RQuals.getPointerAuth()) ||
12011 LQuals.hasUnaligned() != RQuals.hasUnaligned())
12012 return {};
12013
12014 // Exactly one GC qualifier difference is allowed: __strong is
12015 // okay if the other type has no GC qualifier but is an Objective
12016 // C object pointer (i.e. implicitly strong by default). We fix
12017 // this by pretending that the unqualified type was actually
12018 // qualified __strong.
12019 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12020 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12021 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12022
12023 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12024 return {};
12025
12026 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
12027 return mergeTypes(LHS, RHS: getObjCGCQualType(T: RHS, GCAttr: Qualifiers::Strong));
12028 }
12029 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
12030 return mergeTypes(LHS: getObjCGCQualType(T: LHS, GCAttr: Qualifiers::Strong), RHS);
12031 }
12032 return {};
12033 }
12034
12035 // Okay, qualifiers are equal.
12036
12037 Type::TypeClass LHSClass = LHSCan->getTypeClass();
12038 Type::TypeClass RHSClass = RHSCan->getTypeClass();
12039
12040 // We want to consider the two function types to be the same for these
12041 // comparisons, just force one to the other.
12042 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
12043 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
12044
12045 // Same as above for arrays
12046 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
12047 LHSClass = Type::ConstantArray;
12048 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
12049 RHSClass = Type::ConstantArray;
12050
12051 // ObjCInterfaces are just specialized ObjCObjects.
12052 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
12053 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
12054
12055 // Canonicalize ExtVector -> Vector.
12056 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
12057 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
12058
12059 // If the canonical type classes don't match.
12060 if (LHSClass != RHSClass) {
12061 // Note that we only have special rules for turning block enum
12062 // returns into block int returns, not vice-versa.
12063 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
12064 return mergeEnumWithInteger(Context&: *this, ET: ETy, other: RHS, isBlockReturnType: false);
12065 }
12066 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
12067 return mergeEnumWithInteger(Context&: *this, ET: ETy, other: LHS, isBlockReturnType: BlockReturnType);
12068 }
12069 // allow block pointer type to match an 'id' type.
12070 if (OfBlockPointer && !BlockReturnType) {
12071 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
12072 return LHS;
12073 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
12074 return RHS;
12075 }
12076 // Allow __auto_type to match anything; it merges to the type with more
12077 // information.
12078 if (const auto *AT = LHS->getAs<AutoType>()) {
12079 if (!AT->isDeduced() && AT->isGNUAutoType())
12080 return RHS;
12081 }
12082 if (const auto *AT = RHS->getAs<AutoType>()) {
12083 if (!AT->isDeduced() && AT->isGNUAutoType())
12084 return LHS;
12085 }
12086 return {};
12087 }
12088
12089 // The canonical type classes match.
12090 switch (LHSClass) {
12091#define TYPE(Class, Base)
12092#define ABSTRACT_TYPE(Class, Base)
12093#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
12094#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
12095#define DEPENDENT_TYPE(Class, Base) case Type::Class:
12096#include "clang/AST/TypeNodes.inc"
12097 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
12098
12099 case Type::Auto:
12100 case Type::DeducedTemplateSpecialization:
12101 case Type::LValueReference:
12102 case Type::RValueReference:
12103 case Type::MemberPointer:
12104 llvm_unreachable("C++ should never be in mergeTypes");
12105
12106 case Type::ObjCInterface:
12107 case Type::IncompleteArray:
12108 case Type::VariableArray:
12109 case Type::FunctionProto:
12110 case Type::ExtVector:
12111 case Type::OverflowBehavior:
12112 llvm_unreachable("Types are eliminated above");
12113
12114 case Type::Pointer:
12115 {
12116 // Merge two pointer types, while trying to preserve typedef info
12117 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
12118 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
12119 if (Unqualified) {
12120 LHSPointee = LHSPointee.getUnqualifiedType();
12121 RHSPointee = RHSPointee.getUnqualifiedType();
12122 }
12123 QualType ResultType = mergeTypes(LHS: LHSPointee, RHS: RHSPointee, OfBlockPointer: false,
12124 Unqualified);
12125 if (ResultType.isNull())
12126 return {};
12127 if (getCanonicalType(T: LHSPointee) == getCanonicalType(T: ResultType))
12128 return LHS;
12129 if (getCanonicalType(T: RHSPointee) == getCanonicalType(T: ResultType))
12130 return RHS;
12131 return getPointerType(T: ResultType);
12132 }
12133 case Type::BlockPointer:
12134 {
12135 // Merge two block pointer types, while trying to preserve typedef info
12136 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
12137 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
12138 if (Unqualified) {
12139 LHSPointee = LHSPointee.getUnqualifiedType();
12140 RHSPointee = RHSPointee.getUnqualifiedType();
12141 }
12142 if (getLangOpts().OpenCL) {
12143 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
12144 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
12145 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
12146 // 6.12.5) thus the following check is asymmetric.
12147 if (!LHSPteeQual.isAddressSpaceSupersetOf(other: RHSPteeQual, Ctx: *this))
12148 return {};
12149 LHSPteeQual.removeAddressSpace();
12150 RHSPteeQual.removeAddressSpace();
12151 LHSPointee =
12152 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12153 RHSPointee =
12154 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12155 }
12156 QualType ResultType = mergeTypes(LHS: LHSPointee, RHS: RHSPointee, OfBlockPointer,
12157 Unqualified);
12158 if (ResultType.isNull())
12159 return {};
12160 if (getCanonicalType(T: LHSPointee) == getCanonicalType(T: ResultType))
12161 return LHS;
12162 if (getCanonicalType(T: RHSPointee) == getCanonicalType(T: ResultType))
12163 return RHS;
12164 return getBlockPointerType(T: ResultType);
12165 }
12166 case Type::Atomic:
12167 {
12168 // Merge two pointer types, while trying to preserve typedef info
12169 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12170 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12171 if (Unqualified) {
12172 LHSValue = LHSValue.getUnqualifiedType();
12173 RHSValue = RHSValue.getUnqualifiedType();
12174 }
12175 QualType ResultType = mergeTypes(LHS: LHSValue, RHS: RHSValue, OfBlockPointer: false,
12176 Unqualified);
12177 if (ResultType.isNull())
12178 return {};
12179 if (getCanonicalType(T: LHSValue) == getCanonicalType(T: ResultType))
12180 return LHS;
12181 if (getCanonicalType(T: RHSValue) == getCanonicalType(T: ResultType))
12182 return RHS;
12183 return getAtomicType(T: ResultType);
12184 }
12185 case Type::ConstantArray:
12186 {
12187 const ConstantArrayType* LCAT = getAsConstantArrayType(T: LHS);
12188 const ConstantArrayType* RCAT = getAsConstantArrayType(T: RHS);
12189 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12190 return {};
12191
12192 QualType LHSElem = getAsArrayType(T: LHS)->getElementType();
12193 QualType RHSElem = getAsArrayType(T: RHS)->getElementType();
12194 if (Unqualified) {
12195 LHSElem = LHSElem.getUnqualifiedType();
12196 RHSElem = RHSElem.getUnqualifiedType();
12197 }
12198
12199 QualType ResultType = mergeTypes(LHS: LHSElem, RHS: RHSElem, OfBlockPointer: false, Unqualified);
12200 if (ResultType.isNull())
12201 return {};
12202
12203 const VariableArrayType* LVAT = getAsVariableArrayType(T: LHS);
12204 const VariableArrayType* RVAT = getAsVariableArrayType(T: RHS);
12205
12206 // If either side is a variable array, and both are complete, check whether
12207 // the current dimension is definite.
12208 if (LVAT || RVAT) {
12209 auto SizeFetch = [this](const VariableArrayType* VAT,
12210 const ConstantArrayType* CAT)
12211 -> std::pair<bool,llvm::APInt> {
12212 if (VAT) {
12213 std::optional<llvm::APSInt> TheInt;
12214 Expr *E = VAT->getSizeExpr();
12215 if (E && (TheInt = E->getIntegerConstantExpr(Ctx: *this)))
12216 return std::make_pair(x: true, y&: *TheInt);
12217 return std::make_pair(x: false, y: llvm::APSInt());
12218 }
12219 if (CAT)
12220 return std::make_pair(x: true, y: CAT->getSize());
12221 return std::make_pair(x: false, y: llvm::APInt());
12222 };
12223
12224 bool HaveLSize, HaveRSize;
12225 llvm::APInt LSize, RSize;
12226 std::tie(args&: HaveLSize, args&: LSize) = SizeFetch(LVAT, LCAT);
12227 std::tie(args&: HaveRSize, args&: RSize) = SizeFetch(RVAT, RCAT);
12228 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(I1: LSize, I2: RSize))
12229 return {}; // Definite, but unequal, array dimension
12230 }
12231
12232 if (LCAT && getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType))
12233 return LHS;
12234 if (RCAT && getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType))
12235 return RHS;
12236 if (LCAT)
12237 return getConstantArrayType(EltTy: ResultType, ArySizeIn: LCAT->getSize(),
12238 SizeExpr: LCAT->getSizeExpr(), ASM: ArraySizeModifier(), IndexTypeQuals: 0);
12239 if (RCAT)
12240 return getConstantArrayType(EltTy: ResultType, ArySizeIn: RCAT->getSize(),
12241 SizeExpr: RCAT->getSizeExpr(), ASM: ArraySizeModifier(), IndexTypeQuals: 0);
12242 if (LVAT && getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType))
12243 return LHS;
12244 if (RVAT && getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType))
12245 return RHS;
12246 if (LVAT) {
12247 // FIXME: This isn't correct! But tricky to implement because
12248 // the array's size has to be the size of LHS, but the type
12249 // has to be different.
12250 return LHS;
12251 }
12252 if (RVAT) {
12253 // FIXME: This isn't correct! But tricky to implement because
12254 // the array's size has to be the size of RHS, but the type
12255 // has to be different.
12256 return RHS;
12257 }
12258 if (getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType)) return LHS;
12259 if (getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType)) return RHS;
12260 return getIncompleteArrayType(elementType: ResultType, ASM: ArraySizeModifier(), elementTypeQuals: 0);
12261 }
12262 case Type::FunctionNoProto:
12263 return mergeFunctionTypes(lhs: LHS, rhs: RHS, OfBlockPointer, Unqualified,
12264 /*AllowCXX=*/false, IsConditionalOperator);
12265 case Type::Record:
12266 case Type::Enum:
12267 return mergeTagDefinitions(LHS, RHS);
12268 case Type::Builtin:
12269 // Only exactly equal builtin types are compatible, which is tested above.
12270 return {};
12271 case Type::Complex:
12272 // Distinct complex types are incompatible.
12273 return {};
12274 case Type::Vector:
12275 // FIXME: The merged type should be an ExtVector!
12276 if (areCompatVectorTypes(LHS: LHSCan->castAs<VectorType>(),
12277 RHS: RHSCan->castAs<VectorType>()))
12278 return LHS;
12279 return {};
12280 case Type::ConstantMatrix:
12281 if (areCompatMatrixTypes(LHS: LHSCan->castAs<ConstantMatrixType>(),
12282 RHS: RHSCan->castAs<ConstantMatrixType>()))
12283 return LHS;
12284 return {};
12285 case Type::ObjCObject: {
12286 // Check if the types are assignment compatible.
12287 // FIXME: This should be type compatibility, e.g. whether
12288 // "LHS x; RHS x;" at global scope is legal.
12289 if (canAssignObjCInterfaces(LHS: LHS->castAs<ObjCObjectType>(),
12290 RHS: RHS->castAs<ObjCObjectType>()))
12291 return LHS;
12292 return {};
12293 }
12294 case Type::ObjCObjectPointer:
12295 if (OfBlockPointer) {
12296 if (canAssignObjCInterfacesInBlockPointer(
12297 LHSOPT: LHS->castAs<ObjCObjectPointerType>(),
12298 RHSOPT: RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12299 return LHS;
12300 return {};
12301 }
12302 if (canAssignObjCInterfaces(LHSOPT: LHS->castAs<ObjCObjectPointerType>(),
12303 RHSOPT: RHS->castAs<ObjCObjectPointerType>()))
12304 return LHS;
12305 return {};
12306 case Type::Pipe:
12307 assert(LHS != RHS &&
12308 "Equivalent pipe types should have already been handled!");
12309 return {};
12310 case Type::ArrayParameter:
12311 assert(LHS != RHS &&
12312 "Equivalent ArrayParameter types should have already been handled!");
12313 return {};
12314 case Type::BitInt: {
12315 // Merge two bit-precise int types, while trying to preserve typedef info.
12316 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12317 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12318 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12319 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12320
12321 // Like unsigned/int, shouldn't have a type if they don't match.
12322 if (LHSUnsigned != RHSUnsigned)
12323 return {};
12324
12325 if (LHSBits != RHSBits)
12326 return {};
12327 return LHS;
12328 }
12329 case Type::HLSLAttributedResource: {
12330 const HLSLAttributedResourceType *LHSTy =
12331 LHS->castAs<HLSLAttributedResourceType>();
12332 const HLSLAttributedResourceType *RHSTy =
12333 RHS->castAs<HLSLAttributedResourceType>();
12334 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12335 LHSTy->getWrappedType()->isHLSLResourceType() &&
12336 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12337
12338 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12339 LHSTy->getContainedType() == RHSTy->getContainedType())
12340 return LHS;
12341 return {};
12342 }
12343 case Type::HLSLInlineSpirv:
12344 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12345 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12346
12347 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12348 LHSTy->getSize() == RHSTy->getSize() &&
12349 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12350 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12351 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12352 return {};
12353
12354 return LHS;
12355 }
12356 return {};
12357 }
12358
12359 llvm_unreachable("Invalid Type::Class!");
12360}
12361
12362bool ASTContext::mergeExtParameterInfo(
12363 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12364 bool &CanUseFirst, bool &CanUseSecond,
12365 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
12366 assert(NewParamInfos.empty() && "param info list not empty");
12367 CanUseFirst = CanUseSecond = true;
12368 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12369 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12370
12371 // Fast path: if the first type doesn't have ext parameter infos,
12372 // we match if and only if the second type also doesn't have them.
12373 if (!FirstHasInfo && !SecondHasInfo)
12374 return true;
12375
12376 bool NeedParamInfo = false;
12377 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12378 : SecondFnType->getExtParameterInfos().size();
12379
12380 for (size_t I = 0; I < E; ++I) {
12381 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12382 if (FirstHasInfo)
12383 FirstParam = FirstFnType->getExtParameterInfo(I);
12384 if (SecondHasInfo)
12385 SecondParam = SecondFnType->getExtParameterInfo(I);
12386
12387 // Cannot merge unless everything except the noescape flag matches.
12388 if (FirstParam.withIsNoEscape(NoEscape: false) != SecondParam.withIsNoEscape(NoEscape: false))
12389 return false;
12390
12391 bool FirstNoEscape = FirstParam.isNoEscape();
12392 bool SecondNoEscape = SecondParam.isNoEscape();
12393 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12394 NewParamInfos.push_back(Elt: FirstParam.withIsNoEscape(NoEscape: IsNoEscape));
12395 if (NewParamInfos.back().getOpaqueValue())
12396 NeedParamInfo = true;
12397 if (FirstNoEscape != IsNoEscape)
12398 CanUseFirst = false;
12399 if (SecondNoEscape != IsNoEscape)
12400 CanUseSecond = false;
12401 }
12402
12403 if (!NeedParamInfo)
12404 NewParamInfos.clear();
12405
12406 return true;
12407}
12408
12409void ASTContext::ResetObjCLayout(const ObjCInterfaceDecl *D) {
12410 if (auto It = ObjCLayouts.find(Val: D); It != ObjCLayouts.end()) {
12411 It->second = nullptr;
12412 for (auto *SubClass : ObjCSubClasses.lookup(Val: D))
12413 ResetObjCLayout(D: SubClass);
12414 }
12415}
12416
12417/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12418/// 'RHS' attributes and returns the merged version; including for function
12419/// return types.
12420QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
12421 QualType LHSCan = getCanonicalType(T: LHS),
12422 RHSCan = getCanonicalType(T: RHS);
12423 // If two types are identical, they are compatible.
12424 if (LHSCan == RHSCan)
12425 return LHS;
12426 if (RHSCan->isFunctionType()) {
12427 if (!LHSCan->isFunctionType())
12428 return {};
12429 QualType OldReturnType =
12430 cast<FunctionType>(Val: RHSCan.getTypePtr())->getReturnType();
12431 QualType NewReturnType =
12432 cast<FunctionType>(Val: LHSCan.getTypePtr())->getReturnType();
12433 QualType ResReturnType =
12434 mergeObjCGCQualifiers(LHS: NewReturnType, RHS: OldReturnType);
12435 if (ResReturnType.isNull())
12436 return {};
12437 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12438 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12439 // In either case, use OldReturnType to build the new function type.
12440 const auto *F = LHS->castAs<FunctionType>();
12441 if (const auto *FPT = cast<FunctionProtoType>(Val: F)) {
12442 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12443 EPI.ExtInfo = getFunctionExtInfo(t: LHS);
12444 QualType ResultType =
12445 getFunctionType(ResultTy: OldReturnType, Args: FPT->getParamTypes(), EPI);
12446 return ResultType;
12447 }
12448 }
12449 return {};
12450 }
12451
12452 // If the qualifiers are different, the types can still be merged.
12453 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12454 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12455
12456 if (LQuals.withoutObjCGCAttr() != RQuals.withoutObjCGCAttr()) {
12457 // Reject immediately, if anything but the GC qualifiers is different.
12458 return {};
12459 }
12460
12461 if (LQuals != RQuals) {
12462 // Exactly one GC qualifier difference is allowed: __strong is
12463 // okay if the other type has no GC qualifier but is an Objective
12464 // C object pointer (i.e. implicitly strong by default). We fix
12465 // this by pretending that the unqualified type was actually
12466 // qualified __strong.
12467 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12468 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12469 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12470
12471 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12472 return {};
12473
12474 if (GC_L == Qualifiers::Strong)
12475 return LHS;
12476 if (GC_R == Qualifiers::Strong)
12477 return RHS;
12478 return {};
12479 }
12480
12481 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12482 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12483 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12484 QualType ResQT = mergeObjCGCQualifiers(LHS: LHSBaseQT, RHS: RHSBaseQT);
12485 if (ResQT == LHSBaseQT)
12486 return LHS;
12487 if (ResQT == RHSBaseQT)
12488 return RHS;
12489 }
12490 return {};
12491}
12492
12493//===----------------------------------------------------------------------===//
12494// Integer Predicates
12495//===----------------------------------------------------------------------===//
12496
12497unsigned ASTContext::getIntWidth(QualType T) const {
12498 if (const auto *ED = T->getAsEnumDecl())
12499 T = ED->getIntegerType();
12500 if (T->isBooleanType())
12501 return 1;
12502 if (const auto *EIT = T->getAs<BitIntType>())
12503 return EIT->getNumBits();
12504 // For builtin types, just use the standard type sizing method
12505 return (unsigned)getTypeSize(T);
12506}
12507
12508QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
12509 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12510 T->isFixedPointType()) &&
12511 "Unexpected type");
12512
12513 // Turn <4 x signed int> -> <4 x unsigned int>
12514 if (const auto *VTy = T->getAs<VectorType>())
12515 return getVectorType(vecType: getCorrespondingUnsignedType(T: VTy->getElementType()),
12516 NumElts: VTy->getNumElements(), VecKind: VTy->getVectorKind());
12517
12518 // For _BitInt, return an unsigned _BitInt with same width.
12519 if (const auto *EITy = T->getAs<BitIntType>())
12520 return getBitIntType(/*Unsigned=*/IsUnsigned: true, NumBits: EITy->getNumBits());
12521
12522 // For the overflow behavior types, construct a new unsigned variant
12523 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12524 return getOverflowBehaviorType(
12525 Kind: OBT->getBehaviorKind(),
12526 Underlying: getCorrespondingUnsignedType(T: OBT->getUnderlyingType()));
12527
12528 // For enums, get the underlying integer type of the enum, and let the general
12529 // integer type signchanging code handle it.
12530 if (const auto *ED = T->getAsEnumDecl())
12531 T = ED->getIntegerType();
12532
12533 switch (T->castAs<BuiltinType>()->getKind()) {
12534 case BuiltinType::Char_U:
12535 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12536 case BuiltinType::Char_S:
12537 case BuiltinType::SChar:
12538 case BuiltinType::Char8:
12539 return UnsignedCharTy;
12540 case BuiltinType::Short:
12541 return UnsignedShortTy;
12542 case BuiltinType::Int:
12543 return UnsignedIntTy;
12544 case BuiltinType::Long:
12545 return UnsignedLongTy;
12546 case BuiltinType::LongLong:
12547 return UnsignedLongLongTy;
12548 case BuiltinType::Int128:
12549 return UnsignedInt128Ty;
12550 // wchar_t is special. It is either signed or not, but when it's signed,
12551 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12552 // version of its underlying type instead.
12553 case BuiltinType::WChar_S:
12554 return getUnsignedWCharType();
12555
12556 case BuiltinType::ShortAccum:
12557 return UnsignedShortAccumTy;
12558 case BuiltinType::Accum:
12559 return UnsignedAccumTy;
12560 case BuiltinType::LongAccum:
12561 return UnsignedLongAccumTy;
12562 case BuiltinType::SatShortAccum:
12563 return SatUnsignedShortAccumTy;
12564 case BuiltinType::SatAccum:
12565 return SatUnsignedAccumTy;
12566 case BuiltinType::SatLongAccum:
12567 return SatUnsignedLongAccumTy;
12568 case BuiltinType::ShortFract:
12569 return UnsignedShortFractTy;
12570 case BuiltinType::Fract:
12571 return UnsignedFractTy;
12572 case BuiltinType::LongFract:
12573 return UnsignedLongFractTy;
12574 case BuiltinType::SatShortFract:
12575 return SatUnsignedShortFractTy;
12576 case BuiltinType::SatFract:
12577 return SatUnsignedFractTy;
12578 case BuiltinType::SatLongFract:
12579 return SatUnsignedLongFractTy;
12580 default:
12581 assert((T->hasUnsignedIntegerRepresentation() ||
12582 T->isUnsignedFixedPointType()) &&
12583 "Unexpected signed integer or fixed point type");
12584 return T;
12585 }
12586}
12587
12588QualType ASTContext::getCorrespondingSignedType(QualType T) const {
12589 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12590 T->isFixedPointType()) &&
12591 "Unexpected type");
12592
12593 // Turn <4 x unsigned int> -> <4 x signed int>
12594 if (const auto *VTy = T->getAs<VectorType>())
12595 return getVectorType(vecType: getCorrespondingSignedType(T: VTy->getElementType()),
12596 NumElts: VTy->getNumElements(), VecKind: VTy->getVectorKind());
12597
12598 // For _BitInt, return a signed _BitInt with same width.
12599 if (const auto *EITy = T->getAs<BitIntType>())
12600 return getBitIntType(/*Unsigned=*/IsUnsigned: false, NumBits: EITy->getNumBits());
12601
12602 // For enums, get the underlying integer type of the enum, and let the general
12603 // integer type signchanging code handle it.
12604 if (const auto *ED = T->getAsEnumDecl())
12605 T = ED->getIntegerType();
12606
12607 switch (T->castAs<BuiltinType>()->getKind()) {
12608 case BuiltinType::Char_S:
12609 // Plain `char` is mapped to `signed char` even if it's already signed
12610 case BuiltinType::Char_U:
12611 case BuiltinType::UChar:
12612 case BuiltinType::Char8:
12613 return SignedCharTy;
12614 case BuiltinType::UShort:
12615 return ShortTy;
12616 case BuiltinType::UInt:
12617 return IntTy;
12618 case BuiltinType::ULong:
12619 return LongTy;
12620 case BuiltinType::ULongLong:
12621 return LongLongTy;
12622 case BuiltinType::UInt128:
12623 return Int128Ty;
12624 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12625 // there's no matching "signed wchar_t". Therefore we return the signed
12626 // version of its underlying type instead.
12627 case BuiltinType::WChar_U:
12628 return getSignedWCharType();
12629
12630 case BuiltinType::UShortAccum:
12631 return ShortAccumTy;
12632 case BuiltinType::UAccum:
12633 return AccumTy;
12634 case BuiltinType::ULongAccum:
12635 return LongAccumTy;
12636 case BuiltinType::SatUShortAccum:
12637 return SatShortAccumTy;
12638 case BuiltinType::SatUAccum:
12639 return SatAccumTy;
12640 case BuiltinType::SatULongAccum:
12641 return SatLongAccumTy;
12642 case BuiltinType::UShortFract:
12643 return ShortFractTy;
12644 case BuiltinType::UFract:
12645 return FractTy;
12646 case BuiltinType::ULongFract:
12647 return LongFractTy;
12648 case BuiltinType::SatUShortFract:
12649 return SatShortFractTy;
12650 case BuiltinType::SatUFract:
12651 return SatFractTy;
12652 case BuiltinType::SatULongFract:
12653 return SatLongFractTy;
12654 default:
12655 assert(
12656 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12657 "Unexpected signed integer or fixed point type");
12658 return T;
12659 }
12660}
12661
12662ASTMutationListener::~ASTMutationListener() = default;
12663
12664void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
12665 QualType ReturnType) {}
12666
12667//===----------------------------------------------------------------------===//
12668// Builtin Type Computation
12669//===----------------------------------------------------------------------===//
12670
12671/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12672/// pointer over the consumed characters. This returns the resultant type. If
12673/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12674/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12675/// a vector of "i*".
12676///
12677/// RequiresICE is filled in on return to indicate whether the value is required
12678/// to be an Integer Constant Expression.
12679static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12680 ASTContext::GetBuiltinTypeError &Error,
12681 bool &RequiresICE,
12682 bool AllowTypeModifiers) {
12683 // Modifiers.
12684 int HowLong = 0;
12685 bool Signed = false, Unsigned = false;
12686 bool IsChar = false, IsShort = false;
12687 RequiresICE = false;
12688
12689 // Read the prefixed modifiers first.
12690 bool Done = false;
12691 #ifndef NDEBUG
12692 bool IsSpecial = false;
12693 #endif
12694 while (!Done) {
12695 switch (*Str++) {
12696 default: Done = true; --Str; break;
12697 case 'I':
12698 RequiresICE = true;
12699 break;
12700 case 'S':
12701 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12702 assert(!Signed && "Can't use 'S' modifier multiple times!");
12703 Signed = true;
12704 break;
12705 case 'U':
12706 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12707 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12708 Unsigned = true;
12709 break;
12710 case 'B':
12711 // This modifier represents int8 type (byte-width).
12712 assert(!IsSpecial &&
12713 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12714 assert(HowLong == 0 && "Can't use both 'L' and 'B' modifiers!");
12715#ifndef NDEBUG
12716 IsSpecial = true;
12717#endif
12718 IsChar = true;
12719 break;
12720 case 'T':
12721 // This modifier represents int16 type (short-width).
12722 assert(!IsSpecial &&
12723 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12724 assert(HowLong == 0 && "Can't use both 'L' and 'T' modifiers!");
12725#ifndef NDEBUG
12726 IsSpecial = true;
12727#endif
12728 IsShort = true;
12729 break;
12730 case 'L':
12731 assert(!IsSpecial &&
12732 "Can't use 'L' with 'W', 'N', 'Z', 'O', 'B', or 'T' modifiers");
12733 assert(HowLong <= 2 && "Can't have LLLL modifier");
12734 ++HowLong;
12735 break;
12736 case 'N':
12737 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12738 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12739 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12740 #ifndef NDEBUG
12741 IsSpecial = true;
12742 #endif
12743 if (Context.getTargetInfo().getLongWidth() == 32)
12744 ++HowLong;
12745 break;
12746 case 'W':
12747 // This modifier represents int64 type.
12748 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12749 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12750 #ifndef NDEBUG
12751 IsSpecial = true;
12752 #endif
12753 switch (Context.getTargetInfo().getInt64Type()) {
12754 default:
12755 llvm_unreachable("Unexpected integer type");
12756 case TargetInfo::SignedLong:
12757 HowLong = 1;
12758 break;
12759 case TargetInfo::SignedLongLong:
12760 HowLong = 2;
12761 break;
12762 }
12763 break;
12764 case 'Z':
12765 // This modifier represents int32 type.
12766 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12767 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12768 #ifndef NDEBUG
12769 IsSpecial = true;
12770 #endif
12771 switch (Context.getTargetInfo().getIntTypeByWidth(BitWidth: 32, IsSigned: true)) {
12772 default:
12773 llvm_unreachable("Unexpected integer type");
12774 case TargetInfo::SignedInt:
12775 HowLong = 0;
12776 break;
12777 case TargetInfo::SignedLong:
12778 HowLong = 1;
12779 break;
12780 case TargetInfo::SignedLongLong:
12781 HowLong = 2;
12782 break;
12783 }
12784 break;
12785 case 'O':
12786 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12787 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12788 #ifndef NDEBUG
12789 IsSpecial = true;
12790 #endif
12791 if (Context.getLangOpts().OpenCL)
12792 HowLong = 1;
12793 else
12794 HowLong = 2;
12795 break;
12796 }
12797 }
12798
12799 QualType Type;
12800
12801 // Read the base type.
12802 switch (*Str++) {
12803 default:
12804 llvm_unreachable("Unknown builtin type letter!");
12805 case 'x':
12806 assert(HowLong == 0 && !Signed && !Unsigned &&
12807 "Bad modifiers used with 'x'!");
12808 Type = Context.Float16Ty;
12809 break;
12810 case 'y':
12811 assert(HowLong == 0 && !Signed && !Unsigned &&
12812 "Bad modifiers used with 'y'!");
12813 Type = Context.BFloat16Ty;
12814 break;
12815 case 'v':
12816 assert(HowLong == 0 && !Signed && !Unsigned &&
12817 "Bad modifiers used with 'v'!");
12818 Type = Context.VoidTy;
12819 break;
12820 case 'h':
12821 assert(HowLong == 0 && !Signed && !Unsigned &&
12822 "Bad modifiers used with 'h'!");
12823 Type = Context.HalfTy;
12824 break;
12825 case 'f':
12826 assert(HowLong == 0 && !Signed && !Unsigned &&
12827 "Bad modifiers used with 'f'!");
12828 Type = Context.FloatTy;
12829 break;
12830 case 'd':
12831 assert(HowLong < 3 && !Signed && !Unsigned &&
12832 "Bad modifiers used with 'd'!");
12833 if (HowLong == 1)
12834 Type = Context.LongDoubleTy;
12835 else if (HowLong == 2)
12836 Type = Context.Float128Ty;
12837 else
12838 Type = Context.DoubleTy;
12839 break;
12840 case 's':
12841 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12842 if (Unsigned)
12843 Type = Context.UnsignedShortTy;
12844 else
12845 Type = Context.ShortTy;
12846 break;
12847 case 'i':
12848 if (IsChar)
12849 Type = Unsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
12850 else if (IsShort)
12851 Type = Unsigned ? Context.UnsignedShortTy : Context.ShortTy;
12852 else if (HowLong == 3)
12853 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12854 else if (HowLong == 2)
12855 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12856 else if (HowLong == 1)
12857 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12858 else
12859 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12860 break;
12861 case 'c':
12862 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12863 if (Signed)
12864 Type = Context.SignedCharTy;
12865 else if (Unsigned)
12866 Type = Context.UnsignedCharTy;
12867 else
12868 Type = Context.CharTy;
12869 break;
12870 case 'b': // boolean
12871 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12872 Type = Context.BoolTy;
12873 break;
12874 case 'z': // size_t.
12875 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12876 Type = Context.getSizeType();
12877 break;
12878 case 'w': // wchar_t.
12879 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12880 Type = Context.getWideCharType();
12881 break;
12882 case 'F':
12883 Type = Context.getCFConstantStringType();
12884 break;
12885 case 'G':
12886 Type = Context.getObjCIdType();
12887 break;
12888 case 'H':
12889 Type = Context.getObjCSelType();
12890 break;
12891 case 'M':
12892 Type = Context.getObjCSuperType();
12893 break;
12894 case 'a':
12895 Type = Context.getBuiltinVaListType();
12896 assert(!Type.isNull() && "builtin va list type not initialized!");
12897 break;
12898 case 'A':
12899 // This is a "reference" to a va_list; however, what exactly
12900 // this means depends on how va_list is defined. There are two
12901 // different kinds of va_list: ones passed by value, and ones
12902 // passed by reference. An example of a by-value va_list is
12903 // x86, where va_list is a char*. An example of by-ref va_list
12904 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12905 // we want this argument to be a char*&; for x86-64, we want
12906 // it to be a __va_list_tag*.
12907 Type = Context.getBuiltinVaListType();
12908 assert(!Type.isNull() && "builtin va list type not initialized!");
12909 if (Type->isArrayType())
12910 Type = Context.getArrayDecayedType(Ty: Type);
12911 else
12912 Type = Context.getLValueReferenceType(T: Type);
12913 break;
12914 case 'q': {
12915 char *End;
12916 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12917 assert(End != Str && "Missing vector size");
12918 Str = End;
12919
12920 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12921 RequiresICE, AllowTypeModifiers: false);
12922 assert(!RequiresICE && "Can't require vector ICE");
12923
12924 Type = Context.getScalableVectorType(EltTy: ElementType, NumElts: NumElements);
12925 break;
12926 }
12927 case 'Q': {
12928 switch (*Str++) {
12929 case 'a': {
12930 Type = Context.SveCountTy;
12931 break;
12932 }
12933 case 'b': {
12934 Type = Context.AMDGPUBufferRsrcTy;
12935 break;
12936 }
12937 case 'c': {
12938 Type = Context.AMDGPUFeaturePredicateTy;
12939 break;
12940 }
12941 case 't': {
12942 Type = Context.AMDGPUTextureTy;
12943 break;
12944 }
12945 case 'r': {
12946 Type = Context.HLSLResourceTy;
12947 break;
12948 }
12949 default:
12950 llvm_unreachable("Unexpected target builtin type");
12951 }
12952 break;
12953 }
12954 case 'V': {
12955 char *End;
12956 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12957 assert(End != Str && "Missing vector size");
12958 Str = End;
12959
12960 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12961 RequiresICE, AllowTypeModifiers: false);
12962 assert(!RequiresICE && "Can't require vector ICE");
12963
12964 // TODO: No way to make AltiVec vectors in builtins yet.
12965 Type = Context.getVectorType(vecType: ElementType, NumElts: NumElements, VecKind: VectorKind::Generic);
12966 break;
12967 }
12968 case 'E': {
12969 char *End;
12970
12971 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12972 assert(End != Str && "Missing vector size");
12973
12974 Str = End;
12975
12976 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12977 AllowTypeModifiers: false);
12978 Type = Context.getExtVectorType(vecType: ElementType, NumElts: NumElements);
12979 break;
12980 }
12981 case 'X': {
12982 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12983 AllowTypeModifiers: false);
12984 assert(!RequiresICE && "Can't require complex ICE");
12985 Type = Context.getComplexType(T: ElementType);
12986 break;
12987 }
12988 case 'Y':
12989 Type = Context.getPointerDiffType();
12990 break;
12991 case 'P':
12992 Type = Context.getFILEType();
12993 if (Type.isNull()) {
12994 Error = ASTContext::GE_Missing_stdio;
12995 return {};
12996 }
12997 break;
12998 case 'J':
12999 if (Signed)
13000 Type = Context.getsigjmp_bufType();
13001 else
13002 Type = Context.getjmp_bufType();
13003
13004 if (Type.isNull()) {
13005 Error = ASTContext::GE_Missing_setjmp;
13006 return {};
13007 }
13008 break;
13009 case 'K':
13010 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
13011 Type = Context.getucontext_tType();
13012
13013 if (Type.isNull()) {
13014 Error = ASTContext::GE_Missing_ucontext;
13015 return {};
13016 }
13017 break;
13018 case 'p':
13019 Type = Context.getProcessIDType();
13020 break;
13021 case 'm':
13022 Type = Context.MFloat8Ty;
13023 break;
13024 }
13025
13026 // If there are modifiers and if we're allowed to parse them, go for it.
13027 Done = !AllowTypeModifiers;
13028 while (!Done) {
13029 switch (char c = *Str++) {
13030 default: Done = true; --Str; break;
13031 case '*':
13032 case '&': {
13033 // Both pointers and references can have their pointee types
13034 // qualified with an address space.
13035 char *End;
13036 unsigned AddrSpace = strtoul(nptr: Str, endptr: &End, base: 10);
13037 if (End != Str) {
13038 // Note AddrSpace == 0 is not the same as an unspecified address space.
13039 Type = Context.getAddrSpaceQualType(
13040 T: Type,
13041 AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: AddrSpace));
13042 Str = End;
13043 }
13044 if (c == '*')
13045 Type = Context.getPointerType(T: Type);
13046 else
13047 Type = Context.getLValueReferenceType(T: Type);
13048 break;
13049 }
13050 // FIXME: There's no way to have a built-in with an rvalue ref arg.
13051 case 'C':
13052 Type = Type.withConst();
13053 break;
13054 case 'D':
13055 Type = Context.getVolatileType(T: Type);
13056 break;
13057 case 'R':
13058 Type = Type.withRestrict();
13059 break;
13060 }
13061 }
13062
13063 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
13064 "Integer constant 'I' type must be an integer");
13065
13066 return Type;
13067}
13068
13069// On some targets such as PowerPC, some of the builtins are defined with custom
13070// type descriptors for target-dependent types. These descriptors are decoded in
13071// other functions, but it may be useful to be able to fall back to default
13072// descriptor decoding to define builtins mixing target-dependent and target-
13073// independent types. This function allows decoding one type descriptor with
13074// default decoding.
13075QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
13076 GetBuiltinTypeError &Error, bool &RequireICE,
13077 bool AllowTypeModifiers) const {
13078 return DecodeTypeFromStr(Str, Context, Error, RequiresICE&: RequireICE, AllowTypeModifiers);
13079}
13080
13081/// GetBuiltinType - Return the type for the specified builtin.
13082QualType ASTContext::GetBuiltinType(unsigned Id,
13083 GetBuiltinTypeError &Error,
13084 unsigned *IntegerConstantArgs) const {
13085 const char *TypeStr = BuiltinInfo.getTypeString(ID: Id);
13086 if (TypeStr[0] == '\0') {
13087 Error = GE_Missing_type;
13088 return {};
13089 }
13090
13091 SmallVector<QualType, 8> ArgTypes;
13092
13093 bool RequiresICE = false;
13094 Error = GE_None;
13095 QualType ResType = DecodeTypeFromStr(Str&: TypeStr, Context: *this, Error,
13096 RequiresICE, AllowTypeModifiers: true);
13097 if (Error != GE_None)
13098 return {};
13099
13100 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
13101
13102 while (TypeStr[0] && TypeStr[0] != '.') {
13103 QualType Ty = DecodeTypeFromStr(Str&: TypeStr, Context: *this, Error, RequiresICE, AllowTypeModifiers: true);
13104 if (Error != GE_None)
13105 return {};
13106
13107 // If this argument is required to be an IntegerConstantExpression and the
13108 // caller cares, fill in the bitmask we return.
13109 if (RequiresICE && IntegerConstantArgs)
13110 *IntegerConstantArgs |= 1 << ArgTypes.size();
13111
13112 // Do array -> pointer decay. The builtin should use the decayed type.
13113 if (Ty->isArrayType())
13114 Ty = getArrayDecayedType(Ty);
13115
13116 ArgTypes.push_back(Elt: Ty);
13117 }
13118
13119 if (Id == Builtin::BI__GetExceptionInfo)
13120 return {};
13121
13122 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
13123 "'.' should only occur at end of builtin type list!");
13124
13125 bool Variadic = (TypeStr[0] == '.');
13126
13127 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
13128 if (BuiltinInfo.isNoReturn(ID: Id))
13129 EI = EI.withNoReturn(noReturn: true);
13130
13131 // We really shouldn't be making a no-proto type here.
13132 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
13133 return getFunctionNoProtoType(ResultTy: ResType, Info: EI);
13134
13135 FunctionProtoType::ExtProtoInfo EPI;
13136 EPI.ExtInfo = EI;
13137 EPI.Variadic = Variadic;
13138 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(ID: Id))
13139 EPI.ExceptionSpec.Type =
13140 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
13141
13142 return getFunctionType(ResultTy: ResType, Args: ArgTypes, EPI);
13143}
13144
13145static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
13146 const FunctionDecl *FD) {
13147 if (!FD->isExternallyVisible())
13148 return GVA_Internal;
13149
13150 // Non-user-provided functions get emitted as weak definitions with every
13151 // use, no matter whether they've been explicitly instantiated etc.
13152 if (!FD->isUserProvided())
13153 return GVA_DiscardableODR;
13154
13155 GVALinkage External;
13156 switch (FD->getTemplateSpecializationKind()) {
13157 case TSK_Undeclared:
13158 case TSK_ExplicitSpecialization:
13159 External = GVA_StrongExternal;
13160 break;
13161
13162 case TSK_ExplicitInstantiationDefinition:
13163 return GVA_StrongODR;
13164
13165 // C++11 [temp.explicit]p10:
13166 // [ Note: The intent is that an inline function that is the subject of
13167 // an explicit instantiation declaration will still be implicitly
13168 // instantiated when used so that the body can be considered for
13169 // inlining, but that no out-of-line copy of the inline function would be
13170 // generated in the translation unit. -- end note ]
13171 case TSK_ExplicitInstantiationDeclaration:
13172 return GVA_AvailableExternally;
13173
13174 case TSK_ImplicitInstantiation:
13175 External = GVA_DiscardableODR;
13176 break;
13177 }
13178
13179 if (!FD->isInlined())
13180 return External;
13181
13182 if ((!Context.getLangOpts().CPlusPlus &&
13183 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13184 !FD->hasAttr<DLLExportAttr>()) ||
13185 FD->hasAttr<GNUInlineAttr>()) {
13186 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13187
13188 // GNU or C99 inline semantics. Determine whether this symbol should be
13189 // externally visible.
13190 if (auto *Def = FD->getDefinition();
13191 Def && Def->isInlineDefinitionExternallyVisible())
13192 return External;
13193
13194 // C99 inline semantics, where the symbol is not externally visible.
13195 return GVA_AvailableExternally;
13196 }
13197
13198 // Functions specified with extern and inline in -fms-compatibility mode
13199 // forcibly get emitted. While the body of the function cannot be later
13200 // replaced, the function definition cannot be discarded.
13201 if (FD->isMSExternInline())
13202 return GVA_StrongODR;
13203
13204 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13205 isa<CXXConstructorDecl>(Val: FD) &&
13206 cast<CXXConstructorDecl>(Val: FD)->isInheritingConstructor() &&
13207 !FD->hasAttr<DLLExportAttr>()) {
13208 // Both Clang and MSVC implement inherited constructors as forwarding
13209 // thunks that delegate to the base constructor. Keep non-dllexport
13210 // inheriting constructor thunks internal since they are not needed
13211 // outside the translation unit.
13212 //
13213 // dllexport inherited constructors are exempted so they are externally
13214 // visible, matching MSVC's export behavior. Inherited constructors
13215 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13216 // cleanup types) are excluded from export in Sema to avoid silent
13217 // runtime mismatches.
13218 return GVA_Internal;
13219 }
13220
13221 return GVA_DiscardableODR;
13222}
13223
13224static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
13225 const Decl *D, GVALinkage L) {
13226 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13227 // dllexport/dllimport on inline functions.
13228 if (D->hasAttr<DLLImportAttr>()) {
13229 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13230 return GVA_AvailableExternally;
13231 } else if (D->hasAttr<DLLExportAttr>()) {
13232 if (L == GVA_DiscardableODR)
13233 return GVA_StrongODR;
13234 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13235 // Device-side functions with __global__ attribute must always be
13236 // visible externally so they can be launched from host.
13237 if (D->hasAttr<CUDAGlobalAttr>() &&
13238 (L == GVA_DiscardableODR || L == GVA_Internal))
13239 return GVA_StrongODR;
13240 // Single source offloading languages like CUDA/HIP need to be able to
13241 // access static device variables from host code of the same compilation
13242 // unit. This is done by externalizing the static variable with a shared
13243 // name between the host and device compilation which is the same for the
13244 // same compilation unit whereas different among different compilation
13245 // units.
13246 if (Context.shouldExternalize(D))
13247 return GVA_StrongExternal;
13248 }
13249 return L;
13250}
13251
13252/// Adjust the GVALinkage for a declaration based on what an external AST source
13253/// knows about whether there can be other definitions of this declaration.
13254static GVALinkage
13255adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
13256 GVALinkage L) {
13257 ExternalASTSource *Source = Ctx.getExternalSource();
13258 if (!Source)
13259 return L;
13260
13261 switch (Source->hasExternalDefinitions(D)) {
13262 case ExternalASTSource::EK_Never:
13263 // Other translation units rely on us to provide the definition.
13264 if (L == GVA_DiscardableODR)
13265 return GVA_StrongODR;
13266 break;
13267
13268 case ExternalASTSource::EK_Always:
13269 return GVA_AvailableExternally;
13270
13271 case ExternalASTSource::EK_ReplyHazy:
13272 break;
13273 }
13274 return L;
13275}
13276
13277GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
13278 return adjustGVALinkageForExternalDefinitionKind(Ctx: *this, D: FD,
13279 L: adjustGVALinkageForAttributes(Context: *this, D: FD,
13280 L: basicGVALinkageForFunction(Context: *this, FD)));
13281}
13282
13283static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
13284 const VarDecl *VD) {
13285 // As an extension for interactive REPLs, make sure constant variables are
13286 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13287 // marking them as internal.
13288 if (Context.getLangOpts().CPlusPlus &&
13289 Context.getLangOpts().IncrementalExtensions &&
13290 VD->getType().isConstQualified() &&
13291 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13292 !isa<VarTemplateSpecializationDecl>(Val: VD) && !VD->getDescribedVarTemplate())
13293 return GVA_DiscardableODR;
13294
13295 if (!VD->isExternallyVisible())
13296 return GVA_Internal;
13297
13298 if (VD->isStaticLocal()) {
13299 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13300 while (LexicalContext && !isa<FunctionDecl>(Val: LexicalContext))
13301 LexicalContext = LexicalContext->getLexicalParent();
13302
13303 // ObjC Blocks can create local variables that don't have a FunctionDecl
13304 // LexicalContext.
13305 if (!LexicalContext)
13306 return GVA_DiscardableODR;
13307
13308 // Otherwise, let the static local variable inherit its linkage from the
13309 // nearest enclosing function.
13310 auto StaticLocalLinkage =
13311 Context.GetGVALinkageForFunction(FD: cast<FunctionDecl>(Val: LexicalContext));
13312
13313 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13314 // be emitted in any object with references to the symbol for the object it
13315 // contains, whether inline or out-of-line."
13316 // Similar behavior is observed with MSVC. An alternative ABI could use
13317 // StrongODR/AvailableExternally to match the function, but none are
13318 // known/supported currently.
13319 if (StaticLocalLinkage == GVA_StrongODR ||
13320 StaticLocalLinkage == GVA_AvailableExternally)
13321 return GVA_DiscardableODR;
13322 return StaticLocalLinkage;
13323 }
13324
13325 // MSVC treats in-class initialized static data members as definitions.
13326 // By giving them non-strong linkage, out-of-line definitions won't
13327 // cause link errors.
13328 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13329 return GVA_DiscardableODR;
13330
13331 // Most non-template variables have strong linkage; inline variables are
13332 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13333 GVALinkage StrongLinkage;
13334 switch (Context.getInlineVariableDefinitionKind(VD)) {
13335 case ASTContext::InlineVariableDefinitionKind::None:
13336 StrongLinkage = GVA_StrongExternal;
13337 break;
13338 case ASTContext::InlineVariableDefinitionKind::Weak:
13339 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
13340 StrongLinkage = GVA_DiscardableODR;
13341 break;
13342 case ASTContext::InlineVariableDefinitionKind::Strong:
13343 StrongLinkage = GVA_StrongODR;
13344 break;
13345 }
13346
13347 switch (VD->getTemplateSpecializationKind()) {
13348 case TSK_Undeclared:
13349 return StrongLinkage;
13350
13351 case TSK_ExplicitSpecialization:
13352 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13353 VD->isStaticDataMember()
13354 ? GVA_StrongODR
13355 : StrongLinkage;
13356
13357 case TSK_ExplicitInstantiationDefinition:
13358 return GVA_StrongODR;
13359
13360 case TSK_ExplicitInstantiationDeclaration:
13361 return GVA_AvailableExternally;
13362
13363 case TSK_ImplicitInstantiation:
13364 return GVA_DiscardableODR;
13365 }
13366
13367 llvm_unreachable("Invalid Linkage!");
13368}
13369
13370GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) const {
13371 return adjustGVALinkageForExternalDefinitionKind(Ctx: *this, D: VD,
13372 L: adjustGVALinkageForAttributes(Context: *this, D: VD,
13373 L: basicGVALinkageForVariable(Context: *this, VD)));
13374}
13375
13376bool ASTContext::DeclMustBeEmitted(const Decl *D) {
13377 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
13378 if (!VD->isFileVarDecl())
13379 return false;
13380 // Global named register variables (GNU extension) are never emitted.
13381 if (VD->getStorageClass() == SC_Register)
13382 return false;
13383 if (VD->getDescribedVarTemplate() ||
13384 isa<VarTemplatePartialSpecializationDecl>(Val: VD))
13385 return false;
13386 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
13387 // We never need to emit an uninstantiated function template.
13388 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13389 return false;
13390 } else if (isa<PragmaCommentDecl>(Val: D))
13391 return true;
13392 else if (isa<PragmaDetectMismatchDecl>(Val: D))
13393 return true;
13394 else if (isa<OMPRequiresDecl>(Val: D))
13395 return true;
13396 else if (isa<OMPThreadPrivateDecl>(Val: D))
13397 return !D->getDeclContext()->isDependentContext();
13398 else if (isa<OMPAllocateDecl>(Val: D))
13399 return !D->getDeclContext()->isDependentContext();
13400 else if (isa<OMPDeclareReductionDecl>(Val: D) || isa<OMPDeclareMapperDecl>(Val: D))
13401 return !D->getDeclContext()->isDependentContext();
13402 else if (isa<ImportDecl>(Val: D))
13403 return true;
13404 else
13405 return false;
13406
13407 // If this is a member of a class template, we do not need to emit it.
13408 if (D->getDeclContext()->isDependentContext())
13409 return false;
13410
13411 // Weak references don't produce any output by themselves.
13412 if (D->hasAttr<WeakRefAttr>())
13413 return false;
13414
13415 // SYCL device compilation requires that functions defined with the
13416 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13417 // other entities are emitted only if they are used by a function
13418 // defined with one of those attributes.
13419 if (LangOpts.SYCLIsDevice)
13420 return isa<FunctionDecl>(Val: D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13421 D->hasAttr<SYCLExternalAttr>());
13422
13423 // Aliases and used decls are required.
13424 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13425 return true;
13426
13427 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
13428 // Forward declarations aren't required.
13429 if (!FD->doesThisDeclarationHaveABody())
13430 return FD->doesDeclarationForceExternallyVisibleDefinition();
13431
13432 // Constructors and destructors are required.
13433 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13434 return true;
13435
13436 // The key function for a class is required. This rule only comes
13437 // into play when inline functions can be key functions, though.
13438 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13439 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
13440 const CXXRecordDecl *RD = MD->getParent();
13441 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13442 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13443 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13444 return true;
13445 }
13446 }
13447 }
13448
13449 GVALinkage Linkage = GetGVALinkageForFunction(FD);
13450
13451 // static, static inline, always_inline, and extern inline functions can
13452 // always be deferred. Normal inline functions can be deferred in C99/C++.
13453 // Implicit template instantiations can also be deferred in C++.
13454 return !isDiscardableGVALinkage(L: Linkage);
13455 }
13456
13457 const auto *VD = cast<VarDecl>(Val: D);
13458 assert(VD->isFileVarDecl() && "Expected file scoped var");
13459
13460 // If the decl is marked as `declare target to`, it should be emitted for the
13461 // host and for the device.
13462 if (LangOpts.OpenMP &&
13463 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13464 return true;
13465
13466 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13467 !isMSStaticDataMemberInlineDefinition(VD))
13468 return false;
13469
13470 if (VD->shouldEmitInExternalSource())
13471 return false;
13472
13473 // Variables that can be needed in other TUs are required.
13474 auto Linkage = GetGVALinkageForVariable(VD);
13475 if (!isDiscardableGVALinkage(L: Linkage))
13476 return true;
13477
13478 // We never need to emit a variable that is available in another TU.
13479 if (Linkage == GVA_AvailableExternally)
13480 return false;
13481
13482 // Variables that have destruction with side-effects are required.
13483 if (VD->needsDestruction(Ctx: *this))
13484 return true;
13485
13486 // Variables that have initialization with side-effects are required.
13487 if (VD->hasInitWithSideEffects())
13488 return true;
13489
13490 // Likewise, variables with tuple-like bindings are required if their
13491 // bindings have side-effects.
13492 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: VD)) {
13493 for (const auto *BD : DD->flat_bindings())
13494 if (const auto *BindingVD = BD->getHoldingVar())
13495 if (DeclMustBeEmitted(D: BindingVD))
13496 return true;
13497 }
13498
13499 return false;
13500}
13501
13502void ASTContext::forEachMultiversionedFunctionVersion(
13503 const FunctionDecl *FD,
13504 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13505 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13506 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13507 FD = FD->getMostRecentDecl();
13508 // FIXME: The order of traversal here matters and depends on the order of
13509 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13510 // shouldn't rely on that.
13511 for (auto *CurDecl :
13512 FD->getDeclContext()->getRedeclContext()->lookup(Name: FD->getDeclName())) {
13513 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13514 if (CurFD && hasSameType(T1: CurFD->getType(), T2: FD->getType()) &&
13515 SeenDecls.insert(V: CurFD).second) {
13516 Pred(CurFD);
13517 }
13518 }
13519}
13520
13521CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
13522 bool IsCXXMethod) const {
13523 // Pass through to the C++ ABI object
13524 if (IsCXXMethod)
13525 return ABI->getDefaultMethodCallConv(isVariadic: IsVariadic);
13526
13527 switch (LangOpts.getDefaultCallingConv()) {
13528 case LangOptions::DCC_None:
13529 break;
13530 case LangOptions::DCC_CDecl:
13531 return CC_C;
13532 case LangOptions::DCC_FastCall:
13533 if (getTargetInfo().hasFeature(Feature: "sse2") && !IsVariadic)
13534 return CC_X86FastCall;
13535 break;
13536 case LangOptions::DCC_StdCall:
13537 if (!IsVariadic)
13538 return CC_X86StdCall;
13539 break;
13540 case LangOptions::DCC_VectorCall:
13541 // __vectorcall cannot be applied to variadic functions.
13542 if (!IsVariadic)
13543 return CC_X86VectorCall;
13544 break;
13545 case LangOptions::DCC_RegCall:
13546 // __regcall cannot be applied to variadic functions.
13547 if (!IsVariadic)
13548 return CC_X86RegCall;
13549 break;
13550 case LangOptions::DCC_RtdCall:
13551 if (!IsVariadic)
13552 return CC_M68kRTD;
13553 break;
13554 }
13555 return Target->getDefaultCallingConv();
13556}
13557
13558bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
13559 // Pass through to the C++ ABI object
13560 return ABI->isNearlyEmpty(RD);
13561}
13562
13563VTableContextBase *ASTContext::getVTableContext() {
13564 if (!VTContext) {
13565 auto ABI = Target->getCXXABI();
13566 if (ABI.isMicrosoft())
13567 VTContext.reset(p: new MicrosoftVTableContext(*this));
13568 else {
13569 VTContext.reset(p: new ItaniumVTableContext(*this));
13570 }
13571 }
13572 return VTContext.get();
13573}
13574
13575MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
13576 if (!T)
13577 T = Target;
13578 switch (T->getCXXABI().getKind()) {
13579 case TargetCXXABI::AppleARM64:
13580 case TargetCXXABI::Fuchsia:
13581 case TargetCXXABI::GenericAArch64:
13582 case TargetCXXABI::GenericItanium:
13583 case TargetCXXABI::GenericARM:
13584 case TargetCXXABI::GenericMIPS:
13585 case TargetCXXABI::iOS:
13586 case TargetCXXABI::WebAssembly:
13587 case TargetCXXABI::WatchOS:
13588 case TargetCXXABI::XL:
13589 return ItaniumMangleContext::create(Context&: *this, Diags&: getDiagnostics());
13590 case TargetCXXABI::Microsoft:
13591 return MicrosoftMangleContext::create(Context&: *this, Diags&: getDiagnostics());
13592 }
13593 llvm_unreachable("Unsupported ABI");
13594}
13595
13596MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) {
13597 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13598 "Device mangle context does not support Microsoft mangling.");
13599 switch (T.getCXXABI().getKind()) {
13600 case TargetCXXABI::AppleARM64:
13601 case TargetCXXABI::Fuchsia:
13602 case TargetCXXABI::GenericAArch64:
13603 case TargetCXXABI::GenericItanium:
13604 case TargetCXXABI::GenericARM:
13605 case TargetCXXABI::GenericMIPS:
13606 case TargetCXXABI::iOS:
13607 case TargetCXXABI::WebAssembly:
13608 case TargetCXXABI::WatchOS:
13609 case TargetCXXABI::XL:
13610 return ItaniumMangleContext::create(
13611 Context&: *this, Diags&: getDiagnostics(),
13612 Discriminator: [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13613 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
13614 return RD->getDeviceLambdaManglingNumber();
13615 return std::nullopt;
13616 },
13617 /*IsAux=*/true);
13618 case TargetCXXABI::Microsoft:
13619 return MicrosoftMangleContext::create(Context&: *this, Diags&: getDiagnostics(),
13620 /*IsAux=*/true);
13621 }
13622 llvm_unreachable("Unsupported ABI");
13623}
13624
13625MangleContext *ASTContext::cudaNVInitDeviceMC() {
13626 // If the host and device have different C++ ABIs, mark it as the device
13627 // mangle context so that the mangling needs to retrieve the additional
13628 // device lambda mangling number instead of the regular host one.
13629 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13630 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13631 return createDeviceMangleContext(T: *getAuxTargetInfo());
13632 }
13633
13634 return createMangleContext(T: getAuxTargetInfo());
13635}
13636
13637CXXABI::~CXXABI() = default;
13638
13639size_t ASTContext::getSideTableAllocatedMemory() const {
13640 return ASTRecordLayouts.getMemorySize() +
13641 llvm::capacity_in_bytes(X: ObjCLayouts) +
13642 llvm::capacity_in_bytes(X: KeyFunctions) +
13643 llvm::capacity_in_bytes(X: ObjCImpls) +
13644 llvm::capacity_in_bytes(X: BlockVarCopyInits) +
13645 llvm::capacity_in_bytes(X: DeclAttrs) +
13646 llvm::capacity_in_bytes(X: TemplateOrInstantiation) +
13647 llvm::capacity_in_bytes(X: InstantiatedFromUsingDecl) +
13648 llvm::capacity_in_bytes(X: InstantiatedFromUsingShadowDecl) +
13649 llvm::capacity_in_bytes(X: InstantiatedFromUnnamedFieldDecl) +
13650 llvm::capacity_in_bytes(X: OverriddenMethods) +
13651 llvm::capacity_in_bytes(X: Types) +
13652 llvm::capacity_in_bytes(x: VariableArrayTypes);
13653}
13654
13655/// getIntTypeForBitwidth -
13656/// sets integer QualTy according to specified details:
13657/// bitwidth, signed/unsigned.
13658/// Returns empty type if there is no appropriate target types.
13659QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
13660 unsigned Signed) const {
13661 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(BitWidth: DestWidth, IsSigned: Signed);
13662 CanQualType QualTy = getFromTargetType(Type: Ty);
13663 if (!QualTy && DestWidth == 128)
13664 return Signed ? Int128Ty : UnsignedInt128Ty;
13665 return QualTy;
13666}
13667
13668QualType ASTContext::getLeastIntTypeForBitwidth(unsigned DestWidth,
13669 unsigned Signed) const {
13670 return getFromTargetType(
13671 Type: getTargetInfo().getLeastIntTypeByWidth(BitWidth: DestWidth, IsSigned: Signed));
13672}
13673
13674/// getRealTypeForBitwidth -
13675/// sets floating point QualTy according to specified bitwidth.
13676/// Returns empty type if there is no appropriate target types.
13677QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
13678 FloatModeKind ExplicitType) const {
13679 FloatModeKind Ty =
13680 getTargetInfo().getRealTypeByWidth(BitWidth: DestWidth, ExplicitType);
13681 switch (Ty) {
13682 case FloatModeKind::Half:
13683 return HalfTy;
13684 case FloatModeKind::Float:
13685 return FloatTy;
13686 case FloatModeKind::Double:
13687 return DoubleTy;
13688 case FloatModeKind::LongDouble:
13689 return LongDoubleTy;
13690 case FloatModeKind::Float128:
13691 return Float128Ty;
13692 case FloatModeKind::Ibm128:
13693 return Ibm128Ty;
13694 case FloatModeKind::NoFloat:
13695 return {};
13696 }
13697
13698 llvm_unreachable("Unhandled TargetInfo::RealType value");
13699}
13700
13701void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13702 if (Number <= 1)
13703 return;
13704
13705 MangleNumbers[ND] = Number;
13706
13707 if (Listener)
13708 Listener->AddedManglingNumber(D: ND, Number);
13709}
13710
13711unsigned ASTContext::getManglingNumber(const NamedDecl *ND,
13712 bool ForAuxTarget) const {
13713 auto I = MangleNumbers.find(Key: ND);
13714 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13715 // CUDA/HIP host compilation encodes host and device mangling numbers
13716 // as lower and upper half of 32 bit integer.
13717 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13718 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13719 } else {
13720 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13721 "number for aux target");
13722 }
13723 return Res > 1 ? Res : 1;
13724}
13725
13726void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13727 if (Number <= 1)
13728 return;
13729
13730 StaticLocalNumbers[VD] = Number;
13731
13732 if (Listener)
13733 Listener->AddedStaticLocalNumbers(D: VD, Number);
13734}
13735
13736unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
13737 auto I = StaticLocalNumbers.find(Key: VD);
13738 return I != StaticLocalNumbers.end() ? I->second : 1;
13739}
13740
13741void ASTContext::setIsDestroyingOperatorDelete(const FunctionDecl *FD,
13742 bool IsDestroying) {
13743 if (!IsDestroying) {
13744 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13745 return;
13746 }
13747 DestroyingOperatorDeletes.insert(V: FD->getCanonicalDecl());
13748}
13749
13750bool ASTContext::isDestroyingOperatorDelete(const FunctionDecl *FD) const {
13751 return DestroyingOperatorDeletes.contains(V: FD->getCanonicalDecl());
13752}
13753
13754void ASTContext::setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD,
13755 bool IsTypeAware) {
13756 if (!IsTypeAware) {
13757 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13758 return;
13759 }
13760 TypeAwareOperatorNewAndDeletes.insert(V: FD->getCanonicalDecl());
13761}
13762
13763bool ASTContext::isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const {
13764 return TypeAwareOperatorNewAndDeletes.contains(V: FD->getCanonicalDecl());
13765}
13766
13767void ASTContext::addOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor,
13768 FunctionDecl *OperatorDelete,
13769 OperatorDeleteKind K) const {
13770 switch (K) {
13771 case OperatorDeleteKind::Regular:
13772 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13773 break;
13774 case OperatorDeleteKind::GlobalRegular:
13775 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13776 OperatorDelete;
13777 break;
13778 case OperatorDeleteKind::Array:
13779 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13780 OperatorDelete;
13781 break;
13782 case OperatorDeleteKind::ArrayGlobal:
13783 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13784 OperatorDelete;
13785 break;
13786 }
13787}
13788
13789bool ASTContext::dtorHasOperatorDelete(const CXXDestructorDecl *Dtor,
13790 OperatorDeleteKind K) const {
13791 switch (K) {
13792 case OperatorDeleteKind::Regular:
13793 return OperatorDeletesForVirtualDtor.contains(Val: Dtor->getCanonicalDecl());
13794 case OperatorDeleteKind::GlobalRegular:
13795 return GlobalOperatorDeletesForVirtualDtor.contains(
13796 Val: Dtor->getCanonicalDecl());
13797 case OperatorDeleteKind::Array:
13798 return ArrayOperatorDeletesForVirtualDtor.contains(
13799 Val: Dtor->getCanonicalDecl());
13800 case OperatorDeleteKind::ArrayGlobal:
13801 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13802 Val: Dtor->getCanonicalDecl());
13803 }
13804 return false;
13805}
13806
13807FunctionDecl *
13808ASTContext::getOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor,
13809 OperatorDeleteKind K) const {
13810 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13811 switch (K) {
13812 case OperatorDeleteKind::Regular:
13813 if (OperatorDeletesForVirtualDtor.contains(Val: Canon))
13814 return OperatorDeletesForVirtualDtor[Canon];
13815 return nullptr;
13816 case OperatorDeleteKind::GlobalRegular:
13817 if (GlobalOperatorDeletesForVirtualDtor.contains(Val: Canon))
13818 return GlobalOperatorDeletesForVirtualDtor[Canon];
13819 return nullptr;
13820 case OperatorDeleteKind::Array:
13821 if (ArrayOperatorDeletesForVirtualDtor.contains(Val: Canon))
13822 return ArrayOperatorDeletesForVirtualDtor[Canon];
13823 return nullptr;
13824 case OperatorDeleteKind::ArrayGlobal:
13825 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Val: Canon))
13826 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13827 return nullptr;
13828 }
13829 return nullptr;
13830}
13831
13832bool ASTContext::classMaybeNeedsVectorDeletingDestructor(
13833 const CXXRecordDecl *RD) {
13834 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13835 return false;
13836
13837 return MaybeRequireVectorDeletingDtor.count(V: RD);
13838}
13839
13840void ASTContext::setClassMaybeNeedsVectorDeletingDestructor(
13841 const CXXRecordDecl *RD) {
13842 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13843 return;
13844
13845 MaybeRequireVectorDeletingDtor.insert(V: RD);
13846}
13847
13848MangleNumberingContext &
13849ASTContext::getManglingNumberContext(const DeclContext *DC) {
13850 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13851 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13852 if (!MCtx)
13853 MCtx = createMangleNumberingContext();
13854 return *MCtx;
13855}
13856
13857MangleNumberingContext &
13858ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
13859 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13860 std::unique_ptr<MangleNumberingContext> &MCtx =
13861 ExtraMangleNumberingContexts[D];
13862 if (!MCtx)
13863 MCtx = createMangleNumberingContext();
13864 return *MCtx;
13865}
13866
13867std::unique_ptr<MangleNumberingContext>
13868ASTContext::createMangleNumberingContext() const {
13869 return ABI->createMangleNumberingContext();
13870}
13871
13872const CXXConstructorDecl *
13873ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
13874 return ABI->getCopyConstructorForExceptionObject(
13875 cast<CXXRecordDecl>(Val: RD->getFirstDecl()));
13876}
13877
13878void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
13879 CXXConstructorDecl *CD) {
13880 return ABI->addCopyConstructorForExceptionObject(
13881 cast<CXXRecordDecl>(Val: RD->getFirstDecl()),
13882 cast<CXXConstructorDecl>(Val: CD->getFirstDecl()));
13883}
13884
13885void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
13886 TypedefNameDecl *DD) {
13887 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13888}
13889
13890TypedefNameDecl *
13891ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
13892 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13893}
13894
13895void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
13896 DeclaratorDecl *DD) {
13897 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13898}
13899
13900DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
13901 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13902}
13903
13904void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
13905 ParamIndices[D] = index;
13906}
13907
13908unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
13909 ParameterIndexTable::const_iterator I = ParamIndices.find(Val: D);
13910 assert(I != ParamIndices.end() &&
13911 "ParmIndices lacks entry set by ParmVarDecl");
13912 return I->second;
13913}
13914
13915QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
13916 unsigned Length) const {
13917 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13918 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13919 EltTy = EltTy.withConst();
13920
13921 EltTy = adjustStringLiteralBaseType(Ty: EltTy);
13922
13923 // Get an array type for the string, according to C99 6.4.5. This includes
13924 // the null terminator character.
13925 return getConstantArrayType(EltTy, ArySizeIn: llvm::APInt(32, Length + 1), SizeExpr: nullptr,
13926 ASM: ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13927}
13928
13929StringLiteral *
13930ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
13931 StringLiteral *&Result = StringLiteralCache[Key];
13932 if (!Result)
13933 Result = StringLiteral::Create(
13934 Ctx: *this, Str: Key, Kind: StringLiteralKind::Ordinary,
13935 /*Pascal*/ false, Ty: getStringLiteralArrayType(EltTy: CharTy, Length: Key.size()),
13936 Locs: SourceLocation());
13937 return Result;
13938}
13939
13940MSGuidDecl *
13941ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
13942 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13943
13944 llvm::FoldingSetNodeID ID;
13945 MSGuidDecl::Profile(ID, P: Parts);
13946
13947 void *InsertPos;
13948 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13949 return Existing;
13950
13951 QualType GUIDType = getMSGuidType().withConst();
13952 MSGuidDecl *New = MSGuidDecl::Create(C: *this, T: GUIDType, P: Parts);
13953 MSGuidDecls.InsertNode(N: New, InsertPos);
13954 return New;
13955}
13956
13957UnnamedGlobalConstantDecl *
13958ASTContext::getUnnamedGlobalConstantDecl(QualType Ty,
13959 const APValue &APVal) const {
13960 llvm::FoldingSetNodeID ID;
13961 UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal);
13962
13963 void *InsertPos;
13964 if (UnnamedGlobalConstantDecl *Existing =
13965 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13966 return Existing;
13967
13968 UnnamedGlobalConstantDecl *New =
13969 UnnamedGlobalConstantDecl::Create(C: *this, T: Ty, APVal);
13970 UnnamedGlobalConstantDecls.InsertNode(N: New, InsertPos);
13971 return New;
13972}
13973
13974TemplateParamObjectDecl *
13975ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
13976 assert(T->isRecordType() && "template param object of unexpected type");
13977
13978 // C++ [temp.param]p8:
13979 // [...] a static storage duration object of type 'const T' [...]
13980 T.addConst();
13981
13982 llvm::FoldingSetNodeID ID;
13983 TemplateParamObjectDecl::Profile(ID, T, V);
13984
13985 void *InsertPos;
13986 if (TemplateParamObjectDecl *Existing =
13987 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13988 return Existing;
13989
13990 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(C: *this, T, V);
13991 TemplateParamObjectDecls.InsertNode(N: New, InsertPos);
13992 return New;
13993}
13994
13995bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
13996 const llvm::Triple &T = getTargetInfo().getTriple();
13997 if (!T.isOSDarwin())
13998 return false;
13999
14000 if (!(T.isiOS() && T.isOSVersionLT(Major: 7)) &&
14001 !(T.isMacOSX() && T.isOSVersionLT(Major: 10, Minor: 9)))
14002 return false;
14003
14004 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
14005 CharUnits sizeChars = getTypeSizeInChars(T: AtomicTy);
14006 uint64_t Size = sizeChars.getQuantity();
14007 CharUnits alignChars = getTypeAlignInChars(T: AtomicTy);
14008 unsigned Align = alignChars.getQuantity();
14009 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
14010 return (Size != Align || toBits(CharSize: sizeChars) > MaxInlineWidthInBits);
14011}
14012
14013bool
14014ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
14015 const ObjCMethodDecl *MethodImpl) {
14016 // No point trying to match an unavailable/deprecated mothod.
14017 if (MethodDecl->hasAttr<UnavailableAttr>()
14018 || MethodDecl->hasAttr<DeprecatedAttr>())
14019 return false;
14020 if (MethodDecl->getObjCDeclQualifier() !=
14021 MethodImpl->getObjCDeclQualifier())
14022 return false;
14023 if (!hasSameType(T1: MethodDecl->getReturnType(), T2: MethodImpl->getReturnType()))
14024 return false;
14025
14026 if (MethodDecl->param_size() != MethodImpl->param_size())
14027 return false;
14028
14029 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
14030 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
14031 EF = MethodDecl->param_end();
14032 IM != EM && IF != EF; ++IM, ++IF) {
14033 const ParmVarDecl *DeclVar = (*IF);
14034 const ParmVarDecl *ImplVar = (*IM);
14035 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
14036 return false;
14037 if (!hasSameType(T1: DeclVar->getType(), T2: ImplVar->getType()))
14038 return false;
14039 }
14040
14041 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
14042}
14043
14044uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
14045 LangAS AS;
14046 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
14047 AS = LangAS::Default;
14048 else
14049 AS = QT->getPointeeType().getAddressSpace();
14050
14051 return getTargetInfo().getNullPointerValue(AddrSpace: AS);
14052}
14053
14054unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
14055 return getTargetInfo().getTargetAddressSpace(AS);
14056}
14057
14058bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
14059 if (X == Y)
14060 return true;
14061 if (!X || !Y)
14062 return false;
14063 llvm::FoldingSetNodeID IDX, IDY;
14064 X->Profile(ID&: IDX, Context: *this, /*Canonical=*/true);
14065 Y->Profile(ID&: IDY, Context: *this, /*Canonical=*/true);
14066 return IDX == IDY;
14067}
14068
14069// The getCommon* helpers return, for given 'same' X and Y entities given as
14070// inputs, another entity which is also the 'same' as the inputs, but which
14071// is closer to the canonical form of the inputs, each according to a given
14072// criteria.
14073// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
14074// the regular ones.
14075
14076static Decl *getCommonDecl(Decl *X, Decl *Y) {
14077 if (!declaresSameEntity(D1: X, D2: Y))
14078 return nullptr;
14079 for (const Decl *DX : X->redecls()) {
14080 // If we reach Y before reaching the first decl, that means X is older.
14081 if (DX == Y)
14082 return X;
14083 // If we reach the first decl, then Y is older.
14084 if (DX->isFirstDecl())
14085 return Y;
14086 }
14087 llvm_unreachable("Corrupt redecls chain");
14088}
14089
14090template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14091static T *getCommonDecl(T *X, T *Y) {
14092 return cast_or_null<T>(
14093 getCommonDecl(X: const_cast<Decl *>(cast_or_null<Decl>(X)),
14094 Y: const_cast<Decl *>(cast_or_null<Decl>(Y))));
14095}
14096
14097template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14098static T *getCommonDeclChecked(T *X, T *Y) {
14099 return cast<T>(getCommonDecl(X: const_cast<Decl *>(cast<Decl>(X)),
14100 Y: const_cast<Decl *>(cast<Decl>(Y))));
14101}
14102
14103static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X,
14104 TemplateName Y,
14105 bool IgnoreDeduced = false) {
14106 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
14107 return X;
14108 // FIXME: There are cases here where we could find a common template name
14109 // with more sugar. For example one could be a SubstTemplateTemplate*
14110 // replacing the other.
14111 TemplateName CX = Ctx.getCanonicalTemplateName(Name: X, IgnoreDeduced);
14112 if (CX.getAsVoidPointer() !=
14113 Ctx.getCanonicalTemplateName(Name: Y).getAsVoidPointer())
14114 return TemplateName();
14115 return CX;
14116}
14117
14118static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx,
14119 TemplateName X, TemplateName Y,
14120 bool IgnoreDeduced) {
14121 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
14122 assert(R.getAsVoidPointer() != nullptr);
14123 return R;
14124}
14125
14126static auto getCommonTypes(const ASTContext &Ctx, ArrayRef<QualType> Xs,
14127 ArrayRef<QualType> Ys, bool Unqualified = false) {
14128 assert(Xs.size() == Ys.size());
14129 SmallVector<QualType, 8> Rs(Xs.size());
14130 for (size_t I = 0; I < Rs.size(); ++I)
14131 Rs[I] = Ctx.getCommonSugaredType(X: Xs[I], Y: Ys[I], Unqualified);
14132 return Rs;
14133}
14134
14135template <class T>
14136static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
14137 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
14138 : SourceLocation();
14139}
14140
14141static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx,
14142 const TemplateArgument &X,
14143 const TemplateArgument &Y) {
14144 if (X.getKind() != Y.getKind())
14145 return TemplateArgument();
14146
14147 switch (X.getKind()) {
14148 case TemplateArgument::ArgKind::Type:
14149 if (!Ctx.hasSameType(T1: X.getAsType(), T2: Y.getAsType()))
14150 return TemplateArgument();
14151 return TemplateArgument(
14152 Ctx.getCommonSugaredType(X: X.getAsType(), Y: Y.getAsType()));
14153 case TemplateArgument::ArgKind::NullPtr:
14154 if (!Ctx.hasSameType(T1: X.getNullPtrType(), T2: Y.getNullPtrType()))
14155 return TemplateArgument();
14156 return TemplateArgument(
14157 Ctx.getCommonSugaredType(X: X.getNullPtrType(), Y: Y.getNullPtrType()),
14158 /*Unqualified=*/true);
14159 case TemplateArgument::ArgKind::Expression:
14160 if (!Ctx.hasSameType(T1: X.getAsExpr()->getType(), T2: Y.getAsExpr()->getType()))
14161 return TemplateArgument();
14162 // FIXME: Try to keep the common sugar.
14163 return X;
14164 case TemplateArgument::ArgKind::Template: {
14165 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
14166 TemplateName CTN = ::getCommonTemplateName(Ctx, X: TX, Y: TY);
14167 if (!CTN.getAsVoidPointer())
14168 return TemplateArgument();
14169 return TemplateArgument(CTN);
14170 }
14171 case TemplateArgument::ArgKind::TemplateExpansion: {
14172 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
14173 TY = Y.getAsTemplateOrTemplatePattern();
14174 TemplateName CTN = ::getCommonTemplateName(Ctx, X: TX, Y: TY);
14175 if (!CTN.getAsVoidPointer())
14176 return TemplateName();
14177 auto NExpX = X.getNumTemplateExpansions();
14178 assert(NExpX == Y.getNumTemplateExpansions());
14179 return TemplateArgument(CTN, NExpX);
14180 }
14181 default:
14182 // FIXME: Handle the other argument kinds.
14183 return X;
14184 }
14185}
14186
14187static bool getCommonTemplateArguments(const ASTContext &Ctx,
14188 SmallVectorImpl<TemplateArgument> &R,
14189 ArrayRef<TemplateArgument> Xs,
14190 ArrayRef<TemplateArgument> Ys) {
14191 if (Xs.size() != Ys.size())
14192 return true;
14193 R.resize(N: Xs.size());
14194 for (size_t I = 0; I < R.size(); ++I) {
14195 R[I] = getCommonTemplateArgument(Ctx, X: Xs[I], Y: Ys[I]);
14196 if (R[I].isNull())
14197 return true;
14198 }
14199 return false;
14200}
14201
14202static auto getCommonTemplateArguments(const ASTContext &Ctx,
14203 ArrayRef<TemplateArgument> Xs,
14204 ArrayRef<TemplateArgument> Ys) {
14205 SmallVector<TemplateArgument, 8> R;
14206 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14207 assert(!Different);
14208 (void)Different;
14209 return R;
14210}
14211
14212template <class T>
14213static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y,
14214 bool IsSame) {
14215 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14216 if (KX == KY)
14217 return KX;
14218 KX = getCanonicalElaboratedTypeKeyword(Keyword: KX);
14219 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14220 return KX;
14221}
14222
14223/// Returns a NestedNameSpecifier which has only the common sugar
14224/// present in both NNS1 and NNS2.
14225static NestedNameSpecifier getCommonNNS(const ASTContext &Ctx,
14226 NestedNameSpecifier NNS1,
14227 NestedNameSpecifier NNS2, bool IsSame) {
14228 // If they are identical, all sugar is common.
14229 if (NNS1 == NNS2)
14230 return NNS1;
14231
14232 // IsSame implies both Qualifiers are equivalent.
14233 NestedNameSpecifier Canon = NNS1.getCanonical();
14234 if (Canon != NNS2.getCanonical()) {
14235 assert(!IsSame && "Should be the same NestedNameSpecifier");
14236 // If they are not the same, there is nothing to unify.
14237 return std::nullopt;
14238 }
14239
14240 NestedNameSpecifier R = std::nullopt;
14241 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14242 assert(Kind == NNS2.getKind());
14243 switch (Kind) {
14244 case NestedNameSpecifier::Kind::Namespace: {
14245 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14246 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14247 auto Kind = Namespace1->getKind();
14248 if (Kind != Namespace2->getKind() ||
14249 (Kind == Decl::NamespaceAlias &&
14250 !declaresSameEntity(D1: Namespace1, D2: Namespace2))) {
14251 R = NestedNameSpecifier(
14252 Ctx,
14253 ::getCommonDeclChecked(X: Namespace1->getNamespace(),
14254 Y: Namespace2->getNamespace()),
14255 /*Prefix=*/std::nullopt);
14256 break;
14257 }
14258 // The prefixes for namespaces are not significant, its declaration
14259 // identifies it uniquely.
14260 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, NNS1: Prefix1, NNS2: Prefix2,
14261 /*IsSame=*/false);
14262 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(X: Namespace1, Y: Namespace2),
14263 Prefix);
14264 break;
14265 }
14266 case NestedNameSpecifier::Kind::Type: {
14267 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14268 const Type *T = Ctx.getCommonSugaredType(X: QualType(T1, 0), Y: QualType(T2, 0),
14269 /*Unqualified=*/true)
14270 .getTypePtr();
14271 R = NestedNameSpecifier(T);
14272 break;
14273 }
14274 case NestedNameSpecifier::Kind::MicrosoftSuper: {
14275 // FIXME: Can __super even be used with data members?
14276 // If it's only usable in functions, we will never see it here,
14277 // unless we save the qualifiers used in function types.
14278 // In that case, it might be possible NNS2 is a type,
14279 // in which case we should degrade the result to
14280 // a CXXRecordType.
14281 R = NestedNameSpecifier(getCommonDeclChecked(X: NNS1.getAsMicrosoftSuper(),
14282 Y: NNS2.getAsMicrosoftSuper()));
14283 break;
14284 }
14285 case NestedNameSpecifier::Kind::Null:
14286 case NestedNameSpecifier::Kind::Global:
14287 // These are singletons.
14288 llvm_unreachable("singletons did not compare equal");
14289 }
14290 assert(R.getCanonical() == Canon);
14291 return R;
14292}
14293
14294template <class T>
14295static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X,
14296 const T *Y, bool IsSame) {
14297 return ::getCommonNNS(Ctx, NNS1: X->getQualifier(), NNS2: Y->getQualifier(), IsSame);
14298}
14299
14300template <class T>
14301static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14302 const T *Y) {
14303 return Ctx.getCommonSugaredType(X: X->getElementType(), Y: Y->getElementType());
14304}
14305
14306static QualType getCommonTypeWithQualifierLifting(const ASTContext &Ctx,
14307 QualType X, QualType Y,
14308 Qualifiers &QX,
14309 Qualifiers &QY) {
14310 QualType R = Ctx.getCommonSugaredType(X, Y,
14311 /*Unqualified=*/true);
14312 // Qualifiers common to both element types.
14313 Qualifiers RQ = R.getQualifiers();
14314 // For each side, move to the top level any qualifiers which are not common to
14315 // both element types. The caller must assume top level qualifiers might
14316 // be different, even if they are the same type, and can be treated as sugar.
14317 QX += X.getQualifiers() - RQ;
14318 QY += Y.getQualifiers() - RQ;
14319 return R;
14320}
14321
14322template <class T>
14323static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X,
14324 Qualifiers &QX, const T *Y,
14325 Qualifiers &QY) {
14326 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14327 Y->getElementType(), QX, QY);
14328}
14329
14330template <class T>
14331static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14332 const T *Y) {
14333 return Ctx.getCommonSugaredType(X: X->getPointeeType(), Y: Y->getPointeeType());
14334}
14335
14336template <class T>
14337static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14338 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14339 return X->getSizeExpr();
14340}
14341
14342static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14343 assert(X->getSizeModifier() == Y->getSizeModifier());
14344 return X->getSizeModifier();
14345}
14346
14347static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X,
14348 const ArrayType *Y) {
14349 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14350 return X->getIndexTypeCVRQualifiers();
14351}
14352
14353// Merges two type lists such that the resulting vector will contain
14354// each type (in a canonical sense) only once, in the order they appear
14355// from X to Y. If they occur in both X and Y, the result will contain
14356// the common sugared type between them.
14357static void mergeTypeLists(const ASTContext &Ctx,
14358 SmallVectorImpl<QualType> &Out, ArrayRef<QualType> X,
14359 ArrayRef<QualType> Y) {
14360 llvm::DenseMap<QualType, unsigned> Found;
14361 for (auto Ts : {X, Y}) {
14362 for (QualType T : Ts) {
14363 auto Res = Found.try_emplace(Key: Ctx.getCanonicalType(T), Args: Out.size());
14364 if (!Res.second) {
14365 QualType &U = Out[Res.first->second];
14366 U = Ctx.getCommonSugaredType(X: U, Y: T);
14367 } else {
14368 Out.emplace_back(Args&: T);
14369 }
14370 }
14371 }
14372}
14373
14374FunctionProtoType::ExceptionSpecInfo
14375ASTContext::mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1,
14376 FunctionProtoType::ExceptionSpecInfo ESI2,
14377 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14378 bool AcceptDependent) const {
14379 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14380
14381 // If either of them can throw anything, that is the result.
14382 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14383 if (EST1 == I)
14384 return ESI1;
14385 if (EST2 == I)
14386 return ESI2;
14387 }
14388
14389 // If either of them is non-throwing, the result is the other.
14390 for (auto I :
14391 {EST_NoThrow, EST_DynamicNone, EST_BasicNoexcept, EST_NoexceptTrue}) {
14392 if (EST1 == I)
14393 return ESI2;
14394 if (EST2 == I)
14395 return ESI1;
14396 }
14397
14398 // If we're left with value-dependent computed noexcept expressions, we're
14399 // stuck. Before C++17, we can just drop the exception specification entirely,
14400 // since it's not actually part of the canonical type. And this should never
14401 // happen in C++17, because it would mean we were computing the composite
14402 // pointer type of dependent types, which should never happen.
14403 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14404 assert(AcceptDependent &&
14405 "computing composite pointer type of dependent types");
14406 return FunctionProtoType::ExceptionSpecInfo();
14407 }
14408
14409 // Switch over the possibilities so that people adding new values know to
14410 // update this function.
14411 switch (EST1) {
14412 case EST_None:
14413 case EST_DynamicNone:
14414 case EST_MSAny:
14415 case EST_BasicNoexcept:
14416 case EST_DependentNoexcept:
14417 case EST_NoexceptFalse:
14418 case EST_NoexceptTrue:
14419 case EST_NoThrow:
14420 llvm_unreachable("These ESTs should be handled above");
14421
14422 case EST_Dynamic: {
14423 // This is the fun case: both exception specifications are dynamic. Form
14424 // the union of the two lists.
14425 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14426 mergeTypeLists(Ctx: *this, Out&: ExceptionTypeStorage, X: ESI1.Exceptions,
14427 Y: ESI2.Exceptions);
14428 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
14429 Result.Exceptions = ExceptionTypeStorage;
14430 return Result;
14431 }
14432
14433 case EST_Unevaluated:
14434 case EST_Uninstantiated:
14435 case EST_Unparsed:
14436 llvm_unreachable("shouldn't see unresolved exception specifications here");
14437 }
14438
14439 llvm_unreachable("invalid ExceptionSpecificationType");
14440}
14441
14442static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X,
14443 Qualifiers &QX, const Type *Y,
14444 Qualifiers &QY) {
14445 Type::TypeClass TC = X->getTypeClass();
14446 assert(TC == Y->getTypeClass());
14447 switch (TC) {
14448#define UNEXPECTED_TYPE(Class, Kind) \
14449 case Type::Class: \
14450 llvm_unreachable("Unexpected " Kind ": " #Class);
14451
14452#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14453#define TYPE(Class, Base)
14454#include "clang/AST/TypeNodes.inc"
14455
14456#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14457 SUGAR_FREE_TYPE(Builtin)
14458 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14459 SUGAR_FREE_TYPE(DependentBitInt)
14460 SUGAR_FREE_TYPE(BitInt)
14461 SUGAR_FREE_TYPE(ObjCInterface)
14462 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14463 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14464 SUGAR_FREE_TYPE(UnresolvedUsing)
14465 SUGAR_FREE_TYPE(HLSLAttributedResource)
14466 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14467#undef SUGAR_FREE_TYPE
14468#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14469 NON_UNIQUE_TYPE(TypeOfExpr)
14470 NON_UNIQUE_TYPE(VariableArray)
14471#undef NON_UNIQUE_TYPE
14472
14473 UNEXPECTED_TYPE(TypeOf, "sugar")
14474
14475#undef UNEXPECTED_TYPE
14476
14477 case Type::Auto: {
14478 const auto *AX = cast<AutoType>(Val: X), *AY = cast<AutoType>(Val: Y);
14479 assert(AX->getDeducedKind() == AY->getDeducedKind());
14480 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14481 assert(AX->getKeyword() == AY->getKeyword());
14482 TemplateDecl *CD =
14483 ::getCommonDecl(X: AX->getTypeConstraintConcept().getAsTemplateDecl(),
14484 Y: AY->getTypeConstraintConcept().getAsTemplateDecl());
14485 SmallVector<TemplateArgument, 8> As;
14486 if (CD &&
14487 getCommonTemplateArguments(Ctx, R&: As, Xs: AX->getTypeConstraintArguments(),
14488 Ys: AY->getTypeConstraintArguments())) {
14489 CD = nullptr; // The arguments differ, so make it unconstrained.
14490 As.clear();
14491 }
14492 return Ctx.getAutoType(DK: AX->getDeducedKind(), DeducedAsType: QualType(), Keyword: AX->getKeyword(),
14493 TypeConstraintConcept: TemplateName(CD), TypeConstraintArgs: As);
14494 }
14495 case Type::IncompleteArray: {
14496 const auto *AX = cast<IncompleteArrayType>(Val: X),
14497 *AY = cast<IncompleteArrayType>(Val: Y);
14498 return Ctx.getIncompleteArrayType(
14499 elementType: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY),
14500 ASM: getCommonSizeModifier(X: AX, Y: AY), elementTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14501 }
14502 case Type::DependentSizedArray: {
14503 const auto *AX = cast<DependentSizedArrayType>(Val: X),
14504 *AY = cast<DependentSizedArrayType>(Val: Y);
14505 return Ctx.getDependentSizedArrayType(
14506 elementType: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY),
14507 numElements: getCommonSizeExpr(Ctx, X: AX, Y: AY), ASM: getCommonSizeModifier(X: AX, Y: AY),
14508 elementTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14509 }
14510 case Type::ConstantArray: {
14511 const auto *AX = cast<ConstantArrayType>(Val: X),
14512 *AY = cast<ConstantArrayType>(Val: Y);
14513 assert(AX->getSize() == AY->getSize());
14514 const Expr *SizeExpr = Ctx.hasSameExpr(X: AX->getSizeExpr(), Y: AY->getSizeExpr())
14515 ? AX->getSizeExpr()
14516 : nullptr;
14517 return Ctx.getConstantArrayType(
14518 EltTy: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY), ArySizeIn: AX->getSize(), SizeExpr,
14519 ASM: getCommonSizeModifier(X: AX, Y: AY), IndexTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14520 }
14521 case Type::ArrayParameter: {
14522 const auto *AX = cast<ArrayParameterType>(Val: X),
14523 *AY = cast<ArrayParameterType>(Val: Y);
14524 assert(AX->getSize() == AY->getSize());
14525 const Expr *SizeExpr = Ctx.hasSameExpr(X: AX->getSizeExpr(), Y: AY->getSizeExpr())
14526 ? AX->getSizeExpr()
14527 : nullptr;
14528 auto ArrayTy = Ctx.getConstantArrayType(
14529 EltTy: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY), ArySizeIn: AX->getSize(), SizeExpr,
14530 ASM: getCommonSizeModifier(X: AX, Y: AY), IndexTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14531 return Ctx.getArrayParameterType(Ty: ArrayTy);
14532 }
14533 case Type::Atomic: {
14534 const auto *AX = cast<AtomicType>(Val: X), *AY = cast<AtomicType>(Val: Y);
14535 return Ctx.getAtomicType(
14536 T: Ctx.getCommonSugaredType(X: AX->getValueType(), Y: AY->getValueType()));
14537 }
14538 case Type::Complex: {
14539 const auto *CX = cast<ComplexType>(Val: X), *CY = cast<ComplexType>(Val: Y);
14540 return Ctx.getComplexType(T: getCommonArrayElementType(Ctx, X: CX, QX, Y: CY, QY));
14541 }
14542 case Type::Pointer: {
14543 const auto *PX = cast<PointerType>(Val: X), *PY = cast<PointerType>(Val: Y);
14544 return Ctx.getPointerType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14545 }
14546 case Type::BlockPointer: {
14547 const auto *PX = cast<BlockPointerType>(Val: X), *PY = cast<BlockPointerType>(Val: Y);
14548 return Ctx.getBlockPointerType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14549 }
14550 case Type::ObjCObjectPointer: {
14551 const auto *PX = cast<ObjCObjectPointerType>(Val: X),
14552 *PY = cast<ObjCObjectPointerType>(Val: Y);
14553 return Ctx.getObjCObjectPointerType(ObjectT: getCommonPointeeType(Ctx, X: PX, Y: PY));
14554 }
14555 case Type::MemberPointer: {
14556 const auto *PX = cast<MemberPointerType>(Val: X),
14557 *PY = cast<MemberPointerType>(Val: Y);
14558 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14559 PY->getMostRecentCXXRecordDecl()));
14560 return Ctx.getMemberPointerType(
14561 T: getCommonPointeeType(Ctx, X: PX, Y: PY),
14562 Qualifier: getCommonQualifier(Ctx, X: PX, Y: PY, /*IsSame=*/true),
14563 Cls: PX->getMostRecentCXXRecordDecl());
14564 }
14565 case Type::LValueReference: {
14566 const auto *PX = cast<LValueReferenceType>(Val: X),
14567 *PY = cast<LValueReferenceType>(Val: Y);
14568 // FIXME: Preserve PointeeTypeAsWritten.
14569 return Ctx.getLValueReferenceType(T: getCommonPointeeType(Ctx, X: PX, Y: PY),
14570 SpelledAsLValue: PX->isSpelledAsLValue() ||
14571 PY->isSpelledAsLValue());
14572 }
14573 case Type::RValueReference: {
14574 const auto *PX = cast<RValueReferenceType>(Val: X),
14575 *PY = cast<RValueReferenceType>(Val: Y);
14576 // FIXME: Preserve PointeeTypeAsWritten.
14577 return Ctx.getRValueReferenceType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14578 }
14579 case Type::DependentAddressSpace: {
14580 const auto *PX = cast<DependentAddressSpaceType>(Val: X),
14581 *PY = cast<DependentAddressSpaceType>(Val: Y);
14582 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14583 return Ctx.getDependentAddressSpaceType(PointeeType: getCommonPointeeType(Ctx, X: PX, Y: PY),
14584 AddrSpaceExpr: PX->getAddrSpaceExpr(),
14585 AttrLoc: getCommonAttrLoc(X: PX, Y: PY));
14586 }
14587 case Type::FunctionNoProto: {
14588 const auto *FX = cast<FunctionNoProtoType>(Val: X),
14589 *FY = cast<FunctionNoProtoType>(Val: Y);
14590 assert(FX->getExtInfo() == FY->getExtInfo());
14591 return Ctx.getFunctionNoProtoType(
14592 ResultTy: Ctx.getCommonSugaredType(X: FX->getReturnType(), Y: FY->getReturnType()),
14593 Info: FX->getExtInfo());
14594 }
14595 case Type::FunctionProto: {
14596 const auto *FX = cast<FunctionProtoType>(Val: X),
14597 *FY = cast<FunctionProtoType>(Val: Y);
14598 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14599 EPIY = FY->getExtProtoInfo();
14600 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14601 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14602 assert(!EPIX.ExtParameterInfos ||
14603 llvm::equal(
14604 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14605 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14606 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14607 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14608 assert(EPIX.Variadic == EPIY.Variadic);
14609
14610 // FIXME: Can we handle an empty EllipsisLoc?
14611 // Use emtpy EllipsisLoc if X and Y differ.
14612
14613 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14614
14615 QualType R =
14616 Ctx.getCommonSugaredType(X: FX->getReturnType(), Y: FY->getReturnType());
14617 auto P = getCommonTypes(Ctx, Xs: FX->param_types(), Ys: FY->param_types(),
14618 /*Unqualified=*/true);
14619
14620 SmallVector<QualType, 8> Exceptions;
14621 EPIX.ExceptionSpec = Ctx.mergeExceptionSpecs(
14622 ESI1: EPIX.ExceptionSpec, ESI2: EPIY.ExceptionSpec, ExceptionTypeStorage&: Exceptions, AcceptDependent: true);
14623 return Ctx.getFunctionType(ResultTy: R, Args: P, EPI: EPIX);
14624 }
14625 case Type::ObjCObject: {
14626 const auto *OX = cast<ObjCObjectType>(Val: X), *OY = cast<ObjCObjectType>(Val: Y);
14627 assert(
14628 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14629 OY->getProtocols().begin(), OY->getProtocols().end(),
14630 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14631 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14632 }) &&
14633 "protocol lists must be the same");
14634 auto TAs = getCommonTypes(Ctx, Xs: OX->getTypeArgsAsWritten(),
14635 Ys: OY->getTypeArgsAsWritten());
14636 return Ctx.getObjCObjectType(
14637 baseType: Ctx.getCommonSugaredType(X: OX->getBaseType(), Y: OY->getBaseType()), typeArgs: TAs,
14638 protocols: OX->getProtocols(),
14639 isKindOf: OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14640 }
14641 case Type::ConstantMatrix: {
14642 const auto *MX = cast<ConstantMatrixType>(Val: X),
14643 *MY = cast<ConstantMatrixType>(Val: Y);
14644 assert(MX->getNumRows() == MY->getNumRows());
14645 assert(MX->getNumColumns() == MY->getNumColumns());
14646 return Ctx.getConstantMatrixType(ElementTy: getCommonElementType(Ctx, X: MX, Y: MY),
14647 NumRows: MX->getNumRows(), NumColumns: MX->getNumColumns());
14648 }
14649 case Type::DependentSizedMatrix: {
14650 const auto *MX = cast<DependentSizedMatrixType>(Val: X),
14651 *MY = cast<DependentSizedMatrixType>(Val: Y);
14652 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14653 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14654 return Ctx.getDependentSizedMatrixType(
14655 ElementTy: getCommonElementType(Ctx, X: MX, Y: MY), RowExpr: MX->getRowExpr(),
14656 ColumnExpr: MX->getColumnExpr(), AttrLoc: getCommonAttrLoc(X: MX, Y: MY));
14657 }
14658 case Type::Vector: {
14659 const auto *VX = cast<VectorType>(Val: X), *VY = cast<VectorType>(Val: Y);
14660 assert(VX->getNumElements() == VY->getNumElements());
14661 assert(VX->getVectorKind() == VY->getVectorKind());
14662 return Ctx.getVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14663 NumElts: VX->getNumElements(), VecKind: VX->getVectorKind());
14664 }
14665 case Type::ExtVector: {
14666 const auto *VX = cast<ExtVectorType>(Val: X), *VY = cast<ExtVectorType>(Val: Y);
14667 assert(VX->getNumElements() == VY->getNumElements());
14668 return Ctx.getExtVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14669 NumElts: VX->getNumElements());
14670 }
14671 case Type::DependentSizedExtVector: {
14672 const auto *VX = cast<DependentSizedExtVectorType>(Val: X),
14673 *VY = cast<DependentSizedExtVectorType>(Val: Y);
14674 return Ctx.getDependentSizedExtVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14675 SizeExpr: getCommonSizeExpr(Ctx, X: VX, Y: VY),
14676 AttrLoc: getCommonAttrLoc(X: VX, Y: VY));
14677 }
14678 case Type::DependentVector: {
14679 const auto *VX = cast<DependentVectorType>(Val: X),
14680 *VY = cast<DependentVectorType>(Val: Y);
14681 assert(VX->getVectorKind() == VY->getVectorKind());
14682 return Ctx.getDependentVectorType(
14683 VecType: getCommonElementType(Ctx, X: VX, Y: VY), SizeExpr: getCommonSizeExpr(Ctx, X: VX, Y: VY),
14684 AttrLoc: getCommonAttrLoc(X: VX, Y: VY), VecKind: VX->getVectorKind());
14685 }
14686 case Type::Enum:
14687 case Type::Record:
14688 case Type::InjectedClassName: {
14689 const auto *TX = cast<TagType>(Val: X), *TY = cast<TagType>(Val: Y);
14690 return Ctx.getTagType(Keyword: ::getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14691 Qualifier: ::getCommonQualifier(Ctx, X: TX, Y: TY, /*IsSame=*/false),
14692 TD: ::getCommonDeclChecked(X: TX->getDecl(), Y: TY->getDecl()),
14693 /*OwnedTag=*/OwnsTag: false);
14694 }
14695 case Type::TemplateSpecialization: {
14696 const auto *TX = cast<TemplateSpecializationType>(Val: X),
14697 *TY = cast<TemplateSpecializationType>(Val: Y);
14698 auto As = getCommonTemplateArguments(Ctx, Xs: TX->template_arguments(),
14699 Ys: TY->template_arguments());
14700 return Ctx.getTemplateSpecializationType(
14701 Keyword: getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14702 Template: ::getCommonTemplateNameChecked(Ctx, X: TX->getTemplateName(),
14703 Y: TY->getTemplateName(),
14704 /*IgnoreDeduced=*/true),
14705 SpecifiedArgs: As, /*CanonicalArgs=*/{}, Underlying: X->getCanonicalTypeInternal());
14706 }
14707 case Type::Decltype: {
14708 const auto *DX = cast<DecltypeType>(Val: X);
14709 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Val: Y);
14710 assert(DX->isDependentType());
14711 assert(DY->isDependentType());
14712 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14713 // As Decltype is not uniqued, building a common type would be wasteful.
14714 return QualType(DX, 0);
14715 }
14716 case Type::PackIndexing: {
14717 const auto *DX = cast<PackIndexingType>(Val: X);
14718 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Val: Y);
14719 assert(DX->isDependentType());
14720 assert(DY->isDependentType());
14721 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14722 return QualType(DX, 0);
14723 }
14724 case Type::DependentName: {
14725 const auto *NX = cast<DependentNameType>(Val: X),
14726 *NY = cast<DependentNameType>(Val: Y);
14727 assert(NX->getIdentifier() == NY->getIdentifier());
14728 return Ctx.getDependentNameType(
14729 Keyword: getCommonTypeKeyword(X: NX, Y: NY, /*IsSame=*/true),
14730 NNS: getCommonQualifier(Ctx, X: NX, Y: NY, /*IsSame=*/true), Name: NX->getIdentifier());
14731 }
14732 case Type::OverflowBehavior: {
14733 const auto *NX = cast<OverflowBehaviorType>(Val: X),
14734 *NY = cast<OverflowBehaviorType>(Val: Y);
14735 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14736 return Ctx.getOverflowBehaviorType(
14737 Kind: NX->getBehaviorKind(),
14738 Underlying: getCommonTypeWithQualifierLifting(Ctx, X: NX->getUnderlyingType(),
14739 Y: NY->getUnderlyingType(), QX, QY));
14740 }
14741 case Type::UnaryTransform: {
14742 const auto *TX = cast<UnaryTransformType>(Val: X),
14743 *TY = cast<UnaryTransformType>(Val: Y);
14744 assert(TX->getUTTKind() == TY->getUTTKind());
14745 return Ctx.getUnaryTransformType(
14746 BaseType: Ctx.getCommonSugaredType(X: TX->getBaseType(), Y: TY->getBaseType()),
14747 UnderlyingType: Ctx.getCommonSugaredType(X: TX->getUnderlyingType(),
14748 Y: TY->getUnderlyingType()),
14749 Kind: TX->getUTTKind());
14750 }
14751 case Type::PackExpansion: {
14752 const auto *PX = cast<PackExpansionType>(Val: X),
14753 *PY = cast<PackExpansionType>(Val: Y);
14754 assert(PX->getNumExpansions() == PY->getNumExpansions());
14755 return Ctx.getPackExpansionType(
14756 Pattern: Ctx.getCommonSugaredType(X: PX->getPattern(), Y: PY->getPattern()),
14757 NumExpansions: PX->getNumExpansions(), ExpectPackInType: false);
14758 }
14759 case Type::Pipe: {
14760 const auto *PX = cast<PipeType>(Val: X), *PY = cast<PipeType>(Val: Y);
14761 assert(PX->isReadOnly() == PY->isReadOnly());
14762 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14763 : &ASTContext::getWritePipeType;
14764 return (Ctx.*MP)(getCommonElementType(Ctx, X: PX, Y: PY));
14765 }
14766 case Type::TemplateTypeParm: {
14767 const auto *TX = cast<TemplateTypeParmType>(Val: X),
14768 *TY = cast<TemplateTypeParmType>(Val: Y);
14769 assert(TX->getDepth() == TY->getDepth());
14770 assert(TX->getIndex() == TY->getIndex());
14771 assert(TX->isParameterPack() == TY->isParameterPack());
14772 return Ctx.getTemplateTypeParmType(
14773 Depth: TX->getDepth(), Index: TX->getIndex(), ParameterPack: TX->isParameterPack(),
14774 TTPDecl: getCommonDecl(X: TX->getDecl(), Y: TY->getDecl()));
14775 }
14776 }
14777 llvm_unreachable("Unknown Type Class");
14778}
14779
14780static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X,
14781 const Type *Y,
14782 SplitQualType Underlying) {
14783 Type::TypeClass TC = X->getTypeClass();
14784 if (TC != Y->getTypeClass())
14785 return QualType();
14786 switch (TC) {
14787#define UNEXPECTED_TYPE(Class, Kind) \
14788 case Type::Class: \
14789 llvm_unreachable("Unexpected " Kind ": " #Class);
14790#define TYPE(Class, Base)
14791#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14792#include "clang/AST/TypeNodes.inc"
14793
14794#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14795 CANONICAL_TYPE(Atomic)
14796 CANONICAL_TYPE(BitInt)
14797 CANONICAL_TYPE(BlockPointer)
14798 CANONICAL_TYPE(Builtin)
14799 CANONICAL_TYPE(Complex)
14800 CANONICAL_TYPE(ConstantArray)
14801 CANONICAL_TYPE(ArrayParameter)
14802 CANONICAL_TYPE(ConstantMatrix)
14803 CANONICAL_TYPE(Enum)
14804 CANONICAL_TYPE(ExtVector)
14805 CANONICAL_TYPE(FunctionNoProto)
14806 CANONICAL_TYPE(FunctionProto)
14807 CANONICAL_TYPE(IncompleteArray)
14808 CANONICAL_TYPE(HLSLAttributedResource)
14809 CANONICAL_TYPE(HLSLInlineSpirv)
14810 CANONICAL_TYPE(LValueReference)
14811 CANONICAL_TYPE(ObjCInterface)
14812 CANONICAL_TYPE(ObjCObject)
14813 CANONICAL_TYPE(ObjCObjectPointer)
14814 CANONICAL_TYPE(OverflowBehavior)
14815 CANONICAL_TYPE(Pipe)
14816 CANONICAL_TYPE(Pointer)
14817 CANONICAL_TYPE(Record)
14818 CANONICAL_TYPE(RValueReference)
14819 CANONICAL_TYPE(VariableArray)
14820 CANONICAL_TYPE(Vector)
14821#undef CANONICAL_TYPE
14822
14823#undef UNEXPECTED_TYPE
14824
14825 case Type::Adjusted: {
14826 const auto *AX = cast<AdjustedType>(Val: X), *AY = cast<AdjustedType>(Val: Y);
14827 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14828 if (!Ctx.hasSameType(T1: OX, T2: OY))
14829 return QualType();
14830 // FIXME: It's inefficient to have to unify the original types.
14831 return Ctx.getAdjustedType(Orig: Ctx.getCommonSugaredType(X: OX, Y: OY),
14832 New: Ctx.getQualifiedType(split: Underlying));
14833 }
14834 case Type::Decayed: {
14835 const auto *DX = cast<DecayedType>(Val: X), *DY = cast<DecayedType>(Val: Y);
14836 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14837 if (!Ctx.hasSameType(T1: OX, T2: OY))
14838 return QualType();
14839 // FIXME: It's inefficient to have to unify the original types.
14840 return Ctx.getDecayedType(Orig: Ctx.getCommonSugaredType(X: OX, Y: OY),
14841 Decayed: Ctx.getQualifiedType(split: Underlying));
14842 }
14843 case Type::Attributed: {
14844 const auto *AX = cast<AttributedType>(Val: X), *AY = cast<AttributedType>(Val: Y);
14845 AttributedType::Kind Kind = AX->getAttrKind();
14846 if (Kind != AY->getAttrKind())
14847 return QualType();
14848 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14849 if (!Ctx.hasSameType(T1: MX, T2: MY))
14850 return QualType();
14851 // FIXME: It's inefficient to have to unify the modified types.
14852 return Ctx.getAttributedType(attrKind: Kind, modifiedType: Ctx.getCommonSugaredType(X: MX, Y: MY),
14853 equivalentType: Ctx.getQualifiedType(split: Underlying),
14854 attr: AX->getAttr());
14855 }
14856 case Type::BTFTagAttributed: {
14857 const auto *BX = cast<BTFTagAttributedType>(Val: X);
14858 const BTFTypeTagAttr *AX = BX->getAttr();
14859 // The attribute is not uniqued, so just compare the tag.
14860 if (AX->getBTFTypeTag() !=
14861 cast<BTFTagAttributedType>(Val: Y)->getAttr()->getBTFTypeTag())
14862 return QualType();
14863 return Ctx.getBTFTagAttributedType(BTFAttr: AX, Wrapped: Ctx.getQualifiedType(split: Underlying));
14864 }
14865 case Type::Auto: {
14866 const auto *AX = cast<AutoType>(Val: X), *AY = cast<AutoType>(Val: Y);
14867 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14868 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14869
14870 AutoTypeKeyword KW = AX->getKeyword();
14871 if (KW != AY->getKeyword())
14872 return QualType();
14873
14874 TemplateDecl *CD =
14875 ::getCommonDecl(X: AX->getTypeConstraintConcept().getAsTemplateDecl(),
14876 Y: AY->getTypeConstraintConcept().getAsTemplateDecl());
14877 SmallVector<TemplateArgument, 8> As;
14878 if (CD &&
14879 getCommonTemplateArguments(Ctx, R&: As, Xs: AX->getTypeConstraintArguments(),
14880 Ys: AY->getTypeConstraintArguments())) {
14881 CD = nullptr; // The arguments differ, so make it unconstrained.
14882 As.clear();
14883 }
14884
14885 // Both auto types can't be dependent, otherwise they wouldn't have been
14886 // sugar. This implies they can't contain unexpanded packs either.
14887 return Ctx.getAutoType(DK: DeducedKind::Deduced,
14888 DeducedAsType: Ctx.getQualifiedType(split: Underlying), Keyword: AX->getKeyword(),
14889 TypeConstraintConcept: TemplateName(CD), TypeConstraintArgs: As);
14890 }
14891 case Type::PackIndexing:
14892 case Type::Decltype:
14893 return QualType();
14894 case Type::DeducedTemplateSpecialization:
14895 // FIXME: Try to merge these.
14896 return QualType();
14897 case Type::MacroQualified: {
14898 const auto *MX = cast<MacroQualifiedType>(Val: X),
14899 *MY = cast<MacroQualifiedType>(Val: Y);
14900 const IdentifierInfo *IX = MX->getMacroIdentifier();
14901 if (IX != MY->getMacroIdentifier())
14902 return QualType();
14903 return Ctx.getMacroQualifiedType(UnderlyingTy: Ctx.getQualifiedType(split: Underlying), MacroII: IX);
14904 }
14905 case Type::SubstTemplateTypeParm: {
14906 const auto *SX = cast<SubstTemplateTypeParmType>(Val: X),
14907 *SY = cast<SubstTemplateTypeParmType>(Val: Y);
14908 Decl *CD =
14909 ::getCommonDecl(X: SX->getAssociatedDecl(), Y: SY->getAssociatedDecl());
14910 if (!CD)
14911 return QualType();
14912 unsigned Index = SX->getIndex();
14913 if (Index != SY->getIndex())
14914 return QualType();
14915 auto PackIndex = SX->getPackIndex();
14916 if (PackIndex != SY->getPackIndex())
14917 return QualType();
14918 return Ctx.getSubstTemplateTypeParmType(Replacement: Ctx.getQualifiedType(split: Underlying),
14919 AssociatedDecl: CD, Index, PackIndex,
14920 Final: SX->getFinal() && SY->getFinal());
14921 }
14922 case Type::ObjCTypeParam:
14923 // FIXME: Try to merge these.
14924 return QualType();
14925 case Type::Paren:
14926 return Ctx.getParenType(InnerType: Ctx.getQualifiedType(split: Underlying));
14927
14928 case Type::TemplateSpecialization: {
14929 const auto *TX = cast<TemplateSpecializationType>(Val: X),
14930 *TY = cast<TemplateSpecializationType>(Val: Y);
14931 TemplateName CTN =
14932 ::getCommonTemplateName(Ctx, X: TX->getTemplateName(),
14933 Y: TY->getTemplateName(), /*IgnoreDeduced=*/true);
14934 if (!CTN.getAsVoidPointer())
14935 return QualType();
14936 SmallVector<TemplateArgument, 8> As;
14937 if (getCommonTemplateArguments(Ctx, R&: As, Xs: TX->template_arguments(),
14938 Ys: TY->template_arguments()))
14939 return QualType();
14940 return Ctx.getTemplateSpecializationType(
14941 Keyword: getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false), Template: CTN, SpecifiedArgs: As,
14942 /*CanonicalArgs=*/{}, Underlying: Ctx.getQualifiedType(split: Underlying));
14943 }
14944 case Type::Typedef: {
14945 const auto *TX = cast<TypedefType>(Val: X), *TY = cast<TypedefType>(Val: Y);
14946 const TypedefNameDecl *CD = ::getCommonDecl(X: TX->getDecl(), Y: TY->getDecl());
14947 if (!CD)
14948 return QualType();
14949 return Ctx.getTypedefType(
14950 Keyword: ::getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14951 Qualifier: ::getCommonQualifier(Ctx, X: TX, Y: TY, /*IsSame=*/false), Decl: CD,
14952 UnderlyingType: Ctx.getQualifiedType(split: Underlying));
14953 }
14954 case Type::TypeOf: {
14955 // The common sugar between two typeof expressions, where one is
14956 // potentially a typeof_unqual and the other is not, we unify to the
14957 // qualified type as that retains the most information along with the type.
14958 // We only return a typeof_unqual type when both types are unqual types.
14959 TypeOfKind Kind = TypeOfKind::Qualified;
14960 if (cast<TypeOfType>(Val: X)->getKind() == cast<TypeOfType>(Val: Y)->getKind() &&
14961 cast<TypeOfType>(Val: X)->getKind() == TypeOfKind::Unqualified)
14962 Kind = TypeOfKind::Unqualified;
14963 return Ctx.getTypeOfType(tofType: Ctx.getQualifiedType(split: Underlying), Kind);
14964 }
14965 case Type::TypeOfExpr:
14966 return QualType();
14967
14968 case Type::UnaryTransform: {
14969 const auto *UX = cast<UnaryTransformType>(Val: X),
14970 *UY = cast<UnaryTransformType>(Val: Y);
14971 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14972 if (KX != UY->getUTTKind())
14973 return QualType();
14974 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14975 if (!Ctx.hasSameType(T1: BX, T2: BY))
14976 return QualType();
14977 // FIXME: It's inefficient to have to unify the base types.
14978 return Ctx.getUnaryTransformType(BaseType: Ctx.getCommonSugaredType(X: BX, Y: BY),
14979 UnderlyingType: Ctx.getQualifiedType(split: Underlying), Kind: KX);
14980 }
14981 case Type::Using: {
14982 const auto *UX = cast<UsingType>(Val: X), *UY = cast<UsingType>(Val: Y);
14983 const UsingShadowDecl *CD = ::getCommonDecl(X: UX->getDecl(), Y: UY->getDecl());
14984 if (!CD)
14985 return QualType();
14986 return Ctx.getUsingType(Keyword: ::getCommonTypeKeyword(X: UX, Y: UY, /*IsSame=*/false),
14987 Qualifier: ::getCommonQualifier(Ctx, X: UX, Y: UY, /*IsSame=*/false),
14988 D: CD, UnderlyingType: Ctx.getQualifiedType(split: Underlying));
14989 }
14990 case Type::MemberPointer: {
14991 const auto *PX = cast<MemberPointerType>(Val: X),
14992 *PY = cast<MemberPointerType>(Val: Y);
14993 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14994 assert(Cls == PY->getMostRecentCXXRecordDecl());
14995 return Ctx.getMemberPointerType(
14996 T: ::getCommonPointeeType(Ctx, X: PX, Y: PY),
14997 Qualifier: ::getCommonQualifier(Ctx, X: PX, Y: PY, /*IsSame=*/false), Cls);
14998 }
14999 case Type::CountAttributed: {
15000 const auto *DX = cast<CountAttributedType>(Val: X),
15001 *DY = cast<CountAttributedType>(Val: Y);
15002 if (DX->isCountInBytes() != DY->isCountInBytes())
15003 return QualType();
15004 if (DX->isOrNull() != DY->isOrNull())
15005 return QualType();
15006 Expr *CEX = DX->getCountExpr();
15007 Expr *CEY = DY->getCountExpr();
15008 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
15009 if (Ctx.hasSameExpr(X: CEX, Y: CEY))
15010 return Ctx.getCountAttributedType(WrappedTy: Ctx.getQualifiedType(split: Underlying), CountExpr: CEX,
15011 CountInBytes: DX->isCountInBytes(), OrNull: DX->isOrNull(),
15012 DependentDecls: CDX);
15013 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
15014 return QualType();
15015 // Two declarations with the same integer constant may still differ in their
15016 // expression pointers, so we need to evaluate them.
15017 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
15018 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
15019 if (VX != VY)
15020 return QualType();
15021 return Ctx.getCountAttributedType(WrappedTy: Ctx.getQualifiedType(split: Underlying), CountExpr: CEX,
15022 CountInBytes: DX->isCountInBytes(), OrNull: DX->isOrNull(),
15023 DependentDecls: CDX);
15024 }
15025
15026 case Type::LateParsedAttr:
15027 return QualType();
15028
15029 case Type::PredefinedSugar:
15030 assert(cast<PredefinedSugarType>(X)->getKind() !=
15031 cast<PredefinedSugarType>(Y)->getKind());
15032 return QualType();
15033 }
15034 llvm_unreachable("Unhandled Type Class");
15035}
15036
15037static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
15038 SmallVector<SplitQualType, 8> R;
15039 while (true) {
15040 QTotal.addConsistentQualifiers(qs: T.Quals);
15041 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
15042 if (NT == QualType(T.Ty, 0))
15043 break;
15044 R.push_back(Elt: T);
15045 T = NT.split();
15046 }
15047 return R;
15048}
15049
15050QualType ASTContext::getCommonSugaredType(QualType X, QualType Y,
15051 bool Unqualified) const {
15052 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
15053 if (X == Y)
15054 return X;
15055 if (!Unqualified) {
15056 if (X.isCanonical())
15057 return X;
15058 if (Y.isCanonical())
15059 return Y;
15060 }
15061
15062 SplitQualType SX = X.split(), SY = Y.split();
15063 Qualifiers QX, QY;
15064 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
15065 // until we reach their underlying "canonical nodes". Note these are not
15066 // necessarily canonical types, as they may still have sugared properties.
15067 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
15068 auto Xs = ::unwrapSugar(T&: SX, QTotal&: QX), Ys = ::unwrapSugar(T&: SY, QTotal&: QY);
15069
15070 // If this is an ArrayType, the element qualifiers are interchangeable with
15071 // the top level qualifiers.
15072 // * In case the canonical nodes are the same, the elements types are already
15073 // the same.
15074 // * Otherwise, the element types will be made the same, and any different
15075 // element qualifiers will be moved up to the top level qualifiers, per
15076 // 'getCommonArrayElementType'.
15077 // In both cases, this means there may be top level qualifiers which differ
15078 // between X and Y. If so, these differing qualifiers are redundant with the
15079 // element qualifiers, and can be removed without changing the canonical type.
15080 // The desired behaviour is the same as for the 'Unqualified' case here:
15081 // treat the redundant qualifiers as sugar, remove the ones which are not
15082 // common to both sides.
15083 bool KeepCommonQualifiers =
15084 Unqualified || isa<ArrayType, OverflowBehaviorType>(Val: SX.Ty);
15085
15086 if (SX.Ty != SY.Ty) {
15087 // The canonical nodes differ. Build a common canonical node out of the two,
15088 // unifying their sugar. This may recurse back here.
15089 SX.Ty =
15090 ::getCommonNonSugarTypeNode(Ctx: *this, X: SX.Ty, QX, Y: SY.Ty, QY).getTypePtr();
15091 } else {
15092 // The canonical nodes were identical: We may have desugared too much.
15093 // Add any common sugar back in.
15094 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
15095 QX -= SX.Quals;
15096 QY -= SY.Quals;
15097 SX = Xs.pop_back_val();
15098 SY = Ys.pop_back_val();
15099 }
15100 }
15101 if (KeepCommonQualifiers)
15102 QX = Qualifiers::removeCommonQualifiers(L&: QX, R&: QY);
15103 else
15104 assert(QX == QY);
15105
15106 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
15107 // related. Walk up these nodes, unifying them and adding the result.
15108 while (!Xs.empty() && !Ys.empty()) {
15109 auto Underlying = SplitQualType(
15110 SX.Ty, Qualifiers::removeCommonQualifiers(L&: SX.Quals, R&: SY.Quals));
15111 SX = Xs.pop_back_val();
15112 SY = Ys.pop_back_val();
15113 SX.Ty = ::getCommonSugarTypeNode(Ctx: *this, X: SX.Ty, Y: SY.Ty, Underlying)
15114 .getTypePtrOrNull();
15115 // Stop at the first pair which is unrelated.
15116 if (!SX.Ty) {
15117 SX.Ty = Underlying.Ty;
15118 break;
15119 }
15120 QX -= Underlying.Quals;
15121 };
15122
15123 // Add back the missing accumulated qualifiers, which were stripped off
15124 // with the sugar nodes we could not unify.
15125 QualType R = getQualifiedType(T: SX.Ty, Qs: QX);
15126 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
15127 return R;
15128}
15129
15130QualType ASTContext::getCorrespondingUnsaturatedType(QualType Ty) const {
15131 assert(Ty->isFixedPointType());
15132
15133 if (Ty->isUnsaturatedFixedPointType())
15134 return Ty;
15135
15136 switch (Ty->castAs<BuiltinType>()->getKind()) {
15137 default:
15138 llvm_unreachable("Not a saturated fixed point type!");
15139 case BuiltinType::SatShortAccum:
15140 return ShortAccumTy;
15141 case BuiltinType::SatAccum:
15142 return AccumTy;
15143 case BuiltinType::SatLongAccum:
15144 return LongAccumTy;
15145 case BuiltinType::SatUShortAccum:
15146 return UnsignedShortAccumTy;
15147 case BuiltinType::SatUAccum:
15148 return UnsignedAccumTy;
15149 case BuiltinType::SatULongAccum:
15150 return UnsignedLongAccumTy;
15151 case BuiltinType::SatShortFract:
15152 return ShortFractTy;
15153 case BuiltinType::SatFract:
15154 return FractTy;
15155 case BuiltinType::SatLongFract:
15156 return LongFractTy;
15157 case BuiltinType::SatUShortFract:
15158 return UnsignedShortFractTy;
15159 case BuiltinType::SatUFract:
15160 return UnsignedFractTy;
15161 case BuiltinType::SatULongFract:
15162 return UnsignedLongFractTy;
15163 }
15164}
15165
15166QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
15167 assert(Ty->isFixedPointType());
15168
15169 if (Ty->isSaturatedFixedPointType()) return Ty;
15170
15171 switch (Ty->castAs<BuiltinType>()->getKind()) {
15172 default:
15173 llvm_unreachable("Not a fixed point type!");
15174 case BuiltinType::ShortAccum:
15175 return SatShortAccumTy;
15176 case BuiltinType::Accum:
15177 return SatAccumTy;
15178 case BuiltinType::LongAccum:
15179 return SatLongAccumTy;
15180 case BuiltinType::UShortAccum:
15181 return SatUnsignedShortAccumTy;
15182 case BuiltinType::UAccum:
15183 return SatUnsignedAccumTy;
15184 case BuiltinType::ULongAccum:
15185 return SatUnsignedLongAccumTy;
15186 case BuiltinType::ShortFract:
15187 return SatShortFractTy;
15188 case BuiltinType::Fract:
15189 return SatFractTy;
15190 case BuiltinType::LongFract:
15191 return SatLongFractTy;
15192 case BuiltinType::UShortFract:
15193 return SatUnsignedShortFractTy;
15194 case BuiltinType::UFract:
15195 return SatUnsignedFractTy;
15196 case BuiltinType::ULongFract:
15197 return SatUnsignedLongFractTy;
15198 }
15199}
15200
15201LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
15202 if (LangOpts.OpenCL)
15203 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
15204
15205 if (LangOpts.CUDA)
15206 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
15207
15208 return getLangASFromTargetAS(TargetAS: AS);
15209}
15210
15211unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
15212 assert(Ty->isFixedPointType());
15213
15214 const TargetInfo &Target = getTargetInfo();
15215 switch (Ty->castAs<BuiltinType>()->getKind()) {
15216 default:
15217 llvm_unreachable("Not a fixed point type!");
15218 case BuiltinType::ShortAccum:
15219 case BuiltinType::SatShortAccum:
15220 return Target.getShortAccumScale();
15221 case BuiltinType::Accum:
15222 case BuiltinType::SatAccum:
15223 return Target.getAccumScale();
15224 case BuiltinType::LongAccum:
15225 case BuiltinType::SatLongAccum:
15226 return Target.getLongAccumScale();
15227 case BuiltinType::UShortAccum:
15228 case BuiltinType::SatUShortAccum:
15229 return Target.getUnsignedShortAccumScale();
15230 case BuiltinType::UAccum:
15231 case BuiltinType::SatUAccum:
15232 return Target.getUnsignedAccumScale();
15233 case BuiltinType::ULongAccum:
15234 case BuiltinType::SatULongAccum:
15235 return Target.getUnsignedLongAccumScale();
15236 case BuiltinType::ShortFract:
15237 case BuiltinType::SatShortFract:
15238 return Target.getShortFractScale();
15239 case BuiltinType::Fract:
15240 case BuiltinType::SatFract:
15241 return Target.getFractScale();
15242 case BuiltinType::LongFract:
15243 case BuiltinType::SatLongFract:
15244 return Target.getLongFractScale();
15245 case BuiltinType::UShortFract:
15246 case BuiltinType::SatUShortFract:
15247 return Target.getUnsignedShortFractScale();
15248 case BuiltinType::UFract:
15249 case BuiltinType::SatUFract:
15250 return Target.getUnsignedFractScale();
15251 case BuiltinType::ULongFract:
15252 case BuiltinType::SatULongFract:
15253 return Target.getUnsignedLongFractScale();
15254 }
15255}
15256
15257unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
15258 assert(Ty->isFixedPointType());
15259
15260 const TargetInfo &Target = getTargetInfo();
15261 switch (Ty->castAs<BuiltinType>()->getKind()) {
15262 default:
15263 llvm_unreachable("Not a fixed point type!");
15264 case BuiltinType::ShortAccum:
15265 case BuiltinType::SatShortAccum:
15266 return Target.getShortAccumIBits();
15267 case BuiltinType::Accum:
15268 case BuiltinType::SatAccum:
15269 return Target.getAccumIBits();
15270 case BuiltinType::LongAccum:
15271 case BuiltinType::SatLongAccum:
15272 return Target.getLongAccumIBits();
15273 case BuiltinType::UShortAccum:
15274 case BuiltinType::SatUShortAccum:
15275 return Target.getUnsignedShortAccumIBits();
15276 case BuiltinType::UAccum:
15277 case BuiltinType::SatUAccum:
15278 return Target.getUnsignedAccumIBits();
15279 case BuiltinType::ULongAccum:
15280 case BuiltinType::SatULongAccum:
15281 return Target.getUnsignedLongAccumIBits();
15282 case BuiltinType::ShortFract:
15283 case BuiltinType::SatShortFract:
15284 case BuiltinType::Fract:
15285 case BuiltinType::SatFract:
15286 case BuiltinType::LongFract:
15287 case BuiltinType::SatLongFract:
15288 case BuiltinType::UShortFract:
15289 case BuiltinType::SatUShortFract:
15290 case BuiltinType::UFract:
15291 case BuiltinType::SatUFract:
15292 case BuiltinType::ULongFract:
15293 case BuiltinType::SatULongFract:
15294 return 0;
15295 }
15296}
15297
15298llvm::FixedPointSemantics
15299ASTContext::getFixedPointSemantics(QualType Ty) const {
15300 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15301 "Can only get the fixed point semantics for a "
15302 "fixed point or integer type.");
15303 if (Ty->isIntegerType())
15304 return llvm::FixedPointSemantics::GetIntegerSemantics(
15305 Width: getIntWidth(T: Ty), IsSigned: Ty->isSignedIntegerType());
15306
15307 bool isSigned = Ty->isSignedFixedPointType();
15308 return llvm::FixedPointSemantics(
15309 static_cast<unsigned>(getTypeSize(T: Ty)), getFixedPointScale(Ty), isSigned,
15310 Ty->isSaturatedFixedPointType(),
15311 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15312}
15313
15314llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15315 assert(Ty->isFixedPointType());
15316 return llvm::APFixedPoint::getMax(Sema: getFixedPointSemantics(Ty));
15317}
15318
15319llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15320 assert(Ty->isFixedPointType());
15321 return llvm::APFixedPoint::getMin(Sema: getFixedPointSemantics(Ty));
15322}
15323
15324QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
15325 assert(Ty->isUnsignedFixedPointType() &&
15326 "Expected unsigned fixed point type");
15327
15328 switch (Ty->castAs<BuiltinType>()->getKind()) {
15329 case BuiltinType::UShortAccum:
15330 return ShortAccumTy;
15331 case BuiltinType::UAccum:
15332 return AccumTy;
15333 case BuiltinType::ULongAccum:
15334 return LongAccumTy;
15335 case BuiltinType::SatUShortAccum:
15336 return SatShortAccumTy;
15337 case BuiltinType::SatUAccum:
15338 return SatAccumTy;
15339 case BuiltinType::SatULongAccum:
15340 return SatLongAccumTy;
15341 case BuiltinType::UShortFract:
15342 return ShortFractTy;
15343 case BuiltinType::UFract:
15344 return FractTy;
15345 case BuiltinType::ULongFract:
15346 return LongFractTy;
15347 case BuiltinType::SatUShortFract:
15348 return SatShortFractTy;
15349 case BuiltinType::SatUFract:
15350 return SatFractTy;
15351 case BuiltinType::SatULongFract:
15352 return SatLongFractTy;
15353 default:
15354 llvm_unreachable("Unexpected unsigned fixed point type");
15355 }
15356}
15357
15358// Given a list of FMV features, return a concatenated list of the
15359// corresponding backend features (which may contain duplicates).
15360static std::vector<std::string> getFMVBackendFeaturesFor(
15361 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15362 std::vector<std::string> BackendFeats;
15363 llvm::AArch64::ExtensionSet FeatureBits;
15364 for (StringRef F : FMVFeatStrings)
15365 if (auto FMVExt = llvm::AArch64::parseFMVExtension(Extension: F))
15366 if (FMVExt->ID)
15367 FeatureBits.enable(E: *FMVExt->ID);
15368 FeatureBits.toLLVMFeatureList(Features&: BackendFeats);
15369 return BackendFeats;
15370}
15371
15372ParsedTargetAttr
15373ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15374 assert(TD != nullptr);
15375 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: TD->getFeaturesStr());
15376
15377 llvm::erase_if(C&: ParsedAttr.Features, P: [&](const std::string &Feat) {
15378 return !Target->isValidFeatureName(Feature: StringRef{Feat}.substr(Start: 1));
15379 });
15380 return ParsedAttr;
15381}
15382
15383void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15384 const FunctionDecl *FD) const {
15385 if (FD)
15386 getFunctionFeatureMap(FeatureMap, GD: GlobalDecl().getWithDecl(D: FD));
15387 else
15388 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(),
15389 CPU: Target->getTargetOpts().CPU,
15390 FeatureVec: Target->getTargetOpts().Features);
15391}
15392
15393// Fills in the supplied string map with the set of target features for the
15394// passed in function.
15395void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15396 GlobalDecl GD) const {
15397 StringRef TargetCPU = Target->getTargetOpts().CPU;
15398 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15399 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15400 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
15401
15402 // Make a copy of the features as passed on the command line into the
15403 // beginning of the additional features from the function to override.
15404 // AArch64 handles command line option features in parseTargetAttr().
15405 if (!Target->getTriple().isAArch64())
15406 ParsedAttr.Features.insert(
15407 position: ParsedAttr.Features.begin(),
15408 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15409 last: Target->getTargetOpts().FeaturesAsWritten.end());
15410
15411 if (ParsedAttr.CPU != "" && Target->isValidCPUName(Name: ParsedAttr.CPU))
15412 TargetCPU = ParsedAttr.CPU;
15413
15414 // Now populate the feature map, first with the TargetCPU which is either
15415 // the default or a new one from the target attribute string. Then we'll use
15416 // the passed in features (FeaturesAsWritten) along with the new ones from
15417 // the attribute.
15418 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU,
15419 FeatureVec: ParsedAttr.Features);
15420 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15421 llvm::SmallVector<StringRef, 32> FeaturesTmp;
15422 Target->getCPUSpecificCPUDispatchFeatures(
15423 Name: SD->getCPUName(Index: GD.getMultiVersionIndex())->getName(), Features&: FeaturesTmp);
15424 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15425 Features.insert(position: Features.begin(),
15426 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15427 last: Target->getTargetOpts().FeaturesAsWritten.end());
15428 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15429 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15430 if (Target->getTriple().isAArch64()) {
15431 llvm::SmallVector<StringRef, 8> Feats;
15432 TC->getFeatures(Out&: Feats, Index: GD.getMultiVersionIndex());
15433 std::vector<std::string> Features = getFMVBackendFeaturesFor(FMVFeatStrings: Feats);
15434 Features.insert(position: Features.begin(),
15435 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15436 last: Target->getTargetOpts().FeaturesAsWritten.end());
15437 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15438 } else if (Target->getTriple().isRISCV()) {
15439 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15440 std::vector<std::string> Features;
15441 if (VersionStr != "default") {
15442 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: VersionStr);
15443 Features.insert(position: Features.begin(), first: ParsedAttr.Features.begin(),
15444 last: ParsedAttr.Features.end());
15445 }
15446 Features.insert(position: Features.begin(),
15447 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15448 last: Target->getTargetOpts().FeaturesAsWritten.end());
15449 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15450 } else if (Target->getTriple().isOSAIX()) {
15451 std::vector<std::string> Features;
15452 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15453 if (VersionStr.starts_with(Prefix: "cpu="))
15454 TargetCPU = VersionStr.drop_front(N: sizeof("cpu=") - 1);
15455 else
15456 assert(VersionStr == "default");
15457 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15458 } else {
15459 std::vector<std::string> Features;
15460 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15461 if (VersionStr.starts_with(Prefix: "arch="))
15462 TargetCPU = VersionStr.drop_front(N: sizeof("arch=") - 1);
15463 else if (VersionStr != "default")
15464 Features.push_back(x: (StringRef{"+"} + VersionStr).str());
15465 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15466 }
15467 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15468 std::vector<std::string> Features;
15469 if (Target->getTriple().isRISCV()) {
15470 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: TV->getName());
15471 Features.insert(position: Features.begin(), first: ParsedAttr.Features.begin(),
15472 last: ParsedAttr.Features.end());
15473 } else {
15474 assert(Target->getTriple().isAArch64());
15475 llvm::SmallVector<StringRef, 8> Feats;
15476 TV->getFeatures(Out&: Feats);
15477 Features = getFMVBackendFeaturesFor(FMVFeatStrings: Feats);
15478 }
15479 Features.insert(position: Features.begin(),
15480 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15481 last: Target->getTargetOpts().FeaturesAsWritten.end());
15482 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15483 } else {
15484 FeatureMap = Target->getTargetOpts().FeatureMap;
15485 }
15486}
15487
15488static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context,
15489 CanQualType KernelNameType,
15490 const FunctionDecl *FD) {
15491 // Host and device compilation may use different ABIs and different ABIs
15492 // may allocate name mangling discriminators differently. A discriminator
15493 // override is used to ensure consistent discriminator allocation across
15494 // host and device compilation.
15495 auto DeviceDiscriminatorOverrider =
15496 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15497 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
15498 if (RD->isLambda())
15499 return RD->getDeviceLambdaManglingNumber();
15500 return std::nullopt;
15501 };
15502 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15503 Context, Diags&: Context.getDiagnostics(), Discriminator: DeviceDiscriminatorOverrider)};
15504
15505 // Construct a mangled name for the SYCL kernel caller offload entry point.
15506 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15507 // name the SYCL kernel caller offload entry point function. This mangling
15508 // does not suffice to clearly identify symbols that correspond to SYCL
15509 // kernel caller functions, nor is this mangling natural for targets that
15510 // use a non-Itanium ABI.
15511 std::string Buffer;
15512 Buffer.reserve(res_arg: 128);
15513 llvm::raw_string_ostream Out(Buffer);
15514 MC->mangleCanonicalTypeName(T: KernelNameType, Out);
15515 std::string KernelName = Out.str();
15516
15517 return {KernelNameType, FD, KernelName};
15518}
15519
15520void ASTContext::registerSYCLEntryPointFunction(FunctionDecl *FD) {
15521 // If the function declaration to register is invalid or dependent, the
15522 // registration attempt is ignored.
15523 if (FD->isInvalidDecl() || FD->isTemplated())
15524 return;
15525
15526 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15527 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15528
15529 // Be tolerant of multiple registration attempts so long as each attempt
15530 // is for the same entity. Callers are obligated to detect and diagnose
15531 // conflicting kernel names prior to calling this function.
15532 CanQualType KernelNameType = getCanonicalType(T: SKEPAttr->getKernelName());
15533 auto IT = SYCLKernels.find(Val: KernelNameType);
15534 assert((IT == SYCLKernels.end() ||
15535 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15536 "SYCL kernel name conflict");
15537 (void)IT;
15538 SYCLKernels.insert(KV: std::make_pair(
15539 x&: KernelNameType, y: BuildSYCLKernelInfo(Context&: *this, KernelNameType, FD)));
15540}
15541
15542const SYCLKernelInfo &ASTContext::getSYCLKernelInfo(QualType T) const {
15543 CanQualType KernelNameType = getCanonicalType(T);
15544 return SYCLKernels.at(Val: KernelNameType);
15545}
15546
15547const SYCLKernelInfo *ASTContext::findSYCLKernelInfo(QualType T) const {
15548 CanQualType KernelNameType = getCanonicalType(T);
15549 auto IT = SYCLKernels.find(Val: KernelNameType);
15550 if (IT != SYCLKernels.end())
15551 return &IT->second;
15552 return nullptr;
15553}
15554
15555OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
15556 OMPTraitInfoVector.emplace_back(Args: new OMPTraitInfo());
15557 return *OMPTraitInfoVector.back();
15558}
15559
15560const StreamingDiagnostic &clang::
15561operator<<(const StreamingDiagnostic &DB,
15562 const ASTContext::SectionInfo &Section) {
15563 if (Section.Decl)
15564 return DB << Section.Decl;
15565 return DB << "a prior #pragma section";
15566}
15567
15568bool ASTContext::mayExternalize(const Decl *D) const {
15569 bool IsInternalVar =
15570 isa<VarDecl>(Val: D) &&
15571 basicGVALinkageForVariable(Context: *this, VD: cast<VarDecl>(Val: D)) == GVA_Internal;
15572 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15573 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15574 (D->hasAttr<CUDAConstantAttr>() &&
15575 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15576 // CUDA/HIP: managed variables need to be externalized since it is
15577 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15578 // anonymous name space needs to be externalized to avoid duplicate symbols.
15579 return (IsInternalVar &&
15580 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15581 (D->hasAttr<CUDAGlobalAttr>() &&
15582 basicGVALinkageForFunction(Context: *this, FD: cast<FunctionDecl>(Val: D)) ==
15583 GVA_Internal);
15584}
15585
15586bool ASTContext::shouldExternalize(const Decl *D) const {
15587 return mayExternalize(D) &&
15588 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15589 CUDADeviceVarODRUsedByHost.count(key: cast<VarDecl>(Val: D)));
15590}
15591
15592StringRef ASTContext::getCUIDHash() const {
15593 if (!CUIDHash.empty())
15594 return CUIDHash;
15595 if (LangOpts.CUID.empty())
15596 return StringRef();
15597 CUIDHash = llvm::utohexstr(X: llvm::MD5Hash(Str: LangOpts.CUID), /*LowerCase=*/true);
15598 return CUIDHash;
15599}
15600
15601const CXXRecordDecl *
15602ASTContext::baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const {
15603 assert(ThisClass);
15604 assert(ThisClass->isPolymorphic());
15605 const CXXRecordDecl *PrimaryBase = ThisClass;
15606 while (1) {
15607 assert(PrimaryBase);
15608 assert(PrimaryBase->isPolymorphic());
15609 auto &Layout = getASTRecordLayout(D: PrimaryBase);
15610 auto Base = Layout.getPrimaryBase();
15611 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15612 break;
15613 PrimaryBase = Base;
15614 }
15615 return PrimaryBase;
15616}
15617
15618bool ASTContext::useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl,
15619 StringRef MangledName) {
15620 auto *Method = cast<CXXMethodDecl>(Val: VirtualMethodDecl.getDecl());
15621 assert(Method->isVirtual());
15622 bool DefaultIncludesPointerAuth =
15623 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15624
15625 if (!DefaultIncludesPointerAuth)
15626 return true;
15627
15628 auto Existing = ThunksToBeAbbreviated.find(Val: VirtualMethodDecl);
15629 if (Existing != ThunksToBeAbbreviated.end())
15630 return Existing->second.contains(key: MangledName.str());
15631
15632 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15633 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15634 auto VtableContext = getVTableContext();
15635 if (const auto *ThunkInfos = VtableContext->getThunkInfo(GD: VirtualMethodDecl)) {
15636 auto *Destructor = dyn_cast<CXXDestructorDecl>(Val: Method);
15637 for (const auto &Thunk : *ThunkInfos) {
15638 SmallString<256> ElidedName;
15639 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15640 if (Destructor)
15641 Mangler->mangleCXXDtorThunk(DD: Destructor, Type: VirtualMethodDecl.getDtorType(),
15642 Thunk, /* elideOverrideInfo */ ElideOverrideInfo: true,
15643 ElidedNameStream);
15644 else
15645 Mangler->mangleThunk(MD: Method, Thunk, /* elideOverrideInfo */ ElideOverrideInfo: true,
15646 ElidedNameStream);
15647 SmallString<256> MangledName;
15648 llvm::raw_svector_ostream mangledNameStream(MangledName);
15649 if (Destructor)
15650 Mangler->mangleCXXDtorThunk(DD: Destructor, Type: VirtualMethodDecl.getDtorType(),
15651 Thunk, /* elideOverrideInfo */ ElideOverrideInfo: false,
15652 mangledNameStream);
15653 else
15654 Mangler->mangleThunk(MD: Method, Thunk, /* elideOverrideInfo */ ElideOverrideInfo: false,
15655 mangledNameStream);
15656
15657 Thunks[ElidedName].push_back(Elt: std::string(MangledName));
15658 }
15659 }
15660 llvm::StringSet<> SimplifiedThunkNames;
15661 for (auto &ThunkList : Thunks) {
15662 llvm::sort(C&: ThunkList.second);
15663 SimplifiedThunkNames.insert(key: ThunkList.second[0]);
15664 }
15665 bool Result = SimplifiedThunkNames.contains(key: MangledName);
15666 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15667 return Result;
15668}
15669
15670bool ASTContext::arePFPFieldsTriviallyCopyable(const RecordDecl *RD) const {
15671 // Check for trivially-destructible here because non-trivially-destructible
15672 // types will always cause the type and any types derived from it to be
15673 // considered non-trivially-copyable. The same cannot be said for
15674 // trivially-copyable because deleting special members of a type derived from
15675 // a non-trivially-copyable type can cause the derived type to be considered
15676 // trivially copyable.
15677 if (getLangOpts().PointerFieldProtectionTagged)
15678 return !isa<CXXRecordDecl>(Val: RD) ||
15679 cast<CXXRecordDecl>(Val: RD)->hasTrivialDestructor();
15680 return true;
15681}
15682
15683static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15684 std::vector<PFPField> &Fields, bool IncludeVBases) {
15685 if (auto *AT = Ctx.getAsConstantArrayType(T: Ty)) {
15686 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15687 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(D: ElemDecl);
15688 for (unsigned i = 0; i != AT->getSize(); ++i)
15689 findPFPFields(Ctx, Ty: AT->getElementType(), Offset: Offset + i * ElemRL.getSize(),
15690 Fields, IncludeVBases: true);
15691 }
15692 }
15693 auto *Decl = Ty->getAsCXXRecordDecl();
15694 // isPFPType() is inherited from bases and members (including via arrays), so
15695 // we can early exit if it is false. Unions are excluded per the API
15696 // documentation.
15697 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15698 return;
15699 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(D: Decl);
15700 for (FieldDecl *Field : Decl->fields()) {
15701 CharUnits FieldOffset =
15702 Offset +
15703 Ctx.toCharUnitsFromBits(BitSize: RL.getFieldOffset(FieldNo: Field->getFieldIndex()));
15704 if (Ctx.isPFPField(Field))
15705 Fields.push_back(x: {.Offset: FieldOffset, .Field: Field});
15706 findPFPFields(Ctx, Ty: Field->getType(), Offset: FieldOffset, Fields,
15707 /*IncludeVBases=*/true);
15708 }
15709 // Pass false for IncludeVBases below because vbases are only included in
15710 // layout for top-level types, i.e. not bases or vbases.
15711 for (CXXBaseSpecifier &Base : Decl->bases()) {
15712 if (Base.isVirtual())
15713 continue;
15714 CharUnits BaseOffset =
15715 Offset + RL.getBaseClassOffset(Base: Base.getType()->getAsCXXRecordDecl());
15716 findPFPFields(Ctx, Ty: Base.getType(), Offset: BaseOffset, Fields,
15717 /*IncludeVBases=*/false);
15718 }
15719 if (IncludeVBases) {
15720 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15721 CharUnits BaseOffset =
15722 Offset + RL.getVBaseClassOffset(VBase: Base.getType()->getAsCXXRecordDecl());
15723 findPFPFields(Ctx, Ty: Base.getType(), Offset: BaseOffset, Fields,
15724 /*IncludeVBases=*/false);
15725 }
15726 }
15727}
15728
15729std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15730 std::vector<PFPField> PFPFields;
15731 ::findPFPFields(Ctx: *this, Ty, Offset: CharUnits::Zero(), Fields&: PFPFields, IncludeVBases: true);
15732 return PFPFields;
15733}
15734
15735bool ASTContext::hasPFPFields(QualType Ty) const {
15736 return !findPFPFields(Ty).empty();
15737}
15738
15739bool ASTContext::isPFPField(const FieldDecl *FD) const {
15740 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: FD->getParent()))
15741 return RD->isPFPType() && FD->getType()->isPointerType() &&
15742 !FD->hasAttr<NoFieldProtectionAttr>();
15743 return false;
15744}
15745
15746void ASTContext::recordMemberDataPointerEvaluation(const ValueDecl *VD) {
15747 auto *FD = dyn_cast<FieldDecl>(Val: VD);
15748 if (!FD)
15749 FD = cast<FieldDecl>(Val: cast<IndirectFieldDecl>(Val: VD)->chain().back());
15750 if (isPFPField(FD))
15751 PFPFieldsWithEvaluatedOffset.insert(X: FD);
15752}
15753
15754void ASTContext::recordOffsetOfEvaluation(const OffsetOfExpr *E) {
15755 if (E->getNumComponents() == 0)
15756 return;
15757 OffsetOfNode Comp = E->getComponent(Idx: E->getNumComponents() - 1);
15758 if (Comp.getKind() != OffsetOfNode::Field)
15759 return;
15760 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15761 PFPFieldsWithEvaluatedOffset.insert(X: FD);
15762}
15763
15764namespace {
15765// PaddingCalculator is a utility class that calculates the padding bits in a
15766// c/c++ type. It traverses the type recursively, collecting occupied
15767// bit intervals, and then computes the padding intervals.
15768// If a byte only contains some padding bits, it gets intervals for only those
15769// bits. This is the case for bit-fields.
15770struct PaddingCalculator {
15771 PaddingCalculator(const ASTContext &Ctx) : Ctx(Ctx) {}
15772
15773 void run(QualType Ty) {
15774 OccuppiedIntervals.clear();
15775 Stack.clear();
15776
15777 TySizeInBits = Ctx.getTypeSize(T: Ty);
15778
15779 Stack.push_back(Elt: Data{.StartBitOffset: 0, .Ty: Ty.getCanonicalType(), .VisitVirtualBase: true});
15780 while (!Stack.empty()) {
15781 Data Current = Stack.back();
15782 Stack.pop_back();
15783 Visit(D: Current);
15784 }
15785 MergeOccuppiedIntervals();
15786 }
15787
15788 llvm::SmallVector<ASTContext::BitInterval> GetPaddingIntervals() {
15789 llvm::SmallVector<ASTContext::BitInterval> Results;
15790 if (OccuppiedIntervals.size() == 1 &&
15791 OccuppiedIntervals.front().First == 0 &&
15792 OccuppiedIntervals.front().Last == TySizeInBits) {
15793 return Results;
15794 }
15795 Results.reserve(N: OccuppiedIntervals.size() + 1);
15796 uint64_t CurrentPos = 0;
15797 for (const ASTContext::BitInterval &OccupiedInterval : OccuppiedIntervals) {
15798 if (OccupiedInterval.First > CurrentPos) {
15799 Results.push_back(
15800 Elt: ASTContext::BitInterval{.First: CurrentPos, .Last: OccupiedInterval.First});
15801 }
15802 CurrentPos = OccupiedInterval.Last;
15803 }
15804 if (TySizeInBits > CurrentPos) {
15805 Results.push_back(Elt: ASTContext::BitInterval{.First: CurrentPos, .Last: TySizeInBits});
15806 }
15807 return Results;
15808 }
15809
15810private:
15811 struct Data {
15812 uint64_t StartBitOffset;
15813 QualType Ty;
15814 bool VisitVirtualBase;
15815 };
15816
15817 // Return the number of non padding bits of a scalar type.
15818 //
15819 // The property that we specifically care about here is whether the scalar
15820 // type has padding bits, i.e. are there bits in the type which are not
15821 // specified by the ABI.
15822 //
15823 // We currently don't care about this anywhere else in clang: layout cares
15824 // about the ABI size, calling convention code cares about specific types,
15825 // but nothing cares about padding specifically. And it's not something we can
15826 // easily query from LLVM due to the type system mismatches.
15827 // DL.getTypeSizeInBits(convertTypeForLoadStore(T)) is probably close, but the
15828 // DataLayout methods aren't really designed for this usage.
15829 //
15830 // Therefore, it is better to explicitly list all the scalar types
15831 // containing padding bits that we know of, namely, _BitInt(N) and x87 long
15832 // double.
15833 //
15834 // FIXME: There are likely other scalar types we need to think about here, as
15835 // brought up in review for #215823:
15836 // - bool
15837 // - enums(both with/without fixed underlying type)
15838 // - nullptr_t
15839 // - more?
15840 uint64_t getScalarOccupiedSizeInBits(QualType Ty) const {
15841 if (const auto *BIT = Ty->getAs<BitIntType>())
15842 return BIT->getNumBits();
15843
15844 if (const auto *BT = Ty->getAs<BuiltinType>()) {
15845 if (BT->getKind() == BuiltinType::LongDouble &&
15846 &Ctx.getTargetInfo().getLongDoubleFormat() ==
15847 &llvm::APFloat::x87DoubleExtended())
15848 return llvm::APFloat::getSizeInBits(
15849 Sem: Ctx.getTargetInfo().getLongDoubleFormat());
15850 }
15851
15852 return Ctx.getTypeSize(T: Ty);
15853 }
15854
15855 void Visit(const Data &D) {
15856 if (auto *AT = dyn_cast<ConstantArrayType>(Val: D.Ty)) {
15857 VisitArray(AT, StartBitOffset: D.StartBitOffset);
15858 return;
15859 }
15860
15861 if (auto *Record = D.Ty->getAsRecordDecl()) {
15862 VisitStruct(R: Record, StartBitOffset: D.StartBitOffset, VisitVirtualBase: D.VisitVirtualBase);
15863 return;
15864 }
15865
15866 if (D.Ty->isAtomicType()) {
15867 auto Unwrapped = D;
15868 Unwrapped.Ty = D.Ty.getAtomicUnqualifiedType().getCanonicalType();
15869 Stack.push_back(Elt: Unwrapped);
15870 return;
15871 }
15872
15873 if (const auto *Complex = D.Ty->getAs<ComplexType>()) {
15874 VisitComplex(CT: Complex, StartBitOffset: D.StartBitOffset);
15875 return;
15876 }
15877
15878 if (const auto *VT = D.Ty->getAs<clang::VectorType>()) {
15879 VisitVector(VT, StartBitOffset: D.StartBitOffset);
15880 return;
15881 }
15882
15883 uint64_t SizeBit = getScalarOccupiedSizeInBits(Ty: D.Ty);
15884 OccuppiedIntervals.push_back(
15885 Elt: ASTContext::BitInterval{.First: D.StartBitOffset, .Last: D.StartBitOffset + SizeBit});
15886 }
15887
15888 void VisitArray(const ConstantArrayType *AT, uint64_t StartBitOffset) {
15889 for (uint64_t ArrIndex = 0; ArrIndex < AT->getSize().getLimitedValue();
15890 ++ArrIndex) {
15891
15892 QualType ElementQualType = AT->getElementType();
15893 auto ElementSize = Ctx.getTypeSizeInChars(T: ElementQualType);
15894 auto ElementAlign = Ctx.getTypeAlignInChars(T: ElementQualType);
15895 auto Offset = ElementSize.alignTo(Align: ElementAlign);
15896
15897 Stack.push_back(Elt: Data{
15898 .StartBitOffset: StartBitOffset + ArrIndex * Offset.getQuantity() * Ctx.getCharWidth(),
15899 .Ty: ElementQualType.getCanonicalType(), /*VisitVirtualBase*/ true});
15900 }
15901 }
15902
15903 void VisitStruct(const RecordDecl *R, uint64_t StartBitOffset,
15904 bool VisitVirtualBase) {
15905 const ASTRecordLayout &ASTLayout = Ctx.getASTRecordLayout(D: R);
15906 auto *CXXRecord = dyn_cast<CXXRecordDecl>(Val: R);
15907
15908 unsigned PointerSizeInBits = Ctx.getTypeSize(T: Ctx.NullPtrTy);
15909
15910 if (CXXRecord) {
15911 if (ASTLayout.hasOwnVFPtr()) {
15912 OccuppiedIntervals.push_back(Elt: ASTContext::BitInterval{
15913 .First: StartBitOffset, .Last: StartBitOffset + PointerSizeInBits});
15914 }
15915
15916 if (ASTLayout.hasOwnVBPtr()) {
15917 auto Offset = ASTLayout.getVBPtrOffset().getQuantity();
15918 auto StartVBPtr = StartBitOffset + Offset * Ctx.getCharWidth();
15919 OccuppiedIntervals.push_back(Elt: ASTContext::BitInterval{
15920 .First: StartVBPtr, .Last: StartVBPtr + PointerSizeInBits});
15921 }
15922
15923 const auto VisitBase = [&ASTLayout, StartBitOffset, this](
15924 const CXXBaseSpecifier &Base, auto GetOffset) {
15925 auto *BaseRecord = Base.getType()->getAsCXXRecordDecl();
15926 if (!BaseRecord) {
15927 return;
15928 }
15929 auto BaseOffset =
15930 std::invoke(GetOffset, ASTLayout, BaseRecord).getQuantity();
15931
15932 Stack.push_back(
15933 Elt: Data{StartBitOffset + BaseOffset * Ctx.getCharWidth(),
15934 Base.getType().getCanonicalType(), /*VisitVirtualBase*/
15935 false});
15936 };
15937
15938 for (auto Base : CXXRecord->bases()) {
15939 if (!Base.isVirtual()) {
15940 VisitBase(Base, &ASTRecordLayout::getBaseClassOffset);
15941 }
15942 }
15943
15944 if (VisitVirtualBase) {
15945 for (auto VBase : CXXRecord->vbases()) {
15946 VisitBase(VBase, &ASTRecordLayout::getVBaseClassOffset);
15947 }
15948 }
15949 }
15950
15951 for (auto *Field : R->fields()) {
15952 // Treat unnamed bitfields as padding.
15953 if (Field->isUnnamedBitField())
15954 continue;
15955
15956 auto FieldOffset = ASTLayout.getFieldOffset(FieldNo: Field->getFieldIndex());
15957 if (Field->isBitField()) {
15958 OccuppiedIntervals.push_back(Elt: ASTContext::BitInterval{
15959 .First: StartBitOffset + FieldOffset,
15960 .Last: StartBitOffset + FieldOffset + Field->getBitWidthValue()});
15961 } else {
15962 Stack.push_back(Elt: Data{.StartBitOffset: StartBitOffset + FieldOffset,
15963 .Ty: Field->getType().getCanonicalType(),
15964 /*VisitVirtualBase*/ true});
15965 }
15966 }
15967 }
15968
15969 void VisitComplex(const ComplexType *CT, uint64_t StartBitOffset) {
15970 QualType ElementQualType = CT->getElementType().getCanonicalType();
15971 auto ElementSize = Ctx.getTypeSizeInChars(T: ElementQualType);
15972 auto ElementAlign = Ctx.getTypeAlignInChars(T: ElementQualType);
15973 auto ImgOffset = ElementSize.alignTo(Align: ElementAlign);
15974
15975 Stack.push_back(
15976 Elt: Data{.StartBitOffset: StartBitOffset, .Ty: ElementQualType, /*VisitVirtualBase*/ true});
15977 Stack.push_back(
15978 Elt: Data{.StartBitOffset: StartBitOffset + ImgOffset.getQuantity() * Ctx.getCharWidth(),
15979 .Ty: ElementQualType, /*VisitVirtualBase*/ true});
15980 }
15981
15982 void VisitVector(const clang::VectorType *VT, uint64_t StartBitOffset) {
15983 uint64_t SizeBit = [&]() -> uint64_t {
15984 if (VT->isPackedVectorBoolType(ctx: Ctx))
15985 return VT->getNumElements();
15986 return getScalarOccupiedSizeInBits(Ty: VT->getElementType()) *
15987 VT->getNumElements();
15988 }();
15989 OccuppiedIntervals.push_back(
15990 Elt: ASTContext::BitInterval{.First: StartBitOffset, .Last: StartBitOffset + SizeBit});
15991 }
15992
15993 void MergeOccuppiedIntervals() {
15994 std::sort(first: OccuppiedIntervals.begin(), last: OccuppiedIntervals.end(),
15995 comp: [](const ASTContext::BitInterval &lhs,
15996 const ASTContext::BitInterval &rhs) {
15997 return std::tie(args: lhs.First, args: lhs.Last) <
15998 std::tie(args: rhs.First, args: rhs.Last);
15999 });
16000
16001 llvm::SmallVector<ASTContext::BitInterval> Merged;
16002 Merged.reserve(N: OccuppiedIntervals.size());
16003
16004 for (const ASTContext::BitInterval &NextInterval : OccuppiedIntervals) {
16005 if (Merged.empty()) {
16006 Merged.push_back(Elt: NextInterval);
16007 continue;
16008 }
16009 auto &LastInterval = Merged.back();
16010
16011 if (NextInterval.First > LastInterval.Last) {
16012 Merged.push_back(Elt: NextInterval);
16013 } else {
16014 LastInterval.Last = std::max(a: LastInterval.Last, b: NextInterval.Last);
16015 }
16016 }
16017
16018 OccuppiedIntervals = Merged;
16019 }
16020
16021 const ASTContext &Ctx;
16022 // unsigned PointerSizeInBits;
16023 uint64_t TySizeInBits = 0;
16024 llvm::SmallVector<Data> Stack;
16025 llvm::SmallVector<ASTContext::BitInterval> OccuppiedIntervals;
16026};
16027} // namespace
16028
16029llvm::ArrayRef<ASTContext::BitInterval>
16030ASTContext::getPaddingIntervals(QualType Ty) const {
16031 Ty = Ty.getCanonicalType();
16032 auto cached = PaddingIntervalCache.find(Val: Ty);
16033 if (cached != PaddingIntervalCache.end())
16034 return cached->second;
16035
16036 PaddingCalculator pc{*this};
16037 pc.run(Ty);
16038
16039 auto [itr, res] =
16040 PaddingIntervalCache.insert_or_assign(Key: Ty, Val: pc.GetPaddingIntervals());
16041 assert(res && "Failed to insert?");
16042
16043 return itr->second;
16044}
16045