Bug Summary

File:clang/lib/AST/ASTContext.cpp
Warning:line 8721, column 20
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ASTContext.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp
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 "CXXABI.h"
15#include "Interp/Context.h"
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/ASTTypeTraits.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/AttrIterator.h"
22#include "clang/AST/CharUnits.h"
23#include "clang/AST/Comment.h"
24#include "clang/AST/Decl.h"
25#include "clang/AST/DeclBase.h"
26#include "clang/AST/DeclCXX.h"
27#include "clang/AST/DeclContextInternals.h"
28#include "clang/AST/DeclObjC.h"
29#include "clang/AST/DeclOpenMP.h"
30#include "clang/AST/DeclTemplate.h"
31#include "clang/AST/DeclarationName.h"
32#include "clang/AST/Expr.h"
33#include "clang/AST/ExprCXX.h"
34#include "clang/AST/ExternalASTSource.h"
35#include "clang/AST/Mangle.h"
36#include "clang/AST/MangleNumberingContext.h"
37#include "clang/AST/NestedNameSpecifier.h"
38#include "clang/AST/RawCommentList.h"
39#include "clang/AST/RecordLayout.h"
40#include "clang/AST/RecursiveASTVisitor.h"
41#include "clang/AST/Stmt.h"
42#include "clang/AST/TemplateBase.h"
43#include "clang/AST/TemplateName.h"
44#include "clang/AST/Type.h"
45#include "clang/AST/TypeLoc.h"
46#include "clang/AST/UnresolvedSet.h"
47#include "clang/AST/VTableBuilder.h"
48#include "clang/Basic/AddressSpaces.h"
49#include "clang/Basic/Builtins.h"
50#include "clang/Basic/CommentOptions.h"
51#include "clang/Basic/ExceptionSpecificationType.h"
52#include "clang/Basic/FixedPoint.h"
53#include "clang/Basic/IdentifierTable.h"
54#include "clang/Basic/LLVM.h"
55#include "clang/Basic/LangOptions.h"
56#include "clang/Basic/Linkage.h"
57#include "clang/Basic/ObjCRuntime.h"
58#include "clang/Basic/SanitizerBlacklist.h"
59#include "clang/Basic/SourceLocation.h"
60#include "clang/Basic/SourceManager.h"
61#include "clang/Basic/Specifiers.h"
62#include "clang/Basic/TargetCXXABI.h"
63#include "clang/Basic/TargetInfo.h"
64#include "clang/Basic/XRayLists.h"
65#include "llvm/ADT/APInt.h"
66#include "llvm/ADT/APSInt.h"
67#include "llvm/ADT/ArrayRef.h"
68#include "llvm/ADT/DenseMap.h"
69#include "llvm/ADT/DenseSet.h"
70#include "llvm/ADT/FoldingSet.h"
71#include "llvm/ADT/None.h"
72#include "llvm/ADT/Optional.h"
73#include "llvm/ADT/PointerUnion.h"
74#include "llvm/ADT/STLExtras.h"
75#include "llvm/ADT/SmallPtrSet.h"
76#include "llvm/ADT/SmallVector.h"
77#include "llvm/ADT/StringExtras.h"
78#include "llvm/ADT/StringRef.h"
79#include "llvm/ADT/Triple.h"
80#include "llvm/Support/Capacity.h"
81#include "llvm/Support/Casting.h"
82#include "llvm/Support/Compiler.h"
83#include "llvm/Support/ErrorHandling.h"
84#include "llvm/Support/MathExtras.h"
85#include "llvm/Support/raw_ostream.h"
86#include <algorithm>
87#include <cassert>
88#include <cstddef>
89#include <cstdint>
90#include <cstdlib>
91#include <map>
92#include <memory>
93#include <string>
94#include <tuple>
95#include <utility>
96
97using namespace clang;
98
99enum FloatingRank {
100 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
101};
102const Expr *ASTContext::traverseIgnored(const Expr *E) const {
103 return traverseIgnored(const_cast<Expr *>(E));
104}
105
106Expr *ASTContext::traverseIgnored(Expr *E) const {
107 if (!E)
108 return nullptr;
109
110 switch (Traversal) {
111 case ast_type_traits::TK_AsIs:
112 return E;
113 case ast_type_traits::TK_IgnoreImplicitCastsAndParentheses:
114 return E->IgnoreParenImpCasts();
115 case ast_type_traits::TK_IgnoreUnlessSpelledInSource:
116 return E->IgnoreUnlessSpelledInSource();
117 }
118 llvm_unreachable("Invalid Traversal type!")::llvm::llvm_unreachable_internal("Invalid Traversal type!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 118)
;
119}
120
121ast_type_traits::DynTypedNode
122ASTContext::traverseIgnored(const ast_type_traits::DynTypedNode &N) const {
123 if (const auto *E = N.get<Expr>()) {
124 return ast_type_traits::DynTypedNode::create(*traverseIgnored(E));
125 }
126 return N;
127}
128
129/// \returns location that is relevant when searching for Doc comments related
130/// to \p D.
131static SourceLocation getDeclLocForCommentSearch(const Decl *D,
132 SourceManager &SourceMgr) {
133 assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 133, __PRETTY_FUNCTION__))
;
134
135 // User can not attach documentation to implicit declarations.
136 if (D->isImplicit())
137 return {};
138
139 // User can not attach documentation to implicit instantiations.
140 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
141 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
142 return {};
143 }
144
145 if (const auto *VD = dyn_cast<VarDecl>(D)) {
146 if (VD->isStaticDataMember() &&
147 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
148 return {};
149 }
150
151 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
152 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
153 return {};
154 }
155
156 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
157 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
158 if (TSK == TSK_ImplicitInstantiation ||
159 TSK == TSK_Undeclared)
160 return {};
161 }
162
163 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
164 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
165 return {};
166 }
167 if (const auto *TD = dyn_cast<TagDecl>(D)) {
168 // When tag declaration (but not definition!) is part of the
169 // decl-specifier-seq of some other declaration, it doesn't get comment
170 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
171 return {};
172 }
173 // TODO: handle comments for function parameters properly.
174 if (isa<ParmVarDecl>(D))
175 return {};
176
177 // TODO: we could look up template parameter documentation in the template
178 // documentation.
179 if (isa<TemplateTypeParmDecl>(D) ||
180 isa<NonTypeTemplateParmDecl>(D) ||
181 isa<TemplateTemplateParmDecl>(D))
182 return {};
183
184 // Find declaration location.
185 // For Objective-C declarations we generally don't expect to have multiple
186 // declarators, thus use declaration starting location as the "declaration
187 // location".
188 // For all other declarations multiple declarators are used quite frequently,
189 // so we use the location of the identifier as the "declaration location".
190 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
191 isa<ObjCPropertyDecl>(D) ||
192 isa<RedeclarableTemplateDecl>(D) ||
193 isa<ClassTemplateSpecializationDecl>(D) ||
194 // Allow association with Y across {} in `typedef struct X {} Y`.
195 isa<TypedefDecl>(D))
196 return D->getBeginLoc();
197 else {
198 const SourceLocation DeclLoc = D->getLocation();
199 if (DeclLoc.isMacroID()) {
200 if (isa<TypedefDecl>(D)) {
201 // If location of the typedef name is in a macro, it is because being
202 // declared via a macro. Try using declaration's starting location as
203 // the "declaration location".
204 return D->getBeginLoc();
205 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
206 // If location of the tag decl is inside a macro, but the spelling of
207 // the tag name comes from a macro argument, it looks like a special
208 // macro like NS_ENUM is being used to define the tag decl. In that
209 // case, adjust the source location to the expansion loc so that we can
210 // attach the comment to the tag decl.
211 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
212 TD->isCompleteDefinition())
213 return SourceMgr.getExpansionLoc(DeclLoc);
214 }
215 }
216 return DeclLoc;
217 }
218
219 return {};
220}
221
222RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
223 const Decl *D, const SourceLocation RepresentativeLocForDecl,
224 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
225 // If the declaration doesn't map directly to a location in a file, we
226 // can't find the comment.
227 if (RepresentativeLocForDecl.isInvalid() ||
228 !RepresentativeLocForDecl.isFileID())
229 return nullptr;
230
231 // If there are no comments anywhere, we won't find anything.
232 if (CommentsInTheFile.empty())
233 return nullptr;
234
235 // Decompose the location for the declaration and find the beginning of the
236 // file buffer.
237 const std::pair<FileID, unsigned> DeclLocDecomp =
238 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
239
240 // Slow path.
241 auto OffsetCommentBehindDecl =
242 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
243
244 // First check whether we have a trailing comment.
245 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
246 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
247 if ((CommentBehindDecl->isDocumentation() ||
248 LangOpts.CommentOpts.ParseAllComments) &&
249 CommentBehindDecl->isTrailingComment() &&
250 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
251 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
252
253 // Check that Doxygen trailing comment comes after the declaration, starts
254 // on the same line and in the same file as the declaration.
255 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
256 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
257 OffsetCommentBehindDecl->first)) {
258 return CommentBehindDecl;
259 }
260 }
261 }
262
263 // The comment just after the declaration was not a trailing comment.
264 // Let's look at the previous comment.
265 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
266 return nullptr;
267
268 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
269 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
270
271 // Check that we actually have a non-member Doxygen comment.
272 if (!(CommentBeforeDecl->isDocumentation() ||
273 LangOpts.CommentOpts.ParseAllComments) ||
274 CommentBeforeDecl->isTrailingComment())
275 return nullptr;
276
277 // Decompose the end of the comment.
278 const unsigned CommentEndOffset =
279 Comments.getCommentEndOffset(CommentBeforeDecl);
280
281 // Get the corresponding buffer.
282 bool Invalid = false;
283 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
284 &Invalid).data();
285 if (Invalid)
286 return nullptr;
287
288 // Extract text between the comment and declaration.
289 StringRef Text(Buffer + CommentEndOffset,
290 DeclLocDecomp.second - CommentEndOffset);
291
292 // There should be no other declarations or preprocessor directives between
293 // comment and declaration.
294 if (Text.find_first_of(";{}#@") != StringRef::npos)
295 return nullptr;
296
297 return CommentBeforeDecl;
298}
299
300RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
301 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
302
303 // If the declaration doesn't map directly to a location in a file, we
304 // can't find the comment.
305 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
306 return nullptr;
307
308 if (ExternalSource && !CommentsLoaded) {
309 ExternalSource->ReadComments();
310 CommentsLoaded = true;
311 }
312
313 if (Comments.empty())
314 return nullptr;
315
316 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
317 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
318 if (!CommentsInThisFile || CommentsInThisFile->empty())
319 return nullptr;
320
321 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
322}
323
324/// If we have a 'templated' declaration for a template, adjust 'D' to
325/// refer to the actual template.
326/// If we have an implicit instantiation, adjust 'D' to refer to template.
327static const Decl &adjustDeclToTemplate(const Decl &D) {
328 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
329 // Is this function declaration part of a function template?
330 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
331 return *FTD;
332
333 // Nothing to do if function is not an implicit instantiation.
334 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
335 return D;
336
337 // Function is an implicit instantiation of a function template?
338 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
339 return *FTD;
340
341 // Function is instantiated from a member definition of a class template?
342 if (const FunctionDecl *MemberDecl =
343 FD->getInstantiatedFromMemberFunction())
344 return *MemberDecl;
345
346 return D;
347 }
348 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
349 // Static data member is instantiated from a member definition of a class
350 // template?
351 if (VD->isStaticDataMember())
352 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
353 return *MemberDecl;
354
355 return D;
356 }
357 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
358 // Is this class declaration part of a class template?
359 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
360 return *CTD;
361
362 // Class is an implicit instantiation of a class template or partial
363 // specialization?
364 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
365 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
366 return D;
367 llvm::PointerUnion<ClassTemplateDecl *,
368 ClassTemplatePartialSpecializationDecl *>
369 PU = CTSD->getSpecializedTemplateOrPartial();
370 return PU.is<ClassTemplateDecl *>()
371 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
372 : *static_cast<const Decl *>(
373 PU.get<ClassTemplatePartialSpecializationDecl *>());
374 }
375
376 // Class is instantiated from a member definition of a class template?
377 if (const MemberSpecializationInfo *Info =
378 CRD->getMemberSpecializationInfo())
379 return *Info->getInstantiatedFrom();
380
381 return D;
382 }
383 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
384 // Enum is instantiated from a member definition of a class template?
385 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
386 return *MemberDecl;
387
388 return D;
389 }
390 // FIXME: Adjust alias templates?
391 return D;
392}
393
394const RawComment *ASTContext::getRawCommentForAnyRedecl(
395 const Decl *D,
396 const Decl **OriginalDecl) const {
397 if (!D) {
398 if (OriginalDecl)
399 OriginalDecl = nullptr;
400 return nullptr;
401 }
402
403 D = &adjustDeclToTemplate(*D);
404
405 // Any comment directly attached to D?
406 {
407 auto DeclComment = DeclRawComments.find(D);
408 if (DeclComment != DeclRawComments.end()) {
409 if (OriginalDecl)
410 *OriginalDecl = D;
411 return DeclComment->second;
412 }
413 }
414
415 // Any comment attached to any redeclaration of D?
416 const Decl *CanonicalD = D->getCanonicalDecl();
417 if (!CanonicalD)
418 return nullptr;
419
420 {
421 auto RedeclComment = RedeclChainComments.find(CanonicalD);
422 if (RedeclComment != RedeclChainComments.end()) {
423 if (OriginalDecl)
424 *OriginalDecl = RedeclComment->second;
425 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
426 assert(CommentAtRedecl != DeclRawComments.end() &&((CommentAtRedecl != DeclRawComments.end() && "This decl is supposed to have comment attached."
) ? static_cast<void> (0) : __assert_fail ("CommentAtRedecl != DeclRawComments.end() && \"This decl is supposed to have comment attached.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 427, __PRETTY_FUNCTION__))
427 "This decl is supposed to have comment attached.")((CommentAtRedecl != DeclRawComments.end() && "This decl is supposed to have comment attached."
) ? static_cast<void> (0) : __assert_fail ("CommentAtRedecl != DeclRawComments.end() && \"This decl is supposed to have comment attached.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 427, __PRETTY_FUNCTION__))
;
428 return CommentAtRedecl->second;
429 }
430 }
431
432 // Any redeclarations of D that we haven't checked for comments yet?
433 // We can't use DenseMap::iterator directly since it'd get invalid.
434 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
435 auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
436 if (LookupRes != CommentlessRedeclChains.end())
437 return LookupRes->second;
438 return nullptr;
439 }();
440
441 for (const auto Redecl : D->redecls()) {
442 assert(Redecl)((Redecl) ? static_cast<void> (0) : __assert_fail ("Redecl"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 442, __PRETTY_FUNCTION__))
;
443 // Skip all redeclarations that have been checked previously.
444 if (LastCheckedRedecl) {
445 if (LastCheckedRedecl == Redecl) {
446 LastCheckedRedecl = nullptr;
447 }
448 continue;
449 }
450 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
451 if (RedeclComment) {
452 cacheRawCommentForDecl(*Redecl, *RedeclComment);
453 if (OriginalDecl)
454 *OriginalDecl = Redecl;
455 return RedeclComment;
456 }
457 CommentlessRedeclChains[CanonicalD] = Redecl;
458 }
459
460 if (OriginalDecl)
461 *OriginalDecl = nullptr;
462 return nullptr;
463}
464
465void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
466 const RawComment &Comment) const {
467 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments)((Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments
) ? static_cast<void> (0) : __assert_fail ("Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 467, __PRETTY_FUNCTION__))
;
468 DeclRawComments.try_emplace(&OriginalD, &Comment);
469 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
470 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
471 CommentlessRedeclChains.erase(CanonicalDecl);
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>(DC)) {
478 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
479 if (!ID)
480 return;
481 // Add redeclared method here.
482 for (const auto *Ext : ID->known_extensions()) {
483 if (ObjCMethodDecl *RedeclaredMethod =
484 Ext->getMethod(ObjCMethod->getSelector(),
485 ObjCMethod->isInstanceMethod()))
486 Redeclared.push_back(RedeclaredMethod);
487 }
488 }
489}
490
491void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
492 const Preprocessor *PP) {
493 if (Comments.empty() || Decls.empty())
494 return;
495
496 // See if there are any new comments that are not attached to a decl.
497 // The location doesn't have to be precise - we care only about the file.
498 const FileID File =
499 SourceMgr.getDecomposedLoc((*Decls.begin())->getLocation()).first;
500 auto CommentsInThisFile = Comments.getCommentsInFile(File);
501 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
502 CommentsInThisFile->rbegin()->second->isAttached())
503 return;
504
505 // There is at least one comment not attached to a decl.
506 // Maybe it should be attached to one of Decls?
507 //
508 // Note that this way we pick up not only comments that precede the
509 // declaration, but also comments that *follow* the declaration -- thanks to
510 // the lookahead in the lexer: we've consumed the semicolon and looked
511 // ahead through comments.
512
513 for (const Decl *D : Decls) {
514 assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 514, __PRETTY_FUNCTION__))
;
515 if (D->isInvalidDecl())
516 continue;
517
518 D = &adjustDeclToTemplate(*D);
519
520 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
521
522 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
523 continue;
524
525 if (DeclRawComments.count(D) > 0)
526 continue;
527
528 if (RawComment *const DocComment =
529 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
530 cacheRawCommentForDecl(*D, *DocComment);
531 comments::FullComment *FC = DocComment->parse(*this, PP, D);
532 ParsedComments[D->getCanonicalDecl()] = FC;
533 }
534 }
535}
536
537comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
538 const Decl *D) const {
539 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
540 ThisDeclInfo->CommentDecl = D;
541 ThisDeclInfo->IsFilled = false;
542 ThisDeclInfo->fill();
543 ThisDeclInfo->CommentDecl = FC->getDecl();
544 if (!ThisDeclInfo->TemplateParameters)
545 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
546 comments::FullComment *CFC =
547 new (*this) comments::FullComment(FC->getBlocks(),
548 ThisDeclInfo);
549 return CFC;
550}
551
552comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
553 const RawComment *RC = getRawCommentForDeclNoCache(D);
554 return RC ? RC->parse(*this, nullptr, D) : nullptr;
555}
556
557comments::FullComment *ASTContext::getCommentForDecl(
558 const Decl *D,
559 const Preprocessor *PP) const {
560 if (!D || D->isInvalidDecl())
561 return nullptr;
562 D = &adjustDeclToTemplate(*D);
563
564 const Decl *Canonical = D->getCanonicalDecl();
565 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
566 ParsedComments.find(Canonical);
567
568 if (Pos != ParsedComments.end()) {
569 if (Canonical != D) {
570 comments::FullComment *FC = Pos->second;
571 comments::FullComment *CFC = cloneFullComment(FC, D);
572 return CFC;
573 }
574 return Pos->second;
575 }
576
577 const Decl *OriginalDecl = nullptr;
578
579 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
580 if (!RC) {
581 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
582 SmallVector<const NamedDecl*, 8> Overridden;
583 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
584 if (OMD && OMD->isPropertyAccessor())
585 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
586 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
587 return cloneFullComment(FC, D);
588 if (OMD)
589 addRedeclaredMethods(OMD, Overridden);
590 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
591 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
592 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
593 return cloneFullComment(FC, D);
594 }
595 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
596 // Attach any tag type's documentation to its typedef if latter
597 // does not have one of its own.
598 QualType QT = TD->getUnderlyingType();
599 if (const auto *TT = QT->getAs<TagType>())
600 if (const Decl *TD = TT->getDecl())
601 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
602 return cloneFullComment(FC, D);
603 }
604 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
605 while (IC->getSuperClass()) {
606 IC = IC->getSuperClass();
607 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
608 return cloneFullComment(FC, D);
609 }
610 }
611 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
612 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
613 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
614 return cloneFullComment(FC, D);
615 }
616 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
617 if (!(RD = RD->getDefinition()))
618 return nullptr;
619 // Check non-virtual bases.
620 for (const auto &I : RD->bases()) {
621 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
622 continue;
623 QualType Ty = I.getType();
624 if (Ty.isNull())
625 continue;
626 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
627 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
628 continue;
629
630 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
631 return cloneFullComment(FC, D);
632 }
633 }
634 // Check virtual bases.
635 for (const auto &I : RD->vbases()) {
636 if (I.getAccessSpecifier() != AS_public)
637 continue;
638 QualType Ty = I.getType();
639 if (Ty.isNull())
640 continue;
641 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
642 if (!(VirtualBase= VirtualBase->getDefinition()))
643 continue;
644 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
645 return cloneFullComment(FC, D);
646 }
647 }
648 }
649 return nullptr;
650 }
651
652 // If the RawComment was attached to other redeclaration of this Decl, we
653 // should parse the comment in context of that other Decl. This is important
654 // because comments can contain references to parameter names which can be
655 // different across redeclarations.
656 if (D != OriginalDecl && OriginalDecl)
657 return getCommentForDecl(OriginalDecl, PP);
658
659 comments::FullComment *FC = RC->parse(*this, PP, D);
660 ParsedComments[Canonical] = FC;
661 return FC;
662}
663
664void
665ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
666 TemplateTemplateParmDecl *Parm) {
667 ID.AddInteger(Parm->getDepth());
668 ID.AddInteger(Parm->getPosition());
669 ID.AddBoolean(Parm->isParameterPack());
670
671 TemplateParameterList *Params = Parm->getTemplateParameters();
672 ID.AddInteger(Params->size());
673 for (TemplateParameterList::const_iterator P = Params->begin(),
674 PEnd = Params->end();
675 P != PEnd; ++P) {
676 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
677 ID.AddInteger(0);
678 ID.AddBoolean(TTP->isParameterPack());
679 continue;
680 }
681
682 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
683 ID.AddInteger(1);
684 ID.AddBoolean(NTTP->isParameterPack());
685 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
686 if (NTTP->isExpandedParameterPack()) {
687 ID.AddBoolean(true);
688 ID.AddInteger(NTTP->getNumExpansionTypes());
689 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
690 QualType T = NTTP->getExpansionType(I);
691 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
692 }
693 } else
694 ID.AddBoolean(false);
695 continue;
696 }
697
698 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
699 ID.AddInteger(2);
700 Profile(ID, TTP);
701 }
702}
703
704TemplateTemplateParmDecl *
705ASTContext::getCanonicalTemplateTemplateParmDecl(
706 TemplateTemplateParmDecl *TTP) const {
707 // Check if we already have a canonical template template parameter.
708 llvm::FoldingSetNodeID ID;
709 CanonicalTemplateTemplateParm::Profile(ID, TTP);
710 void *InsertPos = nullptr;
711 CanonicalTemplateTemplateParm *Canonical
712 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
713 if (Canonical)
714 return Canonical->getParam();
715
716 // Build a canonical template parameter list.
717 TemplateParameterList *Params = TTP->getTemplateParameters();
718 SmallVector<NamedDecl *, 4> CanonParams;
719 CanonParams.reserve(Params->size());
720 for (TemplateParameterList::const_iterator P = Params->begin(),
721 PEnd = Params->end();
722 P != PEnd; ++P) {
723 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
724 CanonParams.push_back(
725 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
726 SourceLocation(),
727 SourceLocation(),
728 TTP->getDepth(),
729 TTP->getIndex(), nullptr, false,
730 TTP->isParameterPack()));
731 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
732 QualType T = getCanonicalType(NTTP->getType());
733 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
734 NonTypeTemplateParmDecl *Param;
735 if (NTTP->isExpandedParameterPack()) {
736 SmallVector<QualType, 2> ExpandedTypes;
737 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
738 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
739 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
740 ExpandedTInfos.push_back(
741 getTrivialTypeSourceInfo(ExpandedTypes.back()));
742 }
743
744 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
745 SourceLocation(),
746 SourceLocation(),
747 NTTP->getDepth(),
748 NTTP->getPosition(), nullptr,
749 T,
750 TInfo,
751 ExpandedTypes,
752 ExpandedTInfos);
753 } else {
754 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
755 SourceLocation(),
756 SourceLocation(),
757 NTTP->getDepth(),
758 NTTP->getPosition(), nullptr,
759 T,
760 NTTP->isParameterPack(),
761 TInfo);
762 }
763 CanonParams.push_back(Param);
764
765 } else
766 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
767 cast<TemplateTemplateParmDecl>(*P)));
768 }
769
770 assert(!TTP->getTemplateParameters()->getRequiresClause() &&((!TTP->getTemplateParameters()->getRequiresClause() &&
"Unexpected requires-clause on template template-parameter")
? static_cast<void> (0) : __assert_fail ("!TTP->getTemplateParameters()->getRequiresClause() && \"Unexpected requires-clause on template template-parameter\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 771, __PRETTY_FUNCTION__))
771 "Unexpected requires-clause on template template-parameter")((!TTP->getTemplateParameters()->getRequiresClause() &&
"Unexpected requires-clause on template template-parameter")
? static_cast<void> (0) : __assert_fail ("!TTP->getTemplateParameters()->getRequiresClause() && \"Unexpected requires-clause on template template-parameter\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 771, __PRETTY_FUNCTION__))
;
772 Expr *const CanonRequiresClause = nullptr;
773
774 TemplateTemplateParmDecl *CanonTTP
775 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
776 SourceLocation(), TTP->getDepth(),
777 TTP->getPosition(),
778 TTP->isParameterPack(),
779 nullptr,
780 TemplateParameterList::Create(*this, SourceLocation(),
781 SourceLocation(),
782 CanonParams,
783 SourceLocation(),
784 CanonRequiresClause));
785
786 // Get the new insert position for the node we care about.
787 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
788 assert(!Canonical && "Shouldn't be in the map!")((!Canonical && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!Canonical && \"Shouldn't be in the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 788, __PRETTY_FUNCTION__))
;
789 (void)Canonical;
790
791 // Create the canonical template template parameter entry.
792 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
793 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
794 return CanonTTP;
795}
796
797CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
798 if (!LangOpts.CPlusPlus) return nullptr;
799
800 switch (T.getCXXABI().getKind()) {
801 case TargetCXXABI::Fuchsia:
802 case TargetCXXABI::GenericARM: // Same as Itanium at this level
803 case TargetCXXABI::iOS:
804 case TargetCXXABI::iOS64:
805 case TargetCXXABI::WatchOS:
806 case TargetCXXABI::GenericAArch64:
807 case TargetCXXABI::GenericMIPS:
808 case TargetCXXABI::GenericItanium:
809 case TargetCXXABI::WebAssembly:
810 return CreateItaniumCXXABI(*this);
811 case TargetCXXABI::Microsoft:
812 return CreateMicrosoftCXXABI(*this);
813 }
814 llvm_unreachable("Invalid CXXABI type!")::llvm::llvm_unreachable_internal("Invalid CXXABI type!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 814)
;
815}
816
817interp::Context &ASTContext::getInterpContext() {
818 if (!InterpContext) {
819 InterpContext.reset(new interp::Context(*this));
820 }
821 return *InterpContext.get();
822}
823
824static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
825 const LangOptions &LOpts) {
826 if (LOpts.FakeAddressSpaceMap) {
827 // The fake address space map must have a distinct entry for each
828 // language-specific address space.
829 static const unsigned FakeAddrSpaceMap[] = {
830 0, // Default
831 1, // opencl_global
832 3, // opencl_local
833 2, // opencl_constant
834 0, // opencl_private
835 4, // opencl_generic
836 5, // cuda_device
837 6, // cuda_constant
838 7, // cuda_shared
839 8, // ptr32_sptr
840 9, // ptr32_uptr
841 10 // ptr64
842 };
843 return &FakeAddrSpaceMap;
844 } else {
845 return &T.getAddressSpaceMap();
846 }
847}
848
849static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
850 const LangOptions &LangOpts) {
851 switch (LangOpts.getAddressSpaceMapMangling()) {
852 case LangOptions::ASMM_Target:
853 return TI.useAddressSpaceMapMangling();
854 case LangOptions::ASMM_On:
855 return true;
856 case LangOptions::ASMM_Off:
857 return false;
858 }
859 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.")::llvm::llvm_unreachable_internal("getAddressSpaceMapMangling() doesn't cover anything."
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 859)
;
860}
861
862ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
863 IdentifierTable &idents, SelectorTable &sels,
864 Builtin::Context &builtins)
865 : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()),
866 TemplateSpecializationTypes(this_()),
867 DependentTemplateSpecializationTypes(this_()),
868 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
869 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
870 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
871 LangOpts.XRayNeverInstrumentFiles,
872 LangOpts.XRayAttrListFiles, SM)),
873 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
874 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
875 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
876 CompCategories(this_()), LastSDM(nullptr, 0) {
877 TUDecl = TranslationUnitDecl::Create(*this);
878 TraversalScope = {TUDecl};
879}
880
881ASTContext::~ASTContext() {
882 // Release the DenseMaps associated with DeclContext objects.
883 // FIXME: Is this the ideal solution?
884 ReleaseDeclContextMaps();
885
886 // Call all of the deallocation functions on all of their targets.
887 for (auto &Pair : Deallocations)
888 (Pair.first)(Pair.second);
889
890 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
891 // because they can contain DenseMaps.
892 for (llvm::DenseMap<const ObjCContainerDecl*,
893 const ASTRecordLayout*>::iterator
894 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
895 // Increment in loop to prevent using deallocated memory.
896 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
897 R->Destroy(*this);
898
899 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
900 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
901 // Increment in loop to prevent using deallocated memory.
902 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
903 R->Destroy(*this);
904 }
905
906 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
907 AEnd = DeclAttrs.end();
908 A != AEnd; ++A)
909 A->second->~AttrVec();
910
911 for (const auto &Value : ModuleInitializers)
912 Value.second->~PerModuleInitializers();
913
914 for (APValue *Value : APValueCleanups)
915 Value->~APValue();
916}
917
918class ASTContext::ParentMap {
919 /// Contains parents of a node.
920 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
921
922 /// Maps from a node to its parents. This is used for nodes that have
923 /// pointer identity only, which are more common and we can save space by
924 /// only storing a unique pointer to them.
925 using ParentMapPointers = llvm::DenseMap<
926 const void *,
927 llvm::PointerUnion4<const Decl *, const Stmt *,
928 ast_type_traits::DynTypedNode *, ParentVector *>>;
929
930 /// Parent map for nodes without pointer identity. We store a full
931 /// DynTypedNode for all keys.
932 using ParentMapOtherNodes = llvm::DenseMap<
933 ast_type_traits::DynTypedNode,
934 llvm::PointerUnion4<const Decl *, const Stmt *,
935 ast_type_traits::DynTypedNode *, ParentVector *>>;
936
937 ParentMapPointers PointerParents;
938 ParentMapOtherNodes OtherParents;
939 class ASTVisitor;
940
941 static ast_type_traits::DynTypedNode
942 getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
943 if (const auto *D = U.dyn_cast<const Decl *>())
944 return ast_type_traits::DynTypedNode::create(*D);
945 if (const auto *S = U.dyn_cast<const Stmt *>())
946 return ast_type_traits::DynTypedNode::create(*S);
947 return *U.get<ast_type_traits::DynTypedNode *>();
948 }
949
950 template <typename NodeTy, typename MapTy>
951 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
952 const MapTy &Map) {
953 auto I = Map.find(Node);
954 if (I == Map.end()) {
955 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
956 }
957 if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
958 return llvm::makeArrayRef(*V);
959 }
960 return getSingleDynTypedNodeFromParentMap(I->second);
961 }
962
963public:
964 ParentMap(ASTContext &Ctx);
965 ~ParentMap() {
966 for (const auto &Entry : PointerParents) {
967 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
968 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
969 } else if (Entry.second.is<ParentVector *>()) {
970 delete Entry.second.get<ParentVector *>();
971 }
972 }
973 for (const auto &Entry : OtherParents) {
974 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
975 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
976 } else if (Entry.second.is<ParentVector *>()) {
977 delete Entry.second.get<ParentVector *>();
978 }
979 }
980 }
981
982 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
983 if (Node.getNodeKind().hasPointerIdentity())
984 return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
985 return getDynNodeFromMap(Node, OtherParents);
986 }
987};
988
989void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
990 TraversalScope = TopLevelDecls;
991 Parents.clear();
992}
993
994void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
995 Deallocations.push_back({Callback, Data});
996}
997
998void
999ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1000 ExternalSource = std::move(Source);
1001}
1002
1003void ASTContext::PrintStats() const {
1004 llvm::errs() << "\n*** AST Context Stats:\n";
1005 llvm::errs() << " " << Types.size() << " types total.\n";
1006
1007 unsigned counts[] = {
1008#define TYPE(Name, Parent) 0,
1009#define ABSTRACT_TYPE(Name, Parent)
1010#include "clang/AST/TypeNodes.inc"
1011 0 // Extra
1012 };
1013
1014 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1015 Type *T = Types[i];
1016 counts[(unsigned)T->getTypeClass()]++;
1017 }
1018
1019 unsigned Idx = 0;
1020 unsigned TotalBytes = 0;
1021#define TYPE(Name, Parent) \
1022 if (counts[Idx]) \
1023 llvm::errs() << " " << counts[Idx] << " " << #Name \
1024 << " types, " << sizeof(Name##Type) << " each " \
1025 << "(" << counts[Idx] * sizeof(Name##Type) \
1026 << " bytes)\n"; \
1027 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1028 ++Idx;
1029#define ABSTRACT_TYPE(Name, Parent)
1030#include "clang/AST/TypeNodes.inc"
1031
1032 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1033
1034 // Implicit special member functions.
1035 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1036 << NumImplicitDefaultConstructors
1037 << " implicit default constructors created\n";
1038 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1039 << NumImplicitCopyConstructors
1040 << " implicit copy constructors created\n";
1041 if (getLangOpts().CPlusPlus)
1042 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1043 << NumImplicitMoveConstructors
1044 << " implicit move constructors created\n";
1045 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1046 << NumImplicitCopyAssignmentOperators
1047 << " implicit copy assignment operators created\n";
1048 if (getLangOpts().CPlusPlus)
1049 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1050 << NumImplicitMoveAssignmentOperators
1051 << " implicit move assignment operators created\n";
1052 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1053 << NumImplicitDestructors
1054 << " implicit destructors created\n";
1055
1056 if (ExternalSource) {
1057 llvm::errs() << "\n";
1058 ExternalSource->PrintStats();
1059 }
1060
1061 BumpAlloc.PrintStats();
1062}
1063
1064void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1065 bool NotifyListeners) {
1066 if (NotifyListeners)
1067 if (auto *Listener = getASTMutationListener())
1068 Listener->RedefinedHiddenDefinition(ND, M);
1069
1070 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1071}
1072
1073void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
1074 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1075 if (It == MergedDefModules.end())
1076 return;
1077
1078 auto &Merged = It->second;
1079 llvm::DenseSet<Module*> Found;
1080 for (Module *&M : Merged)
1081 if (!Found.insert(M).second)
1082 M = nullptr;
1083 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1084}
1085
1086void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1087 if (LazyInitializers.empty())
1088 return;
1089
1090 auto *Source = Ctx.getExternalSource();
1091 assert(Source && "lazy initializers but no external source")((Source && "lazy initializers but no external source"
) ? static_cast<void> (0) : __assert_fail ("Source && \"lazy initializers but no external source\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1091, __PRETTY_FUNCTION__))
;
1092
1093 auto LazyInits = std::move(LazyInitializers);
1094 LazyInitializers.clear();
1095
1096 for (auto ID : LazyInits)
1097 Initializers.push_back(Source->GetExternalDecl(ID));
1098
1099 assert(LazyInitializers.empty() &&((LazyInitializers.empty() && "GetExternalDecl for lazy module initializer added more inits"
) ? static_cast<void> (0) : __assert_fail ("LazyInitializers.empty() && \"GetExternalDecl for lazy module initializer added more inits\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1100, __PRETTY_FUNCTION__))
1100 "GetExternalDecl for lazy module initializer added more inits")((LazyInitializers.empty() && "GetExternalDecl for lazy module initializer added more inits"
) ? static_cast<void> (0) : __assert_fail ("LazyInitializers.empty() && \"GetExternalDecl for lazy module initializer added more inits\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1100, __PRETTY_FUNCTION__))
;
1101}
1102
1103void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1104 // One special case: if we add a module initializer that imports another
1105 // module, and that module's only initializer is an ImportDecl, simplify.
1106 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1107 auto It = ModuleInitializers.find(ID->getImportedModule());
1108
1109 // Maybe the ImportDecl does nothing at all. (Common case.)
1110 if (It == ModuleInitializers.end())
1111 return;
1112
1113 // Maybe the ImportDecl only imports another ImportDecl.
1114 auto &Imported = *It->second;
1115 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1116 Imported.resolve(*this);
1117 auto *OnlyDecl = Imported.Initializers.front();
1118 if (isa<ImportDecl>(OnlyDecl))
1119 D = OnlyDecl;
1120 }
1121 }
1122
1123 auto *&Inits = ModuleInitializers[M];
1124 if (!Inits)
1125 Inits = new (*this) PerModuleInitializers;
1126 Inits->Initializers.push_back(D);
1127}
1128
1129void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1130 auto *&Inits = ModuleInitializers[M];
1131 if (!Inits)
1132 Inits = new (*this) PerModuleInitializers;
1133 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1134 IDs.begin(), IDs.end());
1135}
1136
1137ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1138 auto It = ModuleInitializers.find(M);
1139 if (It == ModuleInitializers.end())
1140 return None;
1141
1142 auto *Inits = It->second;
1143 Inits->resolve(*this);
1144 return Inits->Initializers;
1145}
1146
1147ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1148 if (!ExternCContext)
1149 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1150
1151 return ExternCContext;
1152}
1153
1154BuiltinTemplateDecl *
1155ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1156 const IdentifierInfo *II) const {
1157 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1158 BuiltinTemplate->setImplicit();
1159 TUDecl->addDecl(BuiltinTemplate);
1160
1161 return BuiltinTemplate;
1162}
1163
1164BuiltinTemplateDecl *
1165ASTContext::getMakeIntegerSeqDecl() const {
1166 if (!MakeIntegerSeqDecl)
1167 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1168 getMakeIntegerSeqName());
1169 return MakeIntegerSeqDecl;
1170}
1171
1172BuiltinTemplateDecl *
1173ASTContext::getTypePackElementDecl() const {
1174 if (!TypePackElementDecl)
1175 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1176 getTypePackElementName());
1177 return TypePackElementDecl;
1178}
1179
1180RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1181 RecordDecl::TagKind TK) const {
1182 SourceLocation Loc;
1183 RecordDecl *NewDecl;
1184 if (getLangOpts().CPlusPlus)
1185 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1186 Loc, &Idents.get(Name));
1187 else
1188 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1189 &Idents.get(Name));
1190 NewDecl->setImplicit();
1191 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1192 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1193 return NewDecl;
1194}
1195
1196TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1197 StringRef Name) const {
1198 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1199 TypedefDecl *NewDecl = TypedefDecl::Create(
1200 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1201 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1202 NewDecl->setImplicit();
1203 return NewDecl;
1204}
1205
1206TypedefDecl *ASTContext::getInt128Decl() const {
1207 if (!Int128Decl)
1208 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1209 return Int128Decl;
1210}
1211
1212TypedefDecl *ASTContext::getUInt128Decl() const {
1213 if (!UInt128Decl)
1214 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1215 return UInt128Decl;
1216}
1217
1218void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1219 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1220 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1221 Types.push_back(Ty);
1222}
1223
1224void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1225 const TargetInfo *AuxTarget) {
1226 assert((!this->Target || this->Target == &Target) &&(((!this->Target || this->Target == &Target) &&
"Incorrect target reinitialization") ? static_cast<void>
(0) : __assert_fail ("(!this->Target || this->Target == &Target) && \"Incorrect target reinitialization\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1227, __PRETTY_FUNCTION__))
1227 "Incorrect target reinitialization")(((!this->Target || this->Target == &Target) &&
"Incorrect target reinitialization") ? static_cast<void>
(0) : __assert_fail ("(!this->Target || this->Target == &Target) && \"Incorrect target reinitialization\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1227, __PRETTY_FUNCTION__))
;
1228 assert(VoidTy.isNull() && "Context reinitialized?")((VoidTy.isNull() && "Context reinitialized?") ? static_cast
<void> (0) : __assert_fail ("VoidTy.isNull() && \"Context reinitialized?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1228, __PRETTY_FUNCTION__))
;
1229
1230 this->Target = &Target;
1231 this->AuxTarget = AuxTarget;
1232
1233 ABI.reset(createCXXABI(Target));
1234 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1235 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1236
1237 // C99 6.2.5p19.
1238 InitBuiltinType(VoidTy, BuiltinType::Void);
1239
1240 // C99 6.2.5p2.
1241 InitBuiltinType(BoolTy, BuiltinType::Bool);
1242 // C99 6.2.5p3.
1243 if (LangOpts.CharIsSigned)
1244 InitBuiltinType(CharTy, BuiltinType::Char_S);
1245 else
1246 InitBuiltinType(CharTy, BuiltinType::Char_U);
1247 // C99 6.2.5p4.
1248 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1249 InitBuiltinType(ShortTy, BuiltinType::Short);
1250 InitBuiltinType(IntTy, BuiltinType::Int);
1251 InitBuiltinType(LongTy, BuiltinType::Long);
1252 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1253
1254 // C99 6.2.5p6.
1255 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1256 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1257 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1258 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1259 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1260
1261 // C99 6.2.5p10.
1262 InitBuiltinType(FloatTy, BuiltinType::Float);
1263 InitBuiltinType(DoubleTy, BuiltinType::Double);
1264 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1265
1266 // GNU extension, __float128 for IEEE quadruple precision
1267 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1268
1269 // C11 extension ISO/IEC TS 18661-3
1270 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1271
1272 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1273 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1274 InitBuiltinType(AccumTy, BuiltinType::Accum);
1275 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1276 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1277 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1278 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1279 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1280 InitBuiltinType(FractTy, BuiltinType::Fract);
1281 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1282 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1283 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1284 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1285 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1286 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1287 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1288 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1289 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1290 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1291 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1292 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1293 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1294 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1295 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1296 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1297
1298 // GNU extension, 128-bit integers.
1299 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1300 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1301
1302 // C++ 3.9.1p5
1303 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1304 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1305 else // -fshort-wchar makes wchar_t be unsigned.
1306 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1307 if (LangOpts.CPlusPlus && LangOpts.WChar)
1308 WideCharTy = WCharTy;
1309 else {
1310 // C99 (or C++ using -fno-wchar).
1311 WideCharTy = getFromTargetType(Target.getWCharType());
1312 }
1313
1314 WIntTy = getFromTargetType(Target.getWIntType());
1315
1316 // C++20 (proposed)
1317 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1318
1319 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1320 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1321 else // C99
1322 Char16Ty = getFromTargetType(Target.getChar16Type());
1323
1324 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1325 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1326 else // C99
1327 Char32Ty = getFromTargetType(Target.getChar32Type());
1328
1329 // Placeholder type for type-dependent expressions whose type is
1330 // completely unknown. No code should ever check a type against
1331 // DependentTy and users should never see it; however, it is here to
1332 // help diagnose failures to properly check for type-dependent
1333 // expressions.
1334 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1335
1336 // Placeholder type for functions.
1337 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1338
1339 // Placeholder type for bound members.
1340 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1341
1342 // Placeholder type for pseudo-objects.
1343 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1344
1345 // "any" type; useful for debugger-like clients.
1346 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1347
1348 // Placeholder type for unbridged ARC casts.
1349 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1350
1351 // Placeholder type for builtin functions.
1352 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1353
1354 // Placeholder type for OMP array sections.
1355 if (LangOpts.OpenMP)
1356 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1357
1358 // C99 6.2.5p11.
1359 FloatComplexTy = getComplexType(FloatTy);
1360 DoubleComplexTy = getComplexType(DoubleTy);
1361 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1362 Float128ComplexTy = getComplexType(Float128Ty);
1363
1364 // Builtin types for 'id', 'Class', and 'SEL'.
1365 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1366 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1367 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1368
1369 if (LangOpts.OpenCL) {
1370#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1371 InitBuiltinType(SingletonId, BuiltinType::Id);
1372#include "clang/Basic/OpenCLImageTypes.def"
1373
1374 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1375 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1376 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1377 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1378 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1379
1380#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1381 InitBuiltinType(Id##Ty, BuiltinType::Id);
1382#include "clang/Basic/OpenCLExtensionTypes.def"
1383 }
1384
1385 if (Target.hasAArch64SVETypes()) {
1386#define SVE_TYPE(Name, Id, SingletonId) \
1387 InitBuiltinType(SingletonId, BuiltinType::Id);
1388#include "clang/Basic/AArch64SVEACLETypes.def"
1389 }
1390
1391 // Builtin type for __objc_yes and __objc_no
1392 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1393 SignedCharTy : BoolTy);
1394
1395 ObjCConstantStringType = QualType();
1396
1397 ObjCSuperType = QualType();
1398
1399 // void * type
1400 if (LangOpts.OpenCLVersion >= 200) {
1401 auto Q = VoidTy.getQualifiers();
1402 Q.setAddressSpace(LangAS::opencl_generic);
1403 VoidPtrTy = getPointerType(getCanonicalType(
1404 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1405 } else {
1406 VoidPtrTy = getPointerType(VoidTy);
1407 }
1408
1409 // nullptr type (C++0x 2.14.7)
1410 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1411
1412 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1413 InitBuiltinType(HalfTy, BuiltinType::Half);
1414
1415 // Builtin type used to help define __builtin_va_list.
1416 VaListTagDecl = nullptr;
1417}
1418
1419DiagnosticsEngine &ASTContext::getDiagnostics() const {
1420 return SourceMgr.getDiagnostics();
1421}
1422
1423AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1424 AttrVec *&Result = DeclAttrs[D];
1425 if (!Result) {
1426 void *Mem = Allocate(sizeof(AttrVec));
1427 Result = new (Mem) AttrVec;
1428 }
1429
1430 return *Result;
1431}
1432
1433/// Erase the attributes corresponding to the given declaration.
1434void ASTContext::eraseDeclAttrs(const Decl *D) {
1435 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1436 if (Pos != DeclAttrs.end()) {
1437 Pos->second->~AttrVec();
1438 DeclAttrs.erase(Pos);
1439 }
1440}
1441
1442// FIXME: Remove ?
1443MemberSpecializationInfo *
1444ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1445 assert(Var->isStaticDataMember() && "Not a static data member")((Var->isStaticDataMember() && "Not a static data member"
) ? static_cast<void> (0) : __assert_fail ("Var->isStaticDataMember() && \"Not a static data member\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1445, __PRETTY_FUNCTION__))
;
1446 return getTemplateOrSpecializationInfo(Var)
1447 .dyn_cast<MemberSpecializationInfo *>();
1448}
1449
1450ASTContext::TemplateOrSpecializationInfo
1451ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1452 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1453 TemplateOrInstantiation.find(Var);
1454 if (Pos == TemplateOrInstantiation.end())
1455 return {};
1456
1457 return Pos->second;
1458}
1459
1460void
1461ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1462 TemplateSpecializationKind TSK,
1463 SourceLocation PointOfInstantiation) {
1464 assert(Inst->isStaticDataMember() && "Not a static data member")((Inst->isStaticDataMember() && "Not a static data member"
) ? static_cast<void> (0) : __assert_fail ("Inst->isStaticDataMember() && \"Not a static data member\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1464, __PRETTY_FUNCTION__))
;
1465 assert(Tmpl->isStaticDataMember() && "Not a static data member")((Tmpl->isStaticDataMember() && "Not a static data member"
) ? static_cast<void> (0) : __assert_fail ("Tmpl->isStaticDataMember() && \"Not a static data member\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1465, __PRETTY_FUNCTION__))
;
1466 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1467 Tmpl, TSK, PointOfInstantiation));
1468}
1469
1470void
1471ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1472 TemplateOrSpecializationInfo TSI) {
1473 assert(!TemplateOrInstantiation[Inst] &&((!TemplateOrInstantiation[Inst] && "Already noted what the variable was instantiated from"
) ? static_cast<void> (0) : __assert_fail ("!TemplateOrInstantiation[Inst] && \"Already noted what the variable was instantiated from\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1474, __PRETTY_FUNCTION__))
1474 "Already noted what the variable was instantiated from")((!TemplateOrInstantiation[Inst] && "Already noted what the variable was instantiated from"
) ? static_cast<void> (0) : __assert_fail ("!TemplateOrInstantiation[Inst] && \"Already noted what the variable was instantiated from\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1474, __PRETTY_FUNCTION__))
;
1475 TemplateOrInstantiation[Inst] = TSI;
1476}
1477
1478NamedDecl *
1479ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1480 auto Pos = InstantiatedFromUsingDecl.find(UUD);
1481 if (Pos == InstantiatedFromUsingDecl.end())
1482 return nullptr;
1483
1484 return Pos->second;
1485}
1486
1487void
1488ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1489 assert((isa<UsingDecl>(Pattern) ||(((isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl
>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern
)) && "pattern decl is not a using decl") ? static_cast
<void> (0) : __assert_fail ("(isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern)) && \"pattern decl is not a using decl\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1492, __PRETTY_FUNCTION__))
1490 isa<UnresolvedUsingValueDecl>(Pattern) ||(((isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl
>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern
)) && "pattern decl is not a using decl") ? static_cast
<void> (0) : __assert_fail ("(isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern)) && \"pattern decl is not a using decl\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1492, __PRETTY_FUNCTION__))
1491 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&(((isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl
>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern
)) && "pattern decl is not a using decl") ? static_cast
<void> (0) : __assert_fail ("(isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern)) && \"pattern decl is not a using decl\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1492, __PRETTY_FUNCTION__))
1492 "pattern decl is not a using decl")(((isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl
>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern
)) && "pattern decl is not a using decl") ? static_cast
<void> (0) : __assert_fail ("(isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern)) && \"pattern decl is not a using decl\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1492, __PRETTY_FUNCTION__))
;
1493 assert((isa<UsingDecl>(Inst) ||(((isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl
>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) &&
"instantiation did not produce a using decl") ? static_cast<
void> (0) : __assert_fail ("(isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) && \"instantiation did not produce a using decl\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1496, __PRETTY_FUNCTION__))
1494 isa<UnresolvedUsingValueDecl>(Inst) ||(((isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl
>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) &&
"instantiation did not produce a using decl") ? static_cast<
void> (0) : __assert_fail ("(isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) && \"instantiation did not produce a using decl\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1496, __PRETTY_FUNCTION__))
1495 isa<UnresolvedUsingTypenameDecl>(Inst)) &&(((isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl
>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) &&
"instantiation did not produce a using decl") ? static_cast<
void> (0) : __assert_fail ("(isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) && \"instantiation did not produce a using decl\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1496, __PRETTY_FUNCTION__))
1496 "instantiation did not produce a using decl")(((isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl
>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) &&
"instantiation did not produce a using decl") ? static_cast<
void> (0) : __assert_fail ("(isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) && \"instantiation did not produce a using decl\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1496, __PRETTY_FUNCTION__))
;
1497 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists")((!InstantiatedFromUsingDecl[Inst] && "pattern already exists"
) ? static_cast<void> (0) : __assert_fail ("!InstantiatedFromUsingDecl[Inst] && \"pattern already exists\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1497, __PRETTY_FUNCTION__))
;
1498 InstantiatedFromUsingDecl[Inst] = Pattern;
1499}
1500
1501UsingShadowDecl *
1502ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1503 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1504 = InstantiatedFromUsingShadowDecl.find(Inst);
1505 if (Pos == InstantiatedFromUsingShadowDecl.end())
1506 return nullptr;
1507
1508 return Pos->second;
1509}
1510
1511void
1512ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1513 UsingShadowDecl *Pattern) {
1514 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists")((!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"
) ? static_cast<void> (0) : __assert_fail ("!InstantiatedFromUsingShadowDecl[Inst] && \"pattern already exists\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1514, __PRETTY_FUNCTION__))
;
1515 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1516}
1517
1518FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1519 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1520 = InstantiatedFromUnnamedFieldDecl.find(Field);
1521 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1522 return nullptr;
1523
1524 return Pos->second;
1525}
1526
1527void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1528 FieldDecl *Tmpl) {
1529 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed")((!Inst->getDeclName() && "Instantiated field decl is not unnamed"
) ? static_cast<void> (0) : __assert_fail ("!Inst->getDeclName() && \"Instantiated field decl is not unnamed\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1529, __PRETTY_FUNCTION__))
;
1530 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed")((!Tmpl->getDeclName() && "Template field decl is not unnamed"
) ? static_cast<void> (0) : __assert_fail ("!Tmpl->getDeclName() && \"Template field decl is not unnamed\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1530, __PRETTY_FUNCTION__))
;
1531 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&((!InstantiatedFromUnnamedFieldDecl[Inst] && "Already noted what unnamed field was instantiated from"
) ? static_cast<void> (0) : __assert_fail ("!InstantiatedFromUnnamedFieldDecl[Inst] && \"Already noted what unnamed field was instantiated from\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1532, __PRETTY_FUNCTION__))
1532 "Already noted what unnamed field was instantiated from")((!InstantiatedFromUnnamedFieldDecl[Inst] && "Already noted what unnamed field was instantiated from"
) ? static_cast<void> (0) : __assert_fail ("!InstantiatedFromUnnamedFieldDecl[Inst] && \"Already noted what unnamed field was instantiated from\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1532, __PRETTY_FUNCTION__))
;
1533
1534 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1535}
1536
1537ASTContext::overridden_cxx_method_iterator
1538ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1539 return overridden_methods(Method).begin();
1540}
1541
1542ASTContext::overridden_cxx_method_iterator
1543ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1544 return overridden_methods(Method).end();
1545}
1546
1547unsigned
1548ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1549 auto Range = overridden_methods(Method);
1550 return Range.end() - Range.begin();
1551}
1552
1553ASTContext::overridden_method_range
1554ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1555 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1556 OverriddenMethods.find(Method->getCanonicalDecl());
1557 if (Pos == OverriddenMethods.end())
1558 return overridden_method_range(nullptr, nullptr);
1559 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1560}
1561
1562void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1563 const CXXMethodDecl *Overridden) {
1564 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl())((Method->isCanonicalDecl() && Overridden->isCanonicalDecl
()) ? static_cast<void> (0) : __assert_fail ("Method->isCanonicalDecl() && Overridden->isCanonicalDecl()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1564, __PRETTY_FUNCTION__))
;
1565 OverriddenMethods[Method].push_back(Overridden);
1566}
1567
1568void ASTContext::getOverriddenMethods(
1569 const NamedDecl *D,
1570 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1571 assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1571, __PRETTY_FUNCTION__))
;
1572
1573 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1574 Overridden.append(overridden_methods_begin(CXXMethod),
1575 overridden_methods_end(CXXMethod));
1576 return;
1577 }
1578
1579 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1580 if (!Method)
1581 return;
1582
1583 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1584 Method->getOverriddenMethods(OverDecls);
1585 Overridden.append(OverDecls.begin(), OverDecls.end());
1586}
1587
1588void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1589 assert(!Import->NextLocalImport && "Import declaration already in the chain")((!Import->NextLocalImport && "Import declaration already in the chain"
) ? static_cast<void> (0) : __assert_fail ("!Import->NextLocalImport && \"Import declaration already in the chain\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1589, __PRETTY_FUNCTION__))
;
1590 assert(!Import->isFromASTFile() && "Non-local import declaration")((!Import->isFromASTFile() && "Non-local import declaration"
) ? static_cast<void> (0) : __assert_fail ("!Import->isFromASTFile() && \"Non-local import declaration\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1590, __PRETTY_FUNCTION__))
;
1591 if (!FirstLocalImport) {
1592 FirstLocalImport = Import;
1593 LastLocalImport = Import;
1594 return;
1595 }
1596
1597 LastLocalImport->NextLocalImport = Import;
1598 LastLocalImport = Import;
1599}
1600
1601//===----------------------------------------------------------------------===//
1602// Type Sizing and Analysis
1603//===----------------------------------------------------------------------===//
1604
1605/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1606/// scalar floating point type.
1607const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1608 switch (T->castAs<BuiltinType>()->getKind()) {
1609 default:
1610 llvm_unreachable("Not a floating point type!")::llvm::llvm_unreachable_internal("Not a floating point type!"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1610)
;
1611 case BuiltinType::Float16:
1612 case BuiltinType::Half:
1613 return Target->getHalfFormat();
1614 case BuiltinType::Float: return Target->getFloatFormat();
1615 case BuiltinType::Double: return Target->getDoubleFormat();
1616 case BuiltinType::LongDouble:
1617 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1618 return AuxTarget->getLongDoubleFormat();
1619 return Target->getLongDoubleFormat();
1620 case BuiltinType::Float128:
1621 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1622 return AuxTarget->getFloat128Format();
1623 return Target->getFloat128Format();
1624 }
1625}
1626
1627CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1628 unsigned Align = Target->getCharWidth();
1629
1630 bool UseAlignAttrOnly = false;
1631 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1632 Align = AlignFromAttr;
1633
1634 // __attribute__((aligned)) can increase or decrease alignment
1635 // *except* on a struct or struct member, where it only increases
1636 // alignment unless 'packed' is also specified.
1637 //
1638 // It is an error for alignas to decrease alignment, so we can
1639 // ignore that possibility; Sema should diagnose it.
1640 if (isa<FieldDecl>(D)) {
1641 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1642 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1643 } else {
1644 UseAlignAttrOnly = true;
1645 }
1646 }
1647 else if (isa<FieldDecl>(D))
1648 UseAlignAttrOnly =
1649 D->hasAttr<PackedAttr>() ||
1650 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1651
1652 // If we're using the align attribute only, just ignore everything
1653 // else about the declaration and its type.
1654 if (UseAlignAttrOnly) {
1655 // do nothing
1656 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1657 QualType T = VD->getType();
1658 if (const auto *RT = T->getAs<ReferenceType>()) {
1659 if (ForAlignof)
1660 T = RT->getPointeeType();
1661 else
1662 T = getPointerType(RT->getPointeeType());
1663 }
1664 QualType BaseT = getBaseElementType(T);
1665 if (T->isFunctionType())
1666 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1667 else if (!BaseT->isIncompleteType()) {
1668 // Adjust alignments of declarations with array type by the
1669 // large-array alignment on the target.
1670 if (const ArrayType *arrayType = getAsArrayType(T)) {
1671 unsigned MinWidth = Target->getLargeArrayMinWidth();
1672 if (!ForAlignof && MinWidth) {
1673 if (isa<VariableArrayType>(arrayType))
1674 Align = std::max(Align, Target->getLargeArrayAlign());
1675 else if (isa<ConstantArrayType>(arrayType) &&
1676 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1677 Align = std::max(Align, Target->getLargeArrayAlign());
1678 }
1679 }
1680 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1681 if (BaseT.getQualifiers().hasUnaligned())
1682 Align = Target->getCharWidth();
1683 if (const auto *VD = dyn_cast<VarDecl>(D)) {
1684 if (VD->hasGlobalStorage() && !ForAlignof) {
1685 uint64_t TypeSize = getTypeSize(T.getTypePtr());
1686 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1687 }
1688 }
1689 }
1690
1691 // Fields can be subject to extra alignment constraints, like if
1692 // the field is packed, the struct is packed, or the struct has a
1693 // a max-field-alignment constraint (#pragma pack). So calculate
1694 // the actual alignment of the field within the struct, and then
1695 // (as we're expected to) constrain that by the alignment of the type.
1696 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1697 const RecordDecl *Parent = Field->getParent();
1698 // We can only produce a sensible answer if the record is valid.
1699 if (!Parent->isInvalidDecl()) {
1700 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1701
1702 // Start with the record's overall alignment.
1703 unsigned FieldAlign = toBits(Layout.getAlignment());
1704
1705 // Use the GCD of that and the offset within the record.
1706 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1707 if (Offset > 0) {
1708 // Alignment is always a power of 2, so the GCD will be a power of 2,
1709 // which means we get to do this crazy thing instead of Euclid's.
1710 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1711 if (LowBitOfOffset < FieldAlign)
1712 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1713 }
1714
1715 Align = std::min(Align, FieldAlign);
1716 }
1717 }
1718 }
1719
1720 return toCharUnitsFromBits(Align);
1721}
1722
1723// getTypeInfoDataSizeInChars - Return the size of a type, in
1724// chars. If the type is a record, its data size is returned. This is
1725// the size of the memcpy that's performed when assigning this type
1726// using a trivial copy/move assignment operator.
1727std::pair<CharUnits, CharUnits>
1728ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1729 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1730
1731 // In C++, objects can sometimes be allocated into the tail padding
1732 // of a base-class subobject. We decide whether that's possible
1733 // during class layout, so here we can just trust the layout results.
1734 if (getLangOpts().CPlusPlus) {
1735 if (const auto *RT = T->getAs<RecordType>()) {
1736 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1737 sizeAndAlign.first = layout.getDataSize();
1738 }
1739 }
1740
1741 return sizeAndAlign;
1742}
1743
1744/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1745/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1746std::pair<CharUnits, CharUnits>
1747static getConstantArrayInfoInChars(const ASTContext &Context,
1748 const ConstantArrayType *CAT) {
1749 std::pair<CharUnits, CharUnits> EltInfo =
1750 Context.getTypeInfoInChars(CAT->getElementType());
1751 uint64_t Size = CAT->getSize().getZExtValue();
1752 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=(((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity
()) <= (uint64_t)(-1)/Size) && "Overflow in array type char size evaluation"
) ? static_cast<void> (0) : __assert_fail ("(Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <= (uint64_t)(-1)/Size) && \"Overflow in array type char size evaluation\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1754, __PRETTY_FUNCTION__))
1753 (uint64_t)(-1)/Size) &&(((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity
()) <= (uint64_t)(-1)/Size) && "Overflow in array type char size evaluation"
) ? static_cast<void> (0) : __assert_fail ("(Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <= (uint64_t)(-1)/Size) && \"Overflow in array type char size evaluation\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1754, __PRETTY_FUNCTION__))
1754 "Overflow in array type char size evaluation")(((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity
()) <= (uint64_t)(-1)/Size) && "Overflow in array type char size evaluation"
) ? static_cast<void> (0) : __assert_fail ("(Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <= (uint64_t)(-1)/Size) && \"Overflow in array type char size evaluation\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1754, __PRETTY_FUNCTION__))
;
1755 uint64_t Width = EltInfo.first.getQuantity() * Size;
1756 unsigned Align = EltInfo.second.getQuantity();
1757 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1758 Context.getTargetInfo().getPointerWidth(0) == 64)
1759 Width = llvm::alignTo(Width, Align);
1760 return std::make_pair(CharUnits::fromQuantity(Width),
1761 CharUnits::fromQuantity(Align));
1762}
1763
1764std::pair<CharUnits, CharUnits>
1765ASTContext::getTypeInfoInChars(const Type *T) const {
1766 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1767 return getConstantArrayInfoInChars(*this, CAT);
1768 TypeInfo Info = getTypeInfo(T);
1769 return std::make_pair(toCharUnitsFromBits(Info.Width),
1770 toCharUnitsFromBits(Info.Align));
1771}
1772
1773std::pair<CharUnits, CharUnits>
1774ASTContext::getTypeInfoInChars(QualType T) const {
1775 return getTypeInfoInChars(T.getTypePtr());
1776}
1777
1778bool ASTContext::isAlignmentRequired(const Type *T) const {
1779 return getTypeInfo(T).AlignIsRequired;
1780}
1781
1782bool ASTContext::isAlignmentRequired(QualType T) const {
1783 return isAlignmentRequired(T.getTypePtr());
1784}
1785
1786unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1787 // An alignment on a typedef overrides anything else.
1788 if (const auto *TT = T->getAs<TypedefType>())
1789 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1790 return Align;
1791
1792 // If we have an (array of) complete type, we're done.
1793 T = getBaseElementType(T);
1794 if (!T->isIncompleteType())
1795 return getTypeAlign(T);
1796
1797 // If we had an array type, its element type might be a typedef
1798 // type with an alignment attribute.
1799 if (const auto *TT = T->getAs<TypedefType>())
1800 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1801 return Align;
1802
1803 // Otherwise, see if the declaration of the type had an attribute.
1804 if (const auto *TT = T->getAs<TagType>())
1805 return TT->getDecl()->getMaxAlignment();
1806
1807 return 0;
1808}
1809
1810TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1811 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1812 if (I != MemoizedTypeInfo.end())
1813 return I->second;
1814
1815 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1816 TypeInfo TI = getTypeInfoImpl(T);
1817 MemoizedTypeInfo[T] = TI;
1818 return TI;
1819}
1820
1821/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1822/// method does not work on incomplete types.
1823///
1824/// FIXME: Pointers into different addr spaces could have different sizes and
1825/// alignment requirements: getPointerInfo should take an AddrSpace, this
1826/// should take a QualType, &c.
1827TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1828 uint64_t Width = 0;
1829 unsigned Align = 8;
1830 bool AlignIsRequired = false;
1831 unsigned AS = 0;
1832 switch (T->getTypeClass()) {
1833#define TYPE(Class, Base)
1834#define ABSTRACT_TYPE(Class, Base)
1835#define NON_CANONICAL_TYPE(Class, Base)
1836#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1837#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1838 case Type::Class: \
1839 assert(!T->isDependentType() && "should not see dependent types here")((!T->isDependentType() && "should not see dependent types here"
) ? static_cast<void> (0) : __assert_fail ("!T->isDependentType() && \"should not see dependent types here\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1839, __PRETTY_FUNCTION__))
; \
1840 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1841#include "clang/AST/TypeNodes.inc"
1842 llvm_unreachable("Should not see dependent types")::llvm::llvm_unreachable_internal("Should not see dependent types"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1842)
;
1843
1844 case Type::FunctionNoProto:
1845 case Type::FunctionProto:
1846 // GCC extension: alignof(function) = 32 bits
1847 Width = 0;
1848 Align = 32;
1849 break;
1850
1851 case Type::IncompleteArray:
1852 case Type::VariableArray:
1853 Width = 0;
1854 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1855 break;
1856
1857 case Type::ConstantArray: {
1858 const auto *CAT = cast<ConstantArrayType>(T);
1859
1860 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1861 uint64_t Size = CAT->getSize().getZExtValue();
1862 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&(((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
"Overflow in array type bit size evaluation") ? static_cast<
void> (0) : __assert_fail ("(Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && \"Overflow in array type bit size evaluation\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1863, __PRETTY_FUNCTION__))
1863 "Overflow in array type bit size evaluation")(((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
"Overflow in array type bit size evaluation") ? static_cast<
void> (0) : __assert_fail ("(Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && \"Overflow in array type bit size evaluation\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1863, __PRETTY_FUNCTION__))
;
1864 Width = EltInfo.Width * Size;
1865 Align = EltInfo.Align;
1866 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1867 getTargetInfo().getPointerWidth(0) == 64)
1868 Width = llvm::alignTo(Width, Align);
1869 break;
1870 }
1871 case Type::ExtVector:
1872 case Type::Vector: {
1873 const auto *VT = cast<VectorType>(T);
1874 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1875 Width = EltInfo.Width * VT->getNumElements();
1876 Align = Width;
1877 // If the alignment is not a power of 2, round up to the next power of 2.
1878 // This happens for non-power-of-2 length vectors.
1879 if (Align & (Align-1)) {
1880 Align = llvm::NextPowerOf2(Align);
1881 Width = llvm::alignTo(Width, Align);
1882 }
1883 // Adjust the alignment based on the target max.
1884 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1885 if (TargetVectorAlign && TargetVectorAlign < Align)
1886 Align = TargetVectorAlign;
1887 break;
1888 }
1889
1890 case Type::Builtin:
1891 switch (cast<BuiltinType>(T)->getKind()) {
1892 default: llvm_unreachable("Unknown builtin type!")::llvm::llvm_unreachable_internal("Unknown builtin type!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1892)
;
1893 case BuiltinType::Void:
1894 // GCC extension: alignof(void) = 8 bits.
1895 Width = 0;
1896 Align = 8;
1897 break;
1898 case BuiltinType::Bool:
1899 Width = Target->getBoolWidth();
1900 Align = Target->getBoolAlign();
1901 break;
1902 case BuiltinType::Char_S:
1903 case BuiltinType::Char_U:
1904 case BuiltinType::UChar:
1905 case BuiltinType::SChar:
1906 case BuiltinType::Char8:
1907 Width = Target->getCharWidth();
1908 Align = Target->getCharAlign();
1909 break;
1910 case BuiltinType::WChar_S:
1911 case BuiltinType::WChar_U:
1912 Width = Target->getWCharWidth();
1913 Align = Target->getWCharAlign();
1914 break;
1915 case BuiltinType::Char16:
1916 Width = Target->getChar16Width();
1917 Align = Target->getChar16Align();
1918 break;
1919 case BuiltinType::Char32:
1920 Width = Target->getChar32Width();
1921 Align = Target->getChar32Align();
1922 break;
1923 case BuiltinType::UShort:
1924 case BuiltinType::Short:
1925 Width = Target->getShortWidth();
1926 Align = Target->getShortAlign();
1927 break;
1928 case BuiltinType::UInt:
1929 case BuiltinType::Int:
1930 Width = Target->getIntWidth();
1931 Align = Target->getIntAlign();
1932 break;
1933 case BuiltinType::ULong:
1934 case BuiltinType::Long:
1935 Width = Target->getLongWidth();
1936 Align = Target->getLongAlign();
1937 break;
1938 case BuiltinType::ULongLong:
1939 case BuiltinType::LongLong:
1940 Width = Target->getLongLongWidth();
1941 Align = Target->getLongLongAlign();
1942 break;
1943 case BuiltinType::Int128:
1944 case BuiltinType::UInt128:
1945 Width = 128;
1946 Align = 128; // int128_t is 128-bit aligned on all targets.
1947 break;
1948 case BuiltinType::ShortAccum:
1949 case BuiltinType::UShortAccum:
1950 case BuiltinType::SatShortAccum:
1951 case BuiltinType::SatUShortAccum:
1952 Width = Target->getShortAccumWidth();
1953 Align = Target->getShortAccumAlign();
1954 break;
1955 case BuiltinType::Accum:
1956 case BuiltinType::UAccum:
1957 case BuiltinType::SatAccum:
1958 case BuiltinType::SatUAccum:
1959 Width = Target->getAccumWidth();
1960 Align = Target->getAccumAlign();
1961 break;
1962 case BuiltinType::LongAccum:
1963 case BuiltinType::ULongAccum:
1964 case BuiltinType::SatLongAccum:
1965 case BuiltinType::SatULongAccum:
1966 Width = Target->getLongAccumWidth();
1967 Align = Target->getLongAccumAlign();
1968 break;
1969 case BuiltinType::ShortFract:
1970 case BuiltinType::UShortFract:
1971 case BuiltinType::SatShortFract:
1972 case BuiltinType::SatUShortFract:
1973 Width = Target->getShortFractWidth();
1974 Align = Target->getShortFractAlign();
1975 break;
1976 case BuiltinType::Fract:
1977 case BuiltinType::UFract:
1978 case BuiltinType::SatFract:
1979 case BuiltinType::SatUFract:
1980 Width = Target->getFractWidth();
1981 Align = Target->getFractAlign();
1982 break;
1983 case BuiltinType::LongFract:
1984 case BuiltinType::ULongFract:
1985 case BuiltinType::SatLongFract:
1986 case BuiltinType::SatULongFract:
1987 Width = Target->getLongFractWidth();
1988 Align = Target->getLongFractAlign();
1989 break;
1990 case BuiltinType::Float16:
1991 case BuiltinType::Half:
1992 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
1993 !getLangOpts().OpenMPIsDevice) {
1994 Width = Target->getHalfWidth();
1995 Align = Target->getHalfAlign();
1996 } else {
1997 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&((getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice
&& "Expected OpenMP device compilation.") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1998, __PRETTY_FUNCTION__))
1998 "Expected OpenMP device compilation.")((getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice
&& "Expected OpenMP device compilation.") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 1998, __PRETTY_FUNCTION__))
;
1999 Width = AuxTarget->getHalfWidth();
2000 Align = AuxTarget->getHalfAlign();
2001 }
2002 break;
2003 case BuiltinType::Float:
2004 Width = Target->getFloatWidth();
2005 Align = Target->getFloatAlign();
2006 break;
2007 case BuiltinType::Double:
2008 Width = Target->getDoubleWidth();
2009 Align = Target->getDoubleAlign();
2010 break;
2011 case BuiltinType::LongDouble:
2012 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2013 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2014 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2015 Width = AuxTarget->getLongDoubleWidth();
2016 Align = AuxTarget->getLongDoubleAlign();
2017 } else {
2018 Width = Target->getLongDoubleWidth();
2019 Align = Target->getLongDoubleAlign();
2020 }
2021 break;
2022 case BuiltinType::Float128:
2023 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2024 !getLangOpts().OpenMPIsDevice) {
2025 Width = Target->getFloat128Width();
2026 Align = Target->getFloat128Align();
2027 } else {
2028 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&((getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice
&& "Expected OpenMP device compilation.") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2029, __PRETTY_FUNCTION__))
2029 "Expected OpenMP device compilation.")((getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice
&& "Expected OpenMP device compilation.") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2029, __PRETTY_FUNCTION__))
;
2030 Width = AuxTarget->getFloat128Width();
2031 Align = AuxTarget->getFloat128Align();
2032 }
2033 break;
2034 case BuiltinType::NullPtr:
2035 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2036 Align = Target->getPointerAlign(0); // == sizeof(void*)
2037 break;
2038 case BuiltinType::ObjCId:
2039 case BuiltinType::ObjCClass:
2040 case BuiltinType::ObjCSel:
2041 Width = Target->getPointerWidth(0);
2042 Align = Target->getPointerAlign(0);
2043 break;
2044 case BuiltinType::OCLSampler:
2045 case BuiltinType::OCLEvent:
2046 case BuiltinType::OCLClkEvent:
2047 case BuiltinType::OCLQueue:
2048 case BuiltinType::OCLReserveID:
2049#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2050 case BuiltinType::Id:
2051#include "clang/Basic/OpenCLImageTypes.def"
2052#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2053 case BuiltinType::Id:
2054#include "clang/Basic/OpenCLExtensionTypes.def"
2055 AS = getTargetAddressSpace(
2056 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
2057 Width = Target->getPointerWidth(AS);
2058 Align = Target->getPointerAlign(AS);
2059 break;
2060 // The SVE types are effectively target-specific. The length of an
2061 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2062 // of 128 bits. There is one predicate bit for each vector byte, so the
2063 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2064 //
2065 // Because the length is only known at runtime, we use a dummy value
2066 // of 0 for the static length. The alignment values are those defined
2067 // by the Procedure Call Standard for the Arm Architecture.
2068#define SVE_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, IsSigned, IsFP)\
2069 case BuiltinType::Id: \
2070 Width = 0; \
2071 Align = 128; \
2072 break;
2073#define SVE_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2074 case BuiltinType::Id: \
2075 Width = 0; \
2076 Align = 16; \
2077 break;
2078#include "clang/Basic/AArch64SVEACLETypes.def"
2079 }
2080 break;
2081 case Type::ObjCObjectPointer:
2082 Width = Target->getPointerWidth(0);
2083 Align = Target->getPointerAlign(0);
2084 break;
2085 case Type::BlockPointer:
2086 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
2087 Width = Target->getPointerWidth(AS);
2088 Align = Target->getPointerAlign(AS);
2089 break;
2090 case Type::LValueReference:
2091 case Type::RValueReference:
2092 // alignof and sizeof should never enter this code path here, so we go
2093 // the pointer route.
2094 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
2095 Width = Target->getPointerWidth(AS);
2096 Align = Target->getPointerAlign(AS);
2097 break;
2098 case Type::Pointer:
2099 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
2100 Width = Target->getPointerWidth(AS);
2101 Align = Target->getPointerAlign(AS);
2102 break;
2103 case Type::MemberPointer: {
2104 const auto *MPT = cast<MemberPointerType>(T);
2105 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2106 Width = MPI.Width;
2107 Align = MPI.Align;
2108 break;
2109 }
2110 case Type::Complex: {
2111 // Complex types have the same alignment as their elements, but twice the
2112 // size.
2113 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2114 Width = EltInfo.Width * 2;
2115 Align = EltInfo.Align;
2116 break;
2117 }
2118 case Type::ObjCObject:
2119 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2120 case Type::Adjusted:
2121 case Type::Decayed:
2122 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2123 case Type::ObjCInterface: {
2124 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2125 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2126 Width = toBits(Layout.getSize());
2127 Align = toBits(Layout.getAlignment());
2128 break;
2129 }
2130 case Type::Record:
2131 case Type::Enum: {
2132 const auto *TT = cast<TagType>(T);
2133
2134 if (TT->getDecl()->isInvalidDecl()) {
2135 Width = 8;
2136 Align = 8;
2137 break;
2138 }
2139
2140 if (const auto *ET = dyn_cast<EnumType>(TT)) {
2141 const EnumDecl *ED = ET->getDecl();
2142 TypeInfo Info =
2143 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2144 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2145 Info.Align = AttrAlign;
2146 Info.AlignIsRequired = true;
2147 }
2148 return Info;
2149 }
2150
2151 const auto *RT = cast<RecordType>(TT);
2152 const RecordDecl *RD = RT->getDecl();
2153 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2154 Width = toBits(Layout.getSize());
2155 Align = toBits(Layout.getAlignment());
2156 AlignIsRequired = RD->hasAttr<AlignedAttr>();
2157 break;
2158 }
2159
2160 case Type::SubstTemplateTypeParm:
2161 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2162 getReplacementType().getTypePtr());
2163
2164 case Type::Auto:
2165 case Type::DeducedTemplateSpecialization: {
2166 const auto *A = cast<DeducedType>(T);
2167 assert(!A->getDeducedType().isNull() &&((!A->getDeducedType().isNull() && "cannot request the size of an undeduced or dependent auto type"
) ? static_cast<void> (0) : __assert_fail ("!A->getDeducedType().isNull() && \"cannot request the size of an undeduced or dependent auto type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2168, __PRETTY_FUNCTION__))
2168 "cannot request the size of an undeduced or dependent auto type")((!A->getDeducedType().isNull() && "cannot request the size of an undeduced or dependent auto type"
) ? static_cast<void> (0) : __assert_fail ("!A->getDeducedType().isNull() && \"cannot request the size of an undeduced or dependent auto type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2168, __PRETTY_FUNCTION__))
;
2169 return getTypeInfo(A->getDeducedType().getTypePtr());
2170 }
2171
2172 case Type::Paren:
2173 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2174
2175 case Type::MacroQualified:
2176 return getTypeInfo(
2177 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2178
2179 case Type::ObjCTypeParam:
2180 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2181
2182 case Type::Typedef: {
2183 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
2184 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
2185 // If the typedef has an aligned attribute on it, it overrides any computed
2186 // alignment we have. This violates the GCC documentation (which says that
2187 // attribute(aligned) can only round up) but matches its implementation.
2188 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
2189 Align = AttrAlign;
2190 AlignIsRequired = true;
2191 } else {
2192 Align = Info.Align;
2193 AlignIsRequired = Info.AlignIsRequired;
2194 }
2195 Width = Info.Width;
2196 break;
2197 }
2198
2199 case Type::Elaborated:
2200 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2201
2202 case Type::Attributed:
2203 return getTypeInfo(
2204 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2205
2206 case Type::Atomic: {
2207 // Start with the base type information.
2208 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2209 Width = Info.Width;
2210 Align = Info.Align;
2211
2212 if (!Width) {
2213 // An otherwise zero-sized type should still generate an
2214 // atomic operation.
2215 Width = Target->getCharWidth();
2216 assert(Align)((Align) ? static_cast<void> (0) : __assert_fail ("Align"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2216, __PRETTY_FUNCTION__))
;
2217 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2218 // If the size of the type doesn't exceed the platform's max
2219 // atomic promotion width, make the size and alignment more
2220 // favorable to atomic operations:
2221
2222 // Round the size up to a power of 2.
2223 if (!llvm::isPowerOf2_64(Width))
2224 Width = llvm::NextPowerOf2(Width);
2225
2226 // Set the alignment equal to the size.
2227 Align = static_cast<unsigned>(Width);
2228 }
2229 }
2230 break;
2231
2232 case Type::Pipe:
2233 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2234 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
2235 break;
2236 }
2237
2238 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2")((llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"
) ? static_cast<void> (0) : __assert_fail ("llvm::isPowerOf2_32(Align) && \"Alignment must be power of 2\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2238, __PRETTY_FUNCTION__))
;
2239 return TypeInfo(Width, Align, AlignIsRequired);
2240}
2241
2242unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2243 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2244 if (I != MemoizedUnadjustedAlign.end())
2245 return I->second;
2246
2247 unsigned UnadjustedAlign;
2248 if (const auto *RT = T->getAs<RecordType>()) {
2249 const RecordDecl *RD = RT->getDecl();
2250 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2251 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2252 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2253 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2254 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2255 } else {
2256 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2257 }
2258
2259 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2260 return UnadjustedAlign;
2261}
2262
2263unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2264 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2265 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2266 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2267 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2268 getTargetInfo().getABI() == "elfv1-qpx" &&
2269 T->isSpecificBuiltinType(BuiltinType::Double))
2270 SimdAlign = 256;
2271 return SimdAlign;
2272}
2273
2274/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2275CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2276 return CharUnits::fromQuantity(BitSize / getCharWidth());
2277}
2278
2279/// toBits - Convert a size in characters to a size in characters.
2280int64_t ASTContext::toBits(CharUnits CharSize) const {
2281 return CharSize.getQuantity() * getCharWidth();
2282}
2283
2284/// getTypeSizeInChars - Return the size of the specified type, in characters.
2285/// This method does not work on incomplete types.
2286CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2287 return getTypeInfoInChars(T).first;
2288}
2289CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2290 return getTypeInfoInChars(T).first;
2291}
2292
2293/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2294/// characters. This method does not work on incomplete types.
2295CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2296 return toCharUnitsFromBits(getTypeAlign(T));
2297}
2298CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2299 return toCharUnitsFromBits(getTypeAlign(T));
2300}
2301
2302/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2303/// type, in characters, before alignment adustments. This method does
2304/// not work on incomplete types.
2305CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2306 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2307}
2308CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2309 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2310}
2311
2312/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2313/// type for the current target in bits. This can be different than the ABI
2314/// alignment in cases where it is beneficial for performance to overalign
2315/// a data type.
2316unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2317 TypeInfo TI = getTypeInfo(T);
2318 unsigned ABIAlign = TI.Align;
2319
2320 T = T->getBaseElementTypeUnsafe();
2321
2322 // The preferred alignment of member pointers is that of a pointer.
2323 if (T->isMemberPointerType())
2324 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2325
2326 if (!Target->allowsLargerPreferedTypeAlignment())
2327 return ABIAlign;
2328
2329 // Double and long long should be naturally aligned if possible.
2330 if (const auto *CT = T->getAs<ComplexType>())
2331 T = CT->getElementType().getTypePtr();
2332 if (const auto *ET = T->getAs<EnumType>())
2333 T = ET->getDecl()->getIntegerType().getTypePtr();
2334 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2335 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2336 T->isSpecificBuiltinType(BuiltinType::ULongLong))
2337 // Don't increase the alignment if an alignment attribute was specified on a
2338 // typedef declaration.
2339 if (!TI.AlignIsRequired)
2340 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2341
2342 return ABIAlign;
2343}
2344
2345/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2346/// for __attribute__((aligned)) on this target, to be used if no alignment
2347/// value is specified.
2348unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2349 return getTargetInfo().getDefaultAlignForAttributeAligned();
2350}
2351
2352/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2353/// to a global variable of the specified type.
2354unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2355 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2356 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
2357}
2358
2359/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2360/// should be given to a global variable of the specified type.
2361CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2362 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2363}
2364
2365CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2366 CharUnits Offset = CharUnits::Zero();
2367 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2368 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2369 Offset += Layout->getBaseClassOffset(Base);
2370 Layout = &getASTRecordLayout(Base);
2371 }
2372 return Offset;
2373}
2374
2375/// DeepCollectObjCIvars -
2376/// This routine first collects all declared, but not synthesized, ivars in
2377/// super class and then collects all ivars, including those synthesized for
2378/// current class. This routine is used for implementation of current class
2379/// when all ivars, declared and synthesized are known.
2380void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2381 bool leafClass,
2382 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2383 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2384 DeepCollectObjCIvars(SuperClass, false, Ivars);
2385 if (!leafClass) {
2386 for (const auto *I : OI->ivars())
2387 Ivars.push_back(I);
2388 } else {
2389 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2390 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2391 Iv= Iv->getNextIvar())
2392 Ivars.push_back(Iv);
2393 }
2394}
2395
2396/// CollectInheritedProtocols - Collect all protocols in current class and
2397/// those inherited by it.
2398void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2399 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2400 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2401 // We can use protocol_iterator here instead of
2402 // all_referenced_protocol_iterator since we are walking all categories.
2403 for (auto *Proto : OI->all_referenced_protocols()) {
2404 CollectInheritedProtocols(Proto, Protocols);
2405 }
2406
2407 // Categories of this Interface.
2408 for (const auto *Cat : OI->visible_categories())
2409 CollectInheritedProtocols(Cat, Protocols);
2410
2411 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2412 while (SD) {
2413 CollectInheritedProtocols(SD, Protocols);
2414 SD = SD->getSuperClass();
2415 }
2416 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2417 for (auto *Proto : OC->protocols()) {
2418 CollectInheritedProtocols(Proto, Protocols);
2419 }
2420 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2421 // Insert the protocol.
2422 if (!Protocols.insert(
2423 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2424 return;
2425
2426 for (auto *Proto : OP->protocols())
2427 CollectInheritedProtocols(Proto, Protocols);
2428 }
2429}
2430
2431static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2432 const RecordDecl *RD) {
2433 assert(RD->isUnion() && "Must be union type")((RD->isUnion() && "Must be union type") ? static_cast
<void> (0) : __assert_fail ("RD->isUnion() && \"Must be union type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2433, __PRETTY_FUNCTION__))
;
2434 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2435
2436 for (const auto *Field : RD->fields()) {
2437 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2438 return false;
2439 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2440 if (FieldSize != UnionSize)
2441 return false;
2442 }
2443 return !RD->field_empty();
2444}
2445
2446static bool isStructEmpty(QualType Ty) {
2447 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2448
2449 if (!RD->field_empty())
2450 return false;
2451
2452 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2453 return ClassDecl->isEmpty();
2454
2455 return true;
2456}
2457
2458static llvm::Optional<int64_t>
2459structHasUniqueObjectRepresentations(const ASTContext &Context,
2460 const RecordDecl *RD) {
2461 assert(!RD->isUnion() && "Must be struct/class type")((!RD->isUnion() && "Must be struct/class type") ?
static_cast<void> (0) : __assert_fail ("!RD->isUnion() && \"Must be struct/class type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2461, __PRETTY_FUNCTION__))
;
2462 const auto &Layout = Context.getASTRecordLayout(RD);
2463
2464 int64_t CurOffsetInBits = 0;
2465 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2466 if (ClassDecl->isDynamicClass())
2467 return llvm::None;
2468
2469 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2470 for (const auto &Base : ClassDecl->bases()) {
2471 // Empty types can be inherited from, and non-empty types can potentially
2472 // have tail padding, so just make sure there isn't an error.
2473 if (!isStructEmpty(Base.getType())) {
2474 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2475 Context, Base.getType()->castAs<RecordType>()->getDecl());
2476 if (!Size)
2477 return llvm::None;
2478 Bases.emplace_back(Base.getType(), Size.getValue());
2479 }
2480 }
2481
2482 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2483 const std::pair<QualType, int64_t> &R) {
2484 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2485 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2486 });
2487
2488 for (const auto &Base : Bases) {
2489 int64_t BaseOffset = Context.toBits(
2490 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2491 int64_t BaseSize = Base.second;
2492 if (BaseOffset != CurOffsetInBits)
2493 return llvm::None;
2494 CurOffsetInBits = BaseOffset + BaseSize;
2495 }
2496 }
2497
2498 for (const auto *Field : RD->fields()) {
2499 if (!Field->getType()->isReferenceType() &&
2500 !Context.hasUniqueObjectRepresentations(Field->getType()))
2501 return llvm::None;
2502
2503 int64_t FieldSizeInBits =
2504 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2505 if (Field->isBitField()) {
2506 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2507
2508 if (BitfieldSize > FieldSizeInBits)
2509 return llvm::None;
2510 FieldSizeInBits = BitfieldSize;
2511 }
2512
2513 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2514
2515 if (FieldOffsetInBits != CurOffsetInBits)
2516 return llvm::None;
2517
2518 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2519 }
2520
2521 return CurOffsetInBits;
2522}
2523
2524bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2525 // C++17 [meta.unary.prop]:
2526 // The predicate condition for a template specialization
2527 // has_unique_object_representations<T> shall be
2528 // satisfied if and only if:
2529 // (9.1) - T is trivially copyable, and
2530 // (9.2) - any two objects of type T with the same value have the same
2531 // object representation, where two objects
2532 // of array or non-union class type are considered to have the same value
2533 // if their respective sequences of
2534 // direct subobjects have the same values, and two objects of union type
2535 // are considered to have the same
2536 // value if they have the same active member and the corresponding members
2537 // have the same value.
2538 // The set of scalar types for which this condition holds is
2539 // implementation-defined. [ Note: If a type has padding
2540 // bits, the condition does not hold; otherwise, the condition holds true
2541 // for unsigned integral types. -- end note ]
2542 assert(!Ty.isNull() && "Null QualType sent to unique object rep check")((!Ty.isNull() && "Null QualType sent to unique object rep check"
) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"Null QualType sent to unique object rep check\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2542, __PRETTY_FUNCTION__))
;
2543
2544 // Arrays are unique only if their element type is unique.
2545 if (Ty->isArrayType())
2546 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2547
2548 // (9.1) - T is trivially copyable...
2549 if (!Ty.isTriviallyCopyableType(*this))
2550 return false;
2551
2552 // All integrals and enums are unique.
2553 if (Ty->isIntegralOrEnumerationType())
2554 return true;
2555
2556 // All other pointers are unique.
2557 if (Ty->isPointerType())
2558 return true;
2559
2560 if (Ty->isMemberPointerType()) {
2561 const auto *MPT = Ty->getAs<MemberPointerType>();
2562 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2563 }
2564
2565 if (Ty->isRecordType()) {
2566 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2567
2568 if (Record->isInvalidDecl())
2569 return false;
2570
2571 if (Record->isUnion())
2572 return unionHasUniqueObjectRepresentations(*this, Record);
2573
2574 Optional<int64_t> StructSize =
2575 structHasUniqueObjectRepresentations(*this, Record);
2576
2577 return StructSize &&
2578 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2579 }
2580
2581 // FIXME: More cases to handle here (list by rsmith):
2582 // vectors (careful about, eg, vector of 3 foo)
2583 // _Complex int and friends
2584 // _Atomic T
2585 // Obj-C block pointers
2586 // Obj-C object pointers
2587 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2588 // clk_event_t, queue_t, reserve_id_t)
2589 // There're also Obj-C class types and the Obj-C selector type, but I think it
2590 // makes sense for those to return false here.
2591
2592 return false;
2593}
2594
2595unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2596 unsigned count = 0;
2597 // Count ivars declared in class extension.
2598 for (const auto *Ext : OI->known_extensions())
2599 count += Ext->ivar_size();
2600
2601 // Count ivar defined in this class's implementation. This
2602 // includes synthesized ivars.
2603 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2604 count += ImplDecl->ivar_size();
2605
2606 return count;
2607}
2608
2609bool ASTContext::isSentinelNullExpr(const Expr *E) {
2610 if (!E)
2611 return false;
2612
2613 // nullptr_t is always treated as null.
2614 if (E->getType()->isNullPtrType()) return true;
2615
2616 if (E->getType()->isAnyPointerType() &&
2617 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2618 Expr::NPC_ValueDependentIsNull))
2619 return true;
2620
2621 // Unfortunately, __null has type 'int'.
2622 if (isa<GNUNullExpr>(E)) return true;
2623
2624 return false;
2625}
2626
2627/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2628/// exists.
2629ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2630 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2631 I = ObjCImpls.find(D);
2632 if (I != ObjCImpls.end())
2633 return cast<ObjCImplementationDecl>(I->second);
2634 return nullptr;
2635}
2636
2637/// Get the implementation of ObjCCategoryDecl, or nullptr if none
2638/// exists.
2639ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2640 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2641 I = ObjCImpls.find(D);
2642 if (I != ObjCImpls.end())
2643 return cast<ObjCCategoryImplDecl>(I->second);
2644 return nullptr;
2645}
2646
2647/// Set the implementation of ObjCInterfaceDecl.
2648void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2649 ObjCImplementationDecl *ImplD) {
2650 assert(IFaceD && ImplD && "Passed null params")((IFaceD && ImplD && "Passed null params") ? static_cast
<void> (0) : __assert_fail ("IFaceD && ImplD && \"Passed null params\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2650, __PRETTY_FUNCTION__))
;
2651 ObjCImpls[IFaceD] = ImplD;
2652}
2653
2654/// Set the implementation of ObjCCategoryDecl.
2655void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2656 ObjCCategoryImplDecl *ImplD) {
2657 assert(CatD && ImplD && "Passed null params")((CatD && ImplD && "Passed null params") ? static_cast
<void> (0) : __assert_fail ("CatD && ImplD && \"Passed null params\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2657, __PRETTY_FUNCTION__))
;
2658 ObjCImpls[CatD] = ImplD;
2659}
2660
2661const ObjCMethodDecl *
2662ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2663 return ObjCMethodRedecls.lookup(MD);
2664}
2665
2666void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2667 const ObjCMethodDecl *Redecl) {
2668 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration")((!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"
) ? static_cast<void> (0) : __assert_fail ("!getObjCMethodRedeclaration(MD) && \"MD already has a redeclaration\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2668, __PRETTY_FUNCTION__))
;
2669 ObjCMethodRedecls[MD] = Redecl;
2670}
2671
2672const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2673 const NamedDecl *ND) const {
2674 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2675 return ID;
2676 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2677 return CD->getClassInterface();
2678 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2679 return IMD->getClassInterface();
2680
2681 return nullptr;
2682}
2683
2684/// Get the copy initialization expression of VarDecl, or nullptr if
2685/// none exists.
2686BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
2687 assert(VD && "Passed null params")((VD && "Passed null params") ? static_cast<void>
(0) : __assert_fail ("VD && \"Passed null params\"",
"/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2687, __PRETTY_FUNCTION__))
;
2688 assert(VD->hasAttr<BlocksAttr>() &&((VD->hasAttr<BlocksAttr>() && "getBlockVarCopyInits - not __block var"
) ? static_cast<void> (0) : __assert_fail ("VD->hasAttr<BlocksAttr>() && \"getBlockVarCopyInits - not __block var\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2689, __PRETTY_FUNCTION__))
2689 "getBlockVarCopyInits - not __block var")((VD->hasAttr<BlocksAttr>() && "getBlockVarCopyInits - not __block var"
) ? static_cast<void> (0) : __assert_fail ("VD->hasAttr<BlocksAttr>() && \"getBlockVarCopyInits - not __block var\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2689, __PRETTY_FUNCTION__))
;
2690 auto I = BlockVarCopyInits.find(VD);
2691 if (I != BlockVarCopyInits.end())
2692 return I->second;
2693 return {nullptr, false};
2694}
2695
2696/// Set the copy initialization expression of a block var decl.
2697void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2698 bool CanThrow) {
2699 assert(VD && CopyExpr && "Passed null params")((VD && CopyExpr && "Passed null params") ? static_cast
<void> (0) : __assert_fail ("VD && CopyExpr && \"Passed null params\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2699, __PRETTY_FUNCTION__))
;
2700 assert(VD->hasAttr<BlocksAttr>() &&((VD->hasAttr<BlocksAttr>() && "setBlockVarCopyInits - not __block var"
) ? static_cast<void> (0) : __assert_fail ("VD->hasAttr<BlocksAttr>() && \"setBlockVarCopyInits - not __block var\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2701, __PRETTY_FUNCTION__))
2701 "setBlockVarCopyInits - not __block var")((VD->hasAttr<BlocksAttr>() && "setBlockVarCopyInits - not __block var"
) ? static_cast<void> (0) : __assert_fail ("VD->hasAttr<BlocksAttr>() && \"setBlockVarCopyInits - not __block var\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2701, __PRETTY_FUNCTION__))
;
2702 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2703}
2704
2705TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2706 unsigned DataSize) const {
2707 if (!DataSize)
2708 DataSize = TypeLoc::getFullDataSizeForType(T);
2709 else
2710 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&((DataSize == TypeLoc::getFullDataSizeForType(T) && "incorrect data size provided to CreateTypeSourceInfo!"
) ? static_cast<void> (0) : __assert_fail ("DataSize == TypeLoc::getFullDataSizeForType(T) && \"incorrect data size provided to CreateTypeSourceInfo!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2711, __PRETTY_FUNCTION__))
2711 "incorrect data size provided to CreateTypeSourceInfo!")((DataSize == TypeLoc::getFullDataSizeForType(T) && "incorrect data size provided to CreateTypeSourceInfo!"
) ? static_cast<void> (0) : __assert_fail ("DataSize == TypeLoc::getFullDataSizeForType(T) && \"incorrect data size provided to CreateTypeSourceInfo!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2711, __PRETTY_FUNCTION__))
;
2712
2713 auto *TInfo =
2714 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2715 new (TInfo) TypeSourceInfo(T);
2716 return TInfo;
2717}
2718
2719TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2720 SourceLocation L) const {
2721 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2722 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2723 return DI;
2724}
2725
2726const ASTRecordLayout &
2727ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2728 return getObjCLayout(D, nullptr);
2729}
2730
2731const ASTRecordLayout &
2732ASTContext::getASTObjCImplementationLayout(
2733 const ObjCImplementationDecl *D) const {
2734 return getObjCLayout(D->getClassInterface(), D);
2735}
2736
2737//===----------------------------------------------------------------------===//
2738// Type creation/memoization methods
2739//===----------------------------------------------------------------------===//
2740
2741QualType
2742ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2743 unsigned fastQuals = quals.getFastQualifiers();
2744 quals.removeFastQualifiers();
2745
2746 // Check if we've already instantiated this type.
2747 llvm::FoldingSetNodeID ID;
2748 ExtQuals::Profile(ID, baseType, quals);
2749 void *insertPos = nullptr;
2750 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2751 assert(eq->getQualifiers() == quals)((eq->getQualifiers() == quals) ? static_cast<void> (
0) : __assert_fail ("eq->getQualifiers() == quals", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2751, __PRETTY_FUNCTION__))
;
2752 return QualType(eq, fastQuals);
2753 }
2754
2755 // If the base type is not canonical, make the appropriate canonical type.
2756 QualType canon;
2757 if (!baseType->isCanonicalUnqualified()) {
2758 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2759 canonSplit.Quals.addConsistentQualifiers(quals);
2760 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2761
2762 // Re-find the insert position.
2763 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2764 }
2765
2766 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2767 ExtQualNodes.InsertNode(eq, insertPos);
2768 return QualType(eq, fastQuals);
2769}
2770
2771QualType ASTContext::getAddrSpaceQualType(QualType T,
2772 LangAS AddressSpace) const {
2773 QualType CanT = getCanonicalType(T);
2774 if (CanT.getAddressSpace() == AddressSpace)
2775 return T;
2776
2777 // If we are composing extended qualifiers together, merge together
2778 // into one ExtQuals node.
2779 QualifierCollector Quals;
2780 const Type *TypeNode = Quals.strip(T);
2781
2782 // If this type already has an address space specified, it cannot get
2783 // another one.
2784 assert(!Quals.hasAddressSpace() &&((!Quals.hasAddressSpace() && "Type cannot be in multiple addr spaces!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasAddressSpace() && \"Type cannot be in multiple addr spaces!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2785, __PRETTY_FUNCTION__))
2785 "Type cannot be in multiple addr spaces!")((!Quals.hasAddressSpace() && "Type cannot be in multiple addr spaces!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasAddressSpace() && \"Type cannot be in multiple addr spaces!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2785, __PRETTY_FUNCTION__))
;
2786 Quals.addAddressSpace(AddressSpace);
2787
2788 return getExtQualType(TypeNode, Quals);
2789}
2790
2791QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2792 // If we are composing extended qualifiers together, merge together
2793 // into one ExtQuals node.
2794 QualifierCollector Quals;
2795 const Type *TypeNode = Quals.strip(T);
2796
2797 // If the qualifier doesn't have an address space just return it.
2798 if (!Quals.hasAddressSpace())
2799 return T;
2800
2801 Quals.removeAddressSpace();
2802
2803 // Removal of the address space can mean there are no longer any
2804 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2805 // or required.
2806 if (Quals.hasNonFastQualifiers())
2807 return getExtQualType(TypeNode, Quals);
2808 else
2809 return QualType(TypeNode, Quals.getFastQualifiers());
2810}
2811
2812QualType ASTContext::getObjCGCQualType(QualType T,
2813 Qualifiers::GC GCAttr) const {
2814 QualType CanT = getCanonicalType(T);
2815 if (CanT.getObjCGCAttr() == GCAttr)
2816 return T;
2817
2818 if (const auto *ptr = T->getAs<PointerType>()) {
2819 QualType Pointee = ptr->getPointeeType();
2820 if (Pointee->isAnyPointerType()) {
2821 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2822 return getPointerType(ResultType);
2823 }
2824 }
2825
2826 // If we are composing extended qualifiers together, merge together
2827 // into one ExtQuals node.
2828 QualifierCollector Quals;
2829 const Type *TypeNode = Quals.strip(T);
2830
2831 // If this type already has an ObjCGC specified, it cannot get
2832 // another one.
2833 assert(!Quals.hasObjCGCAttr() &&((!Quals.hasObjCGCAttr() && "Type cannot have multiple ObjCGCs!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasObjCGCAttr() && \"Type cannot have multiple ObjCGCs!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2834, __PRETTY_FUNCTION__))
2834 "Type cannot have multiple ObjCGCs!")((!Quals.hasObjCGCAttr() && "Type cannot have multiple ObjCGCs!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasObjCGCAttr() && \"Type cannot have multiple ObjCGCs!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2834, __PRETTY_FUNCTION__))
;
2835 Quals.addObjCGCAttr(GCAttr);
2836
2837 return getExtQualType(TypeNode, Quals);
2838}
2839
2840QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
2841 if (const PointerType *Ptr = T->getAs<PointerType>()) {
2842 QualType Pointee = Ptr->getPointeeType();
2843 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
2844 return getPointerType(removeAddrSpaceQualType(Pointee));
2845 }
2846 }
2847 return T;
2848}
2849
2850const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2851 FunctionType::ExtInfo Info) {
2852 if (T->getExtInfo() == Info)
2853 return T;
2854
2855 QualType Result;
2856 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2857 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2858 } else {
2859 const auto *FPT = cast<FunctionProtoType>(T);
2860 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2861 EPI.ExtInfo = Info;
2862 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2863 }
2864
2865 return cast<FunctionType>(Result.getTypePtr());
2866}
2867
2868void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2869 QualType ResultType) {
2870 FD = FD->getMostRecentDecl();
2871 while (true) {
2872 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
2873 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2874 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2875 if (FunctionDecl *Next = FD->getPreviousDecl())
2876 FD = Next;
2877 else
2878 break;
2879 }
2880 if (ASTMutationListener *L = getASTMutationListener())
2881 L->DeducedReturnType(FD, ResultType);
2882}
2883
2884/// Get a function type and produce the equivalent function type with the
2885/// specified exception specification. Type sugar that can be present on a
2886/// declaration of a function with an exception specification is permitted
2887/// and preserved. Other type sugar (for instance, typedefs) is not.
2888QualType ASTContext::getFunctionTypeWithExceptionSpec(
2889 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
2890 // Might have some parens.
2891 if (const auto *PT = dyn_cast<ParenType>(Orig))
2892 return getParenType(
2893 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
2894
2895 // Might be wrapped in a macro qualified type.
2896 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
2897 return getMacroQualifiedType(
2898 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
2899 MQT->getMacroIdentifier());
2900
2901 // Might have a calling-convention attribute.
2902 if (const auto *AT = dyn_cast<AttributedType>(Orig))
2903 return getAttributedType(
2904 AT->getAttrKind(),
2905 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2906 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
2907
2908 // Anything else must be a function type. Rebuild it with the new exception
2909 // specification.
2910 const auto *Proto = Orig->castAs<FunctionProtoType>();
2911 return getFunctionType(
2912 Proto->getReturnType(), Proto->getParamTypes(),
2913 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2914}
2915
2916bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2917 QualType U) {
2918 return hasSameType(T, U) ||
2919 (getLangOpts().CPlusPlus17 &&
2920 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2921 getFunctionTypeWithExceptionSpec(U, EST_None)));
2922}
2923
2924QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
2925 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
2926 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
2927 SmallVector<QualType, 16> Args(Proto->param_types());
2928 for (unsigned i = 0, n = Args.size(); i != n; ++i)
2929 Args[i] = removePtrSizeAddrSpace(Args[i]);
2930 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
2931 }
2932
2933 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
2934 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
2935 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
2936 }
2937
2938 return T;
2939}
2940
2941bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
2942 return hasSameType(T, U) ||
2943 hasSameType(getFunctionTypeWithoutPtrSizes(T),
2944 getFunctionTypeWithoutPtrSizes(U));
2945}
2946
2947void ASTContext::adjustExceptionSpec(
2948 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2949 bool AsWritten) {
2950 // Update the type.
2951 QualType Updated =
2952 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
2953 FD->setType(Updated);
2954
2955 if (!AsWritten)
2956 return;
2957
2958 // Update the type in the type source information too.
2959 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2960 // If the type and the type-as-written differ, we may need to update
2961 // the type-as-written too.
2962 if (TSInfo->getType() != FD->getType())
2963 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
2964
2965 // FIXME: When we get proper type location information for exceptions,
2966 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2967 // up the TypeSourceInfo;
2968 assert(TypeLoc::getFullDataSizeForType(Updated) ==((TypeLoc::getFullDataSizeForType(Updated) == TypeLoc::getFullDataSizeForType
(TSInfo->getType()) && "TypeLoc size mismatch from updating exception specification"
) ? static_cast<void> (0) : __assert_fail ("TypeLoc::getFullDataSizeForType(Updated) == TypeLoc::getFullDataSizeForType(TSInfo->getType()) && \"TypeLoc size mismatch from updating exception specification\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2970, __PRETTY_FUNCTION__))
2969 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&((TypeLoc::getFullDataSizeForType(Updated) == TypeLoc::getFullDataSizeForType
(TSInfo->getType()) && "TypeLoc size mismatch from updating exception specification"
) ? static_cast<void> (0) : __assert_fail ("TypeLoc::getFullDataSizeForType(Updated) == TypeLoc::getFullDataSizeForType(TSInfo->getType()) && \"TypeLoc size mismatch from updating exception specification\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2970, __PRETTY_FUNCTION__))
2970 "TypeLoc size mismatch from updating exception specification")((TypeLoc::getFullDataSizeForType(Updated) == TypeLoc::getFullDataSizeForType
(TSInfo->getType()) && "TypeLoc size mismatch from updating exception specification"
) ? static_cast<void> (0) : __assert_fail ("TypeLoc::getFullDataSizeForType(Updated) == TypeLoc::getFullDataSizeForType(TSInfo->getType()) && \"TypeLoc size mismatch from updating exception specification\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2970, __PRETTY_FUNCTION__))
;
2971 TSInfo->overrideType(Updated);
2972 }
2973}
2974
2975/// getComplexType - Return the uniqued reference to the type for a complex
2976/// number with the specified element type.
2977QualType ASTContext::getComplexType(QualType T) const {
2978 // Unique pointers, to guarantee there is only one pointer of a particular
2979 // structure.
2980 llvm::FoldingSetNodeID ID;
2981 ComplexType::Profile(ID, T);
2982
2983 void *InsertPos = nullptr;
2984 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2985 return QualType(CT, 0);
2986
2987 // If the pointee type isn't canonical, this won't be a canonical type either,
2988 // so fill in the canonical type field.
2989 QualType Canonical;
2990 if (!T.isCanonical()) {
2991 Canonical = getComplexType(getCanonicalType(T));
2992
2993 // Get the new insert position for the node we care about.
2994 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2995 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 2995, __PRETTY_FUNCTION__))
; (void)NewIP;
2996 }
2997 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2998 Types.push_back(New);
2999 ComplexTypes.InsertNode(New, InsertPos);
3000 return QualType(New, 0);
3001}
3002
3003/// getPointerType - Return the uniqued reference to the type for a pointer to
3004/// the specified type.
3005QualType ASTContext::getPointerType(QualType T) const {
3006 // Unique pointers, to guarantee there is only one pointer of a particular
3007 // structure.
3008 llvm::FoldingSetNodeID ID;
3009 PointerType::Profile(ID, T);
3010
3011 void *InsertPos = nullptr;
3012 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3013 return QualType(PT, 0);
3014
3015 // If the pointee type isn't canonical, this won't be a canonical type either,
3016 // so fill in the canonical type field.
3017 QualType Canonical;
3018 if (!T.isCanonical()) {
3019 Canonical = getPointerType(getCanonicalType(T));
3020
3021 // Get the new insert position for the node we care about.
3022 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3023 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3023, __PRETTY_FUNCTION__))
; (void)NewIP;
3024 }
3025 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
3026 Types.push_back(New);
3027 PointerTypes.InsertNode(New, InsertPos);
3028 return QualType(New, 0);
3029}
3030
3031QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3032 llvm::FoldingSetNodeID ID;
3033 AdjustedType::Profile(ID, Orig, New);
3034 void *InsertPos = nullptr;
3035 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3036 if (AT)
3037 return QualType(AT, 0);
3038
3039 QualType Canonical = getCanonicalType(New);
3040
3041 // Get the new insert position for the node we care about.
3042 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3043 assert(!AT && "Shouldn't be in the map!")((!AT && "Shouldn't be in the map!") ? static_cast<
void> (0) : __assert_fail ("!AT && \"Shouldn't be in the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3043, __PRETTY_FUNCTION__))
;
3044
3045 AT = new (*this, TypeAlignment)
3046 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3047 Types.push_back(AT);
3048 AdjustedTypes.InsertNode(AT, InsertPos);
3049 return QualType(AT, 0);
3050}
3051
3052QualType ASTContext::getDecayedType(QualType T) const {
3053 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay")(((T->isArrayType() || T->isFunctionType()) && "T does not decay"
) ? static_cast<void> (0) : __assert_fail ("(T->isArrayType() || T->isFunctionType()) && \"T does not decay\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3053, __PRETTY_FUNCTION__))
;
3054
3055 QualType Decayed;
3056
3057 // C99 6.7.5.3p7:
3058 // A declaration of a parameter as "array of type" shall be
3059 // adjusted to "qualified pointer to type", where the type
3060 // qualifiers (if any) are those specified within the [ and ] of
3061 // the array type derivation.
3062 if (T->isArrayType())
3063 Decayed = getArrayDecayedType(T);
3064
3065 // C99 6.7.5.3p8:
3066 // A declaration of a parameter as "function returning type"
3067 // shall be adjusted to "pointer to function returning type", as
3068 // in 6.3.2.1.
3069 if (T->isFunctionType())
3070 Decayed = getPointerType(T);
3071
3072 llvm::FoldingSetNodeID ID;
3073 AdjustedType::Profile(ID, T, Decayed);
3074 void *InsertPos = nullptr;
3075 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3076 if (AT)
3077 return QualType(AT, 0);
3078
3079 QualType Canonical = getCanonicalType(Decayed);
3080
3081 // Get the new insert position for the node we care about.
3082 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3083 assert(!AT && "Shouldn't be in the map!")((!AT && "Shouldn't be in the map!") ? static_cast<
void> (0) : __assert_fail ("!AT && \"Shouldn't be in the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3083, __PRETTY_FUNCTION__))
;
3084
3085 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3086 Types.push_back(AT);
3087 AdjustedTypes.InsertNode(AT, InsertPos);
3088 return QualType(AT, 0);
3089}
3090
3091/// getBlockPointerType - Return the uniqued reference to the type for
3092/// a pointer to the specified block.
3093QualType ASTContext::getBlockPointerType(QualType T) const {
3094 assert(T->isFunctionType() && "block of function types only")((T->isFunctionType() && "block of function types only"
) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"block of function types only\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3094, __PRETTY_FUNCTION__))
;
3095 // Unique pointers, to guarantee there is only one block of a particular
3096 // structure.
3097 llvm::FoldingSetNodeID ID;
3098 BlockPointerType::Profile(ID, T);
3099
3100 void *InsertPos = nullptr;
3101 if (BlockPointerType *PT =
3102 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3103 return QualType(PT, 0);
3104
3105 // If the block pointee type isn't canonical, this won't be a canonical
3106 // type either so fill in the canonical type field.
3107 QualType Canonical;
3108 if (!T.isCanonical()) {
3109 Canonical = getBlockPointerType(getCanonicalType(T));
3110
3111 // Get the new insert position for the node we care about.
3112 BlockPointerType *NewIP =
3113 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3114 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3114, __PRETTY_FUNCTION__))
; (void)NewIP;
3115 }
3116 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
3117 Types.push_back(New);
3118 BlockPointerTypes.InsertNode(New, InsertPos);
3119 return QualType(New, 0);
3120}
3121
3122/// getLValueReferenceType - Return the uniqued reference to the type for an
3123/// lvalue reference to the specified type.
3124QualType
3125ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3126 assert(getCanonicalType(T) != OverloadTy &&((getCanonicalType(T) != OverloadTy && "Unresolved overloaded function type"
) ? static_cast<void> (0) : __assert_fail ("getCanonicalType(T) != OverloadTy && \"Unresolved overloaded function type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3127, __PRETTY_FUNCTION__))
3127 "Unresolved overloaded function type")((getCanonicalType(T) != OverloadTy && "Unresolved overloaded function type"
) ? static_cast<void> (0) : __assert_fail ("getCanonicalType(T) != OverloadTy && \"Unresolved overloaded function type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3127, __PRETTY_FUNCTION__))
;
3128
3129 // Unique pointers, to guarantee there is only one pointer of a particular
3130 // structure.
3131 llvm::FoldingSetNodeID ID;
3132 ReferenceType::Profile(ID, T, SpelledAsLValue);
3133
3134 void *InsertPos = nullptr;
3135 if (LValueReferenceType *RT =
3136 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3137 return QualType(RT, 0);
3138
3139 const auto *InnerRef = T->getAs<ReferenceType>();
3140
3141 // If the referencee type isn't canonical, this won't be a canonical type
3142 // either, so fill in the canonical type field.
3143 QualType Canonical;
3144 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3145 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3146 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3147
3148 // Get the new insert position for the node we care about.
3149 LValueReferenceType *NewIP =
3150 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3151 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3151, __PRETTY_FUNCTION__))
; (void)NewIP;
3152 }
3153
3154 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3155 SpelledAsLValue);
3156 Types.push_back(New);
3157 LValueReferenceTypes.InsertNode(New, InsertPos);
3158
3159 return QualType(New, 0);
3160}
3161
3162/// getRValueReferenceType - Return the uniqued reference to the type for an
3163/// rvalue reference to the specified type.
3164QualType ASTContext::getRValueReferenceType(QualType T) const {
3165 // Unique pointers, to guarantee there is only one pointer of a particular
3166 // structure.
3167 llvm::FoldingSetNodeID ID;
3168 ReferenceType::Profile(ID, T, false);
3169
3170 void *InsertPos = nullptr;
3171 if (RValueReferenceType *RT =
3172 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3173 return QualType(RT, 0);
3174
3175 const auto *InnerRef = T->getAs<ReferenceType>();
3176
3177 // If the referencee type isn't canonical, this won't be a canonical type
3178 // either, so fill in the canonical type field.
3179 QualType Canonical;
3180 if (InnerRef || !T.isCanonical()) {
3181 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3182 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3183
3184 // Get the new insert position for the node we care about.
3185 RValueReferenceType *NewIP =
3186 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3187 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3187, __PRETTY_FUNCTION__))
; (void)NewIP;
3188 }
3189
3190 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
3191 Types.push_back(New);
3192 RValueReferenceTypes.InsertNode(New, InsertPos);
3193 return QualType(New, 0);
3194}
3195
3196/// getMemberPointerType - Return the uniqued reference to the type for a
3197/// member pointer to the specified type, in the specified class.
3198QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
3199 // Unique pointers, to guarantee there is only one pointer of a particular
3200 // structure.
3201 llvm::FoldingSetNodeID ID;
3202 MemberPointerType::Profile(ID, T, Cls);
3203
3204 void *InsertPos = nullptr;
3205 if (MemberPointerType *PT =
3206 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3207 return QualType(PT, 0);
3208
3209 // If the pointee or class type isn't canonical, this won't be a canonical
3210 // type either, so fill in the canonical type field.
3211 QualType Canonical;
3212 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3213 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3214
3215 // Get the new insert position for the node we care about.
3216 MemberPointerType *NewIP =
3217 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3218 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3218, __PRETTY_FUNCTION__))
; (void)NewIP;
3219 }
3220 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
3221 Types.push_back(New);
3222 MemberPointerTypes.InsertNode(New, InsertPos);
3223 return QualType(New, 0);
3224}
3225
3226/// getConstantArrayType - Return the unique reference to the type for an
3227/// array of the specified element type.
3228QualType ASTContext::getConstantArrayType(QualType EltTy,
3229 const llvm::APInt &ArySizeIn,
3230 const Expr *SizeExpr,
3231 ArrayType::ArraySizeModifier ASM,
3232 unsigned IndexTypeQuals) const {
3233 assert((EltTy->isDependentType() ||(((EltTy->isDependentType() || EltTy->isIncompleteType(
) || EltTy->isConstantSizeType()) && "Constant array of VLAs is illegal!"
) ? static_cast<void> (0) : __assert_fail ("(EltTy->isDependentType() || EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && \"Constant array of VLAs is illegal!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3235, __PRETTY_FUNCTION__))
3234 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&(((EltTy->isDependentType() || EltTy->isIncompleteType(
) || EltTy->isConstantSizeType()) && "Constant array of VLAs is illegal!"
) ? static_cast<void> (0) : __assert_fail ("(EltTy->isDependentType() || EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && \"Constant array of VLAs is illegal!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3235, __PRETTY_FUNCTION__))
3235 "Constant array of VLAs is illegal!")(((EltTy->isDependentType() || EltTy->isIncompleteType(
) || EltTy->isConstantSizeType()) && "Constant array of VLAs is illegal!"
) ? static_cast<void> (0) : __assert_fail ("(EltTy->isDependentType() || EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && \"Constant array of VLAs is illegal!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3235, __PRETTY_FUNCTION__))
;
3236
3237 // We only need the size as part of the type if it's instantiation-dependent.
3238 if (SizeExpr && !SizeExpr->isInstantiationDependent())
3239 SizeExpr = nullptr;
3240
3241 // Convert the array size into a canonical width matching the pointer size for
3242 // the target.
3243 llvm::APInt ArySize(ArySizeIn);
3244 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3245
3246 llvm::FoldingSetNodeID ID;
3247 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3248 IndexTypeQuals);
3249
3250 void *InsertPos = nullptr;
3251 if (ConstantArrayType *ATP =
3252 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3253 return QualType(ATP, 0);
3254
3255 // If the element type isn't canonical or has qualifiers, or the array bound
3256 // is instantiation-dependent, this won't be a canonical type either, so fill
3257 // in the canonical type field.
3258 QualType Canon;
3259 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3260 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3261 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3262 ASM, IndexTypeQuals);
3263 Canon = getQualifiedType(Canon, canonSplit.Quals);
3264
3265 // Get the new insert position for the node we care about.
3266 ConstantArrayType *NewIP =
3267 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3268 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3268, __PRETTY_FUNCTION__))
; (void)NewIP;
3269 }
3270
3271 void *Mem = Allocate(
3272 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3273 TypeAlignment);
3274 auto *New = new (Mem)
3275 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
3276 ConstantArrayTypes.InsertNode(New, InsertPos);
3277 Types.push_back(New);
3278 return QualType(New, 0);
3279}
3280
3281/// getVariableArrayDecayedType - Turns the given type, which may be
3282/// variably-modified, into the corresponding type with all the known
3283/// sizes replaced with [*].
3284QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3285 // Vastly most common case.
3286 if (!type->isVariablyModifiedType()) return type;
3287
3288 QualType result;
3289
3290 SplitQualType split = type.getSplitDesugaredType();
3291 const Type *ty = split.Ty;
3292 switch (ty->getTypeClass()) {
3293#define TYPE(Class, Base)
3294#define ABSTRACT_TYPE(Class, Base)
3295#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3296#include "clang/AST/TypeNodes.inc"
3297 llvm_unreachable("didn't desugar past all non-canonical types?")::llvm::llvm_unreachable_internal("didn't desugar past all non-canonical types?"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3297)
;
3298
3299 // These types should never be variably-modified.
3300 case Type::Builtin:
3301 case Type::Complex:
3302 case Type::Vector:
3303 case Type::DependentVector:
3304 case Type::ExtVector:
3305 case Type::DependentSizedExtVector:
3306 case Type::DependentAddressSpace:
3307 case Type::ObjCObject:
3308 case Type::ObjCInterface:
3309 case Type::ObjCObjectPointer:
3310 case Type::Record:
3311 case Type::Enum:
3312 case Type::UnresolvedUsing:
3313 case Type::TypeOfExpr:
3314 case Type::TypeOf:
3315 case Type::Decltype:
3316 case Type::UnaryTransform:
3317 case Type::DependentName:
3318 case Type::InjectedClassName:
3319 case Type::TemplateSpecialization:
3320 case Type::DependentTemplateSpecialization:
3321 case Type::TemplateTypeParm:
3322 case Type::SubstTemplateTypeParmPack:
3323 case Type::Auto:
3324 case Type::DeducedTemplateSpecialization:
3325 case Type::PackExpansion:
3326 llvm_unreachable("type should never be variably-modified")::llvm::llvm_unreachable_internal("type should never be variably-modified"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3326)
;
3327
3328 // These types can be variably-modified but should never need to
3329 // further decay.
3330 case Type::FunctionNoProto:
3331 case Type::FunctionProto:
3332 case Type::BlockPointer:
3333 case Type::MemberPointer:
3334 case Type::Pipe:
3335 return type;
3336
3337 // These types can be variably-modified. All these modifications
3338 // preserve structure except as noted by comments.
3339 // TODO: if we ever care about optimizing VLAs, there are no-op
3340 // optimizations available here.
3341 case Type::Pointer:
3342 result = getPointerType(getVariableArrayDecayedType(
3343 cast<PointerType>(ty)->getPointeeType()));
3344 break;
3345
3346 case Type::LValueReference: {
3347 const auto *lv = cast<LValueReferenceType>(ty);
3348 result = getLValueReferenceType(
3349 getVariableArrayDecayedType(lv->getPointeeType()),
3350 lv->isSpelledAsLValue());
3351 break;
3352 }
3353
3354 case Type::RValueReference: {
3355 const auto *lv = cast<RValueReferenceType>(ty);
3356 result = getRValueReferenceType(
3357 getVariableArrayDecayedType(lv->getPointeeType()));
3358 break;
3359 }
3360
3361 case Type::Atomic: {
3362 const auto *at = cast<AtomicType>(ty);
3363 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3364 break;
3365 }
3366
3367 case Type::ConstantArray: {
3368 const auto *cat = cast<ConstantArrayType>(ty);
3369 result = getConstantArrayType(
3370 getVariableArrayDecayedType(cat->getElementType()),
3371 cat->getSize(),
3372 cat->getSizeExpr(),
3373 cat->getSizeModifier(),
3374 cat->getIndexTypeCVRQualifiers());
3375 break;
3376 }
3377
3378 case Type::DependentSizedArray: {
3379 const auto *dat = cast<DependentSizedArrayType>(ty);
3380 result = getDependentSizedArrayType(
3381 getVariableArrayDecayedType(dat->getElementType()),
3382 dat->getSizeExpr(),
3383 dat->getSizeModifier(),
3384 dat->getIndexTypeCVRQualifiers(),
3385 dat->getBracketsRange());
3386 break;
3387 }
3388
3389 // Turn incomplete types into [*] types.
3390 case Type::IncompleteArray: {
3391 const auto *iat = cast<IncompleteArrayType>(ty);
3392 result = getVariableArrayType(
3393 getVariableArrayDecayedType(iat->getElementType()),
3394 /*size*/ nullptr,
3395 ArrayType::Normal,
3396 iat->getIndexTypeCVRQualifiers(),
3397 SourceRange());
3398 break;
3399 }
3400
3401 // Turn VLA types into [*] types.
3402 case Type::VariableArray: {
3403 const auto *vat = cast<VariableArrayType>(ty);
3404 result = getVariableArrayType(
3405 getVariableArrayDecayedType(vat->getElementType()),
3406 /*size*/ nullptr,
3407 ArrayType::Star,
3408 vat->getIndexTypeCVRQualifiers(),
3409 vat->getBracketsRange());
3410 break;
3411 }
3412 }
3413
3414 // Apply the top-level qualifiers from the original.
3415 return getQualifiedType(result, split.Quals);
3416}
3417
3418/// getVariableArrayType - Returns a non-unique reference to the type for a
3419/// variable array of the specified element type.
3420QualType ASTContext::getVariableArrayType(QualType EltTy,
3421 Expr *NumElts,
3422 ArrayType::ArraySizeModifier ASM,
3423 unsigned IndexTypeQuals,
3424 SourceRange Brackets) const {
3425 // Since we don't unique expressions, it isn't possible to unique VLA's
3426 // that have an expression provided for their size.
3427 QualType Canon;
3428
3429 // Be sure to pull qualifiers off the element type.
3430 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3431 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3432 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3433 IndexTypeQuals, Brackets);
3434 Canon = getQualifiedType(Canon, canonSplit.Quals);
3435 }
3436
3437 auto *New = new (*this, TypeAlignment)
3438 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3439
3440 VariableArrayTypes.push_back(New);
3441 Types.push_back(New);
3442 return QualType(New, 0);
3443}
3444
3445/// getDependentSizedArrayType - Returns a non-unique reference to
3446/// the type for a dependently-sized array of the specified element
3447/// type.
3448QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3449 Expr *numElements,
3450 ArrayType::ArraySizeModifier ASM,
3451 unsigned elementTypeQuals,
3452 SourceRange brackets) const {
3453 assert((!numElements || numElements->isTypeDependent() ||(((!numElements || numElements->isTypeDependent() || numElements
->isValueDependent()) && "Size must be type- or value-dependent!"
) ? static_cast<void> (0) : __assert_fail ("(!numElements || numElements->isTypeDependent() || numElements->isValueDependent()) && \"Size must be type- or value-dependent!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3455, __PRETTY_FUNCTION__))
3454 numElements->isValueDependent()) &&(((!numElements || numElements->isTypeDependent() || numElements
->isValueDependent()) && "Size must be type- or value-dependent!"
) ? static_cast<void> (0) : __assert_fail ("(!numElements || numElements->isTypeDependent() || numElements->isValueDependent()) && \"Size must be type- or value-dependent!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3455, __PRETTY_FUNCTION__))
3455 "Size must be type- or value-dependent!")(((!numElements || numElements->isTypeDependent() || numElements
->isValueDependent()) && "Size must be type- or value-dependent!"
) ? static_cast<void> (0) : __assert_fail ("(!numElements || numElements->isTypeDependent() || numElements->isValueDependent()) && \"Size must be type- or value-dependent!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3455, __PRETTY_FUNCTION__))
;
3456
3457 // Dependently-sized array types that do not have a specified number
3458 // of elements will have their sizes deduced from a dependent
3459 // initializer. We do no canonicalization here at all, which is okay
3460 // because they can't be used in most locations.
3461 if (!numElements) {
3462 auto *newType
3463 = new (*this, TypeAlignment)
3464 DependentSizedArrayType(*this, elementType, QualType(),
3465 numElements, ASM, elementTypeQuals,
3466 brackets);
3467 Types.push_back(newType);
3468 return QualType(newType, 0);
3469 }
3470
3471 // Otherwise, we actually build a new type every time, but we
3472 // also build a canonical type.
3473
3474 SplitQualType canonElementType = getCanonicalType(elementType).split();
3475
3476 void *insertPos = nullptr;
3477 llvm::FoldingSetNodeID ID;
3478 DependentSizedArrayType::Profile(ID, *this,
3479 QualType(canonElementType.Ty, 0),
3480 ASM, elementTypeQuals, numElements);
3481
3482 // Look for an existing type with these properties.
3483 DependentSizedArrayType *canonTy =
3484 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3485
3486 // If we don't have one, build one.
3487 if (!canonTy) {
3488 canonTy = new (*this, TypeAlignment)
3489 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
3490 QualType(), numElements, ASM, elementTypeQuals,
3491 brackets);
3492 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3493 Types.push_back(canonTy);
3494 }
3495
3496 // Apply qualifiers from the element type to the array.
3497 QualType canon = getQualifiedType(QualType(canonTy,0),
3498 canonElementType.Quals);
3499
3500 // If we didn't need extra canonicalization for the element type or the size
3501 // expression, then just use that as our result.
3502 if (QualType(canonElementType.Ty, 0) == elementType &&
3503 canonTy->getSizeExpr() == numElements)
3504 return canon;
3505
3506 // Otherwise, we need to build a type which follows the spelling
3507 // of the element type.
3508 auto *sugaredType
3509 = new (*this, TypeAlignment)
3510 DependentSizedArrayType(*this, elementType, canon, numElements,
3511 ASM, elementTypeQuals, brackets);
3512 Types.push_back(sugaredType);
3513 return QualType(sugaredType, 0);
3514}
3515
3516QualType ASTContext::getIncompleteArrayType(QualType elementType,
3517 ArrayType::ArraySizeModifier ASM,
3518 unsigned elementTypeQuals) const {
3519 llvm::FoldingSetNodeID ID;
3520 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3521
3522 void *insertPos = nullptr;
3523 if (IncompleteArrayType *iat =
3524 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3525 return QualType(iat, 0);
3526
3527 // If the element type isn't canonical, this won't be a canonical type
3528 // either, so fill in the canonical type field. We also have to pull
3529 // qualifiers off the element type.
3530 QualType canon;
3531
3532 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3533 SplitQualType canonSplit = getCanonicalType(elementType).split();
3534 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3535 ASM, elementTypeQuals);
3536 canon = getQualifiedType(canon, canonSplit.Quals);
3537
3538 // Get the new insert position for the node we care about.
3539 IncompleteArrayType *existing =
3540 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3541 assert(!existing && "Shouldn't be in the map!")((!existing && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!existing && \"Shouldn't be in the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3541, __PRETTY_FUNCTION__))
; (void) existing;
3542 }
3543
3544 auto *newType = new (*this, TypeAlignment)
3545 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3546
3547 IncompleteArrayTypes.InsertNode(newType, insertPos);
3548 Types.push_back(newType);
3549 return QualType(newType, 0);
3550}
3551
3552/// getVectorType - Return the unique reference to a vector type of
3553/// the specified element type and size. VectorType must be a built-in type.
3554QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3555 VectorType::VectorKind VecKind) const {
3556 assert(vecType->isBuiltinType())((vecType->isBuiltinType()) ? static_cast<void> (0) :
__assert_fail ("vecType->isBuiltinType()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3556, __PRETTY_FUNCTION__))
;
3557
3558 // Check if we've already instantiated a vector of this type.
3559 llvm::FoldingSetNodeID ID;
3560 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3561
3562 void *InsertPos = nullptr;
3563 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3564 return QualType(VTP, 0);
3565
3566 // If the element type isn't canonical, this won't be a canonical type either,
3567 // so fill in the canonical type field.
3568 QualType Canonical;
3569 if (!vecType.isCanonical()) {
3570 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
3571
3572 // Get the new insert position for the node we care about.
3573 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3574 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3574, __PRETTY_FUNCTION__))
; (void)NewIP;
3575 }
3576 auto *New = new (*this, TypeAlignment)
3577 VectorType(vecType, NumElts, Canonical, VecKind);
3578 VectorTypes.InsertNode(New, InsertPos);
3579 Types.push_back(New);
3580 return QualType(New, 0);
3581}
3582
3583QualType
3584ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3585 SourceLocation AttrLoc,
3586 VectorType::VectorKind VecKind) const {
3587 llvm::FoldingSetNodeID ID;
3588 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3589 VecKind);
3590 void *InsertPos = nullptr;
3591 DependentVectorType *Canon =
3592 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3593 DependentVectorType *New;
3594
3595 if (Canon) {
3596 New = new (*this, TypeAlignment) DependentVectorType(
3597 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3598 } else {
3599 QualType CanonVecTy = getCanonicalType(VecType);
3600 if (CanonVecTy == VecType) {
3601 New = new (*this, TypeAlignment) DependentVectorType(
3602 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3603
3604 DependentVectorType *CanonCheck =
3605 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3606 assert(!CanonCheck &&((!CanonCheck && "Dependent-sized vector_size canonical type broken"
) ? static_cast<void> (0) : __assert_fail ("!CanonCheck && \"Dependent-sized vector_size canonical type broken\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3607, __PRETTY_FUNCTION__))
3607 "Dependent-sized vector_size canonical type broken")((!CanonCheck && "Dependent-sized vector_size canonical type broken"
) ? static_cast<void> (0) : __assert_fail ("!CanonCheck && \"Dependent-sized vector_size canonical type broken\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3607, __PRETTY_FUNCTION__))
;
3608 (void)CanonCheck;
3609 DependentVectorTypes.InsertNode(New, InsertPos);
3610 } else {
3611 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3612 SourceLocation());
3613 New = new (*this, TypeAlignment) DependentVectorType(
3614 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3615 }
3616 }
3617
3618 Types.push_back(New);
3619 return QualType(New, 0);
3620}
3621
3622/// getExtVectorType - Return the unique reference to an extended vector type of
3623/// the specified element type and size. VectorType must be a built-in type.
3624QualType
3625ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
3626 assert(vecType->isBuiltinType() || vecType->isDependentType())((vecType->isBuiltinType() || vecType->isDependentType(
)) ? static_cast<void> (0) : __assert_fail ("vecType->isBuiltinType() || vecType->isDependentType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3626, __PRETTY_FUNCTION__))
;
3627
3628 // Check if we've already instantiated a vector of this type.
3629 llvm::FoldingSetNodeID ID;
3630 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
3631 VectorType::GenericVector);
3632 void *InsertPos = nullptr;
3633 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3634 return QualType(VTP, 0);
3635
3636 // If the element type isn't canonical, this won't be a canonical type either,
3637 // so fill in the canonical type field.
3638 QualType Canonical;
3639 if (!vecType.isCanonical()) {
3640 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
3641
3642 // Get the new insert position for the node we care about.
3643 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3644 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3644, __PRETTY_FUNCTION__))
; (void)NewIP;
3645 }
3646 auto *New = new (*this, TypeAlignment)
3647 ExtVectorType(vecType, NumElts, Canonical);
3648 VectorTypes.InsertNode(New, InsertPos);
3649 Types.push_back(New);
3650 return QualType(New, 0);
3651}
3652
3653QualType
3654ASTContext::getDependentSizedExtVectorType(QualType vecType,
3655 Expr *SizeExpr,
3656 SourceLocation AttrLoc) const {
3657 llvm::FoldingSetNodeID ID;
3658 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
3659 SizeExpr);
3660
3661 void *InsertPos = nullptr;
3662 DependentSizedExtVectorType *Canon
3663 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3664 DependentSizedExtVectorType *New;
3665 if (Canon) {
3666 // We already have a canonical version of this array type; use it as
3667 // the canonical type for a newly-built type.
3668 New = new (*this, TypeAlignment)
3669 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3670 SizeExpr, AttrLoc);
3671 } else {
3672 QualType CanonVecTy = getCanonicalType(vecType);
3673 if (CanonVecTy == vecType) {
3674 New = new (*this, TypeAlignment)
3675 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3676 AttrLoc);
3677
3678 DependentSizedExtVectorType *CanonCheck
3679 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3680 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken")((!CanonCheck && "Dependent-sized ext_vector canonical type broken"
) ? static_cast<void> (0) : __assert_fail ("!CanonCheck && \"Dependent-sized ext_vector canonical type broken\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3680, __PRETTY_FUNCTION__))
;
3681 (void)CanonCheck;
3682 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3683 } else {
3684 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3685 SourceLocation());
3686 New = new (*this, TypeAlignment)
3687 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
3688 }
3689 }
3690
3691 Types.push_back(New);
3692 return QualType(New, 0);
3693}
3694
3695QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3696 Expr *AddrSpaceExpr,
3697 SourceLocation AttrLoc) const {
3698 assert(AddrSpaceExpr->isInstantiationDependent())((AddrSpaceExpr->isInstantiationDependent()) ? static_cast
<void> (0) : __assert_fail ("AddrSpaceExpr->isInstantiationDependent()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3698, __PRETTY_FUNCTION__))
;
3699
3700 QualType canonPointeeType = getCanonicalType(PointeeType);
3701
3702 void *insertPos = nullptr;
3703 llvm::FoldingSetNodeID ID;
3704 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3705 AddrSpaceExpr);
3706
3707 DependentAddressSpaceType *canonTy =
3708 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3709
3710 if (!canonTy) {
3711 canonTy = new (*this, TypeAlignment)
3712 DependentAddressSpaceType(*this, canonPointeeType,
3713 QualType(), AddrSpaceExpr, AttrLoc);
3714 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3715 Types.push_back(canonTy);
3716 }
3717
3718 if (canonPointeeType == PointeeType &&
3719 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
3720 return QualType(canonTy, 0);
3721
3722 auto *sugaredType
3723 = new (*this, TypeAlignment)
3724 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
3725 AddrSpaceExpr, AttrLoc);
3726 Types.push_back(sugaredType);
3727 return QualType(sugaredType, 0);
3728}
3729
3730/// Determine whether \p T is canonical as the result type of a function.
3731static bool isCanonicalResultType(QualType T) {
3732 return T.isCanonical() &&
3733 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3734 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3735}
3736
3737/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
3738QualType
3739ASTContext::getFunctionNoProtoType(QualType ResultTy,
3740 const FunctionType::ExtInfo &Info) const {
3741 // Unique functions, to guarantee there is only one function of a particular
3742 // structure.
3743 llvm::FoldingSetNodeID ID;
3744 FunctionNoProtoType::Profile(ID, ResultTy, Info);
3745
3746 void *InsertPos = nullptr;
3747 if (FunctionNoProtoType *FT =
3748 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3749 return QualType(FT, 0);
3750
3751 QualType Canonical;
3752 if (!isCanonicalResultType(ResultTy)) {
3753 Canonical =
3754 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
3755
3756 // Get the new insert position for the node we care about.
3757 FunctionNoProtoType *NewIP =
3758 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3759 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3759, __PRETTY_FUNCTION__))
; (void)NewIP;
3760 }
3761
3762 auto *New = new (*this, TypeAlignment)
3763 FunctionNoProtoType(ResultTy, Canonical, Info);
3764 Types.push_back(New);
3765 FunctionNoProtoTypes.InsertNode(New, InsertPos);
3766 return QualType(New, 0);
3767}
3768
3769CanQualType
3770ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3771 CanQualType CanResultType = getCanonicalType(ResultType);
3772
3773 // Canonical result types do not have ARC lifetime qualifiers.
3774 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3775 Qualifiers Qs = CanResultType.getQualifiers();
3776 Qs.removeObjCLifetime();
3777 return CanQualType::CreateUnsafe(
3778 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3779 }
3780
3781 return CanResultType;
3782}
3783
3784static bool isCanonicalExceptionSpecification(
3785 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3786 if (ESI.Type == EST_None)
3787 return true;
3788 if (!NoexceptInType)
3789 return false;
3790
3791 // C++17 onwards: exception specification is part of the type, as a simple
3792 // boolean "can this function type throw".
3793 if (ESI.Type == EST_BasicNoexcept)
3794 return true;
3795
3796 // A noexcept(expr) specification is (possibly) canonical if expr is
3797 // value-dependent.
3798 if (ESI.Type == EST_DependentNoexcept)
3799 return true;
3800
3801 // A dynamic exception specification is canonical if it only contains pack
3802 // expansions (so we can't tell whether it's non-throwing) and all its
3803 // contained types are canonical.
3804 if (ESI.Type == EST_Dynamic) {
3805 bool AnyPackExpansions = false;
3806 for (QualType ET : ESI.Exceptions) {
3807 if (!ET.isCanonical())
3808 return false;
3809 if (ET->getAs<PackExpansionType>())
3810 AnyPackExpansions = true;
3811 }
3812 return AnyPackExpansions;
3813 }
3814
3815 return false;
3816}
3817
3818QualType ASTContext::getFunctionTypeInternal(
3819 QualType ResultTy, ArrayRef<QualType> ArgArray,
3820 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
3821 size_t NumArgs = ArgArray.size();
3822
3823 // Unique functions, to guarantee there is only one function of a particular
3824 // structure.
3825 llvm::FoldingSetNodeID ID;
3826 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3827 *this, true);
3828
3829 QualType Canonical;
3830 bool Unique = false;
3831
3832 void *InsertPos = nullptr;
3833 if (FunctionProtoType *FPT =
3834 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3835 QualType Existing = QualType(FPT, 0);
3836
3837 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3838 // it so long as our exception specification doesn't contain a dependent
3839 // noexcept expression, or we're just looking for a canonical type.
3840 // Otherwise, we're going to need to create a type
3841 // sugar node to hold the concrete expression.
3842 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
3843 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3844 return Existing;
3845
3846 // We need a new type sugar node for this one, to hold the new noexcept
3847 // expression. We do no canonicalization here, but that's OK since we don't
3848 // expect to see the same noexcept expression much more than once.
3849 Canonical = getCanonicalType(Existing);
3850 Unique = true;
3851 }
3852
3853 bool NoexceptInType = getLangOpts().CPlusPlus17;
3854 bool IsCanonicalExceptionSpec =
3855 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3856
3857 // Determine whether the type being created is already canonical or not.
3858 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
3859 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
3860 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
3861 if (!ArgArray[i].isCanonicalAsParam())
3862 isCanonical = false;
3863
3864 if (OnlyWantCanonical)
3865 assert(isCanonical &&((isCanonical && "given non-canonical parameters constructing canonical type"
) ? static_cast<void> (0) : __assert_fail ("isCanonical && \"given non-canonical parameters constructing canonical type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3866, __PRETTY_FUNCTION__))
3866 "given non-canonical parameters constructing canonical type")((isCanonical && "given non-canonical parameters constructing canonical type"
) ? static_cast<void> (0) : __assert_fail ("isCanonical && \"given non-canonical parameters constructing canonical type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3866, __PRETTY_FUNCTION__))
;
3867
3868 // If this type isn't canonical, get the canonical version of it if we don't
3869 // already have it. The exception spec is only partially part of the
3870 // canonical type, and only in C++17 onwards.
3871 if (!isCanonical && Canonical.isNull()) {
3872 SmallVector<QualType, 16> CanonicalArgs;
3873 CanonicalArgs.reserve(NumArgs);
3874 for (unsigned i = 0; i != NumArgs; ++i)
3875 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
3876
3877 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
3878 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
3879 CanonicalEPI.HasTrailingReturn = false;
3880
3881 if (IsCanonicalExceptionSpec) {
3882 // Exception spec is already OK.
3883 } else if (NoexceptInType) {
3884 switch (EPI.ExceptionSpec.Type) {
3885 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3886 // We don't know yet. It shouldn't matter what we pick here; no-one
3887 // should ever look at this.
3888 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3889 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
3890 CanonicalEPI.ExceptionSpec.Type = EST_None;
3891 break;
3892
3893 // A dynamic exception specification is almost always "not noexcept",
3894 // with the exception that a pack expansion might expand to no types.
3895 case EST_Dynamic: {
3896 bool AnyPacks = false;
3897 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3898 if (ET->getAs<PackExpansionType>())
3899 AnyPacks = true;
3900 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3901 }
3902 if (!AnyPacks)
3903 CanonicalEPI.ExceptionSpec.Type = EST_None;
3904 else {
3905 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3906 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3907 }
3908 break;
3909 }
3910
3911 case EST_DynamicNone:
3912 case EST_BasicNoexcept:
3913 case EST_NoexceptTrue:
3914 case EST_NoThrow:
3915 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3916 break;
3917
3918 case EST_DependentNoexcept:
3919 llvm_unreachable("dependent noexcept is already canonical")::llvm::llvm_unreachable_internal("dependent noexcept is already canonical"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3919)
;
3920 }
3921 } else {
3922 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3923 }
3924
3925 // Adjust the canonical function result type.
3926 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
3927 Canonical =
3928 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
3929
3930 // Get the new insert position for the node we care about.
3931 FunctionProtoType *NewIP =
3932 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3933 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3933, __PRETTY_FUNCTION__))
; (void)NewIP;
3934 }
3935
3936 // Compute the needed size to hold this FunctionProtoType and the
3937 // various trailing objects.
3938 auto ESH = FunctionProtoType::getExceptionSpecSize(
3939 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
3940 size_t Size = FunctionProtoType::totalSizeToAlloc<
3941 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
3942 FunctionType::ExceptionType, Expr *, FunctionDecl *,
3943 FunctionProtoType::ExtParameterInfo, Qualifiers>(
3944 NumArgs, EPI.Variadic,
3945 FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
3946 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
3947 EPI.ExtParameterInfos ? NumArgs : 0,
3948 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
3949
3950 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
3951 FunctionProtoType::ExtProtoInfo newEPI = EPI;
3952 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
3953 Types.push_back(FTP);
3954 if (!Unique)
3955 FunctionProtoTypes.InsertNode(FTP, InsertPos);
3956 return QualType(FTP, 0);
3957}
3958
3959QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
3960 llvm::FoldingSetNodeID ID;
3961 PipeType::Profile(ID, T, ReadOnly);
3962
3963 void *InsertPos = nullptr;
3964 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3965 return QualType(PT, 0);
3966
3967 // If the pipe element type isn't canonical, this won't be a canonical type
3968 // either, so fill in the canonical type field.
3969 QualType Canonical;
3970 if (!T.isCanonical()) {
3971 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
3972
3973 // Get the new insert position for the node we care about.
3974 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3975 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 3975, __PRETTY_FUNCTION__))
;
3976 (void)NewIP;
3977 }
3978 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
3979 Types.push_back(New);
3980 PipeTypes.InsertNode(New, InsertPos);
3981 return QualType(New, 0);
3982}
3983
3984QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3985 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3986 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3987 : Ty;
3988}
3989
3990QualType ASTContext::getReadPipeType(QualType T) const {
3991 return getPipeType(T, true);
3992}
3993
3994QualType ASTContext::getWritePipeType(QualType T) const {
3995 return getPipeType(T, false);
3996}
3997
3998#ifndef NDEBUG
3999static bool NeedsInjectedClassNameType(const RecordDecl *D) {
4000 if (!isa<CXXRecordDecl>(D)) return false;
4001 const auto *RD = cast<CXXRecordDecl>(D);
4002 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4003 return true;
4004 if (RD->getDescribedClassTemplate() &&
4005 !isa<ClassTemplateSpecializationDecl>(RD))
4006 return true;
4007 return false;
4008}
4009#endif
4010
4011/// getInjectedClassNameType - Return the unique reference to the
4012/// injected class name type for the specified templated declaration.
4013QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
4014 QualType TST) const {
4015 assert(NeedsInjectedClassNameType(Decl))((NeedsInjectedClassNameType(Decl)) ? static_cast<void>
(0) : __assert_fail ("NeedsInjectedClassNameType(Decl)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4015, __PRETTY_FUNCTION__))
;
4016 if (Decl->TypeForDecl) {
4017 assert(isa<InjectedClassNameType>(Decl->TypeForDecl))((isa<InjectedClassNameType>(Decl->TypeForDecl)) ? static_cast
<void> (0) : __assert_fail ("isa<InjectedClassNameType>(Decl->TypeForDecl)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4017, __PRETTY_FUNCTION__))
;
4018 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4019 assert(PrevDecl->TypeForDecl && "previous declaration has no type")((PrevDecl->TypeForDecl && "previous declaration has no type"
) ? static_cast<void> (0) : __assert_fail ("PrevDecl->TypeForDecl && \"previous declaration has no type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4019, __PRETTY_FUNCTION__))
;
4020 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4021 assert(isa<InjectedClassNameType>(Decl->TypeForDecl))((isa<InjectedClassNameType>(Decl->TypeForDecl)) ? static_cast
<void> (0) : __assert_fail ("isa<InjectedClassNameType>(Decl->TypeForDecl)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4021, __PRETTY_FUNCTION__))
;
4022 } else {
4023 Type *newType =
4024 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
4025 Decl->TypeForDecl = newType;
4026 Types.push_back(newType);
4027 }
4028 return QualType(Decl->TypeForDecl, 0);
4029}
4030
4031/// getTypeDeclType - Return the unique reference to the type for the
4032/// specified type declaration.
4033QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4034 assert(Decl && "Passed null for Decl param")((Decl && "Passed null for Decl param") ? static_cast
<void> (0) : __assert_fail ("Decl && \"Passed null for Decl param\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4034, __PRETTY_FUNCTION__))
;
4035 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case")((!Decl->TypeForDecl && "TypeForDecl present in slow case"
) ? static_cast<void> (0) : __assert_fail ("!Decl->TypeForDecl && \"TypeForDecl present in slow case\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4035, __PRETTY_FUNCTION__))
;
4036
4037 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4038 return getTypedefType(Typedef);
4039
4040 assert(!isa<TemplateTypeParmDecl>(Decl) &&((!isa<TemplateTypeParmDecl>(Decl) && "Template type parameter types are always available."
) ? static_cast<void> (0) : __assert_fail ("!isa<TemplateTypeParmDecl>(Decl) && \"Template type parameter types are always available.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4041, __PRETTY_FUNCTION__))
4041 "Template type parameter types are always available.")((!isa<TemplateTypeParmDecl>(Decl) && "Template type parameter types are always available."
) ? static_cast<void> (0) : __assert_fail ("!isa<TemplateTypeParmDecl>(Decl) && \"Template type parameter types are always available.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4041, __PRETTY_FUNCTION__))
;
4042
4043 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4044 assert(Record->isFirstDecl() && "struct/union has previous declaration")((Record->isFirstDecl() && "struct/union has previous declaration"
) ? static_cast<void> (0) : __assert_fail ("Record->isFirstDecl() && \"struct/union has previous declaration\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4044, __PRETTY_FUNCTION__))
;
4045 assert(!NeedsInjectedClassNameType(Record))((!NeedsInjectedClassNameType(Record)) ? static_cast<void>
(0) : __assert_fail ("!NeedsInjectedClassNameType(Record)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4045, __PRETTY_FUNCTION__))
;
4046 return getRecordType(Record);
4047 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4048 assert(Enum->isFirstDecl() && "enum has previous declaration")((Enum->isFirstDecl() && "enum has previous declaration"
) ? static_cast<void> (0) : __assert_fail ("Enum->isFirstDecl() && \"enum has previous declaration\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4048, __PRETTY_FUNCTION__))
;
4049 return getEnumType(Enum);
4050 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4051 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
4052 Decl->TypeForDecl = newType;
4053 Types.push_back(newType);
4054 } else
4055 llvm_unreachable("TypeDecl without a type?")::llvm::llvm_unreachable_internal("TypeDecl without a type?",
"/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4055)
;
4056
4057 return QualType(Decl->TypeForDecl, 0);
4058}
4059
4060/// getTypedefType - Return the unique reference to the type for the
4061/// specified typedef name decl.
4062QualType
4063ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4064 QualType Canonical) const {
4065 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4066
4067 if (Canonical.isNull())
4068 Canonical = getCanonicalType(Decl->getUnderlyingType());
4069 auto *newType = new (*this, TypeAlignment)
4070 TypedefType(Type::Typedef, Decl, Canonical);
4071 Decl->TypeForDecl = newType;
4072 Types.push_back(newType);
4073 return QualType(newType, 0);
4074}
4075
4076QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
4077 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4078
4079 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4080 if (PrevDecl->TypeForDecl)
4081 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4082
4083 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
4084 Decl->TypeForDecl = newType;
4085 Types.push_back(newType);
4086 return QualType(newType, 0);
4087}
4088
4089QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
4090 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4091
4092 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4093 if (PrevDecl->TypeForDecl)
4094 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4095
4096 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
4097 Decl->TypeForDecl = newType;
4098 Types.push_back(newType);
4099 return QualType(newType, 0);
4100}
4101
4102QualType ASTContext::getAttributedType(attr::Kind attrKind,
4103 QualType modifiedType,
4104 QualType equivalentType) {
4105 llvm::FoldingSetNodeID id;
4106 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4107
4108 void *insertPos = nullptr;
4109 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4110 if (type) return QualType(type, 0);
4111
4112 QualType canon = getCanonicalType(equivalentType);
4113 type = new (*this, TypeAlignment)
4114 AttributedType(canon, attrKind, modifiedType, equivalentType);
4115
4116 Types.push_back(type);
4117 AttributedTypes.InsertNode(type, insertPos);
4118
4119 return QualType(type, 0);
4120}
4121
4122/// Retrieve a substitution-result type.
4123QualType
4124ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
4125 QualType Replacement) const {
4126 assert(Replacement.isCanonical()((Replacement.isCanonical() && "replacement types must always be canonical"
) ? static_cast<void> (0) : __assert_fail ("Replacement.isCanonical() && \"replacement types must always be canonical\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4127, __PRETTY_FUNCTION__))
4127 && "replacement types must always be canonical")((Replacement.isCanonical() && "replacement types must always be canonical"
) ? static_cast<void> (0) : __assert_fail ("Replacement.isCanonical() && \"replacement types must always be canonical\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4127, __PRETTY_FUNCTION__))
;
4128
4129 llvm::FoldingSetNodeID ID;
4130 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
4131 void *InsertPos = nullptr;
4132 SubstTemplateTypeParmType *SubstParm
4133 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4134
4135 if (!SubstParm) {
4136 SubstParm = new (*this, TypeAlignment)
4137 SubstTemplateTypeParmType(Parm, Replacement);
4138 Types.push_back(SubstParm);
4139 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4140 }
4141
4142 return QualType(SubstParm, 0);
4143}
4144
4145/// Retrieve a
4146QualType ASTContext::getSubstTemplateTypeParmPackType(
4147 const TemplateTypeParmType *Parm,
4148 const TemplateArgument &ArgPack) {
4149#ifndef NDEBUG
4150 for (const auto &P : ArgPack.pack_elements()) {
4151 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type")((P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"
) ? static_cast<void> (0) : __assert_fail ("P.getKind() == TemplateArgument::Type &&\"Pack contains a non-type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4151, __PRETTY_FUNCTION__))
;
4152 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type")((P.getAsType().isCanonical() && "Pack contains non-canonical type"
) ? static_cast<void> (0) : __assert_fail ("P.getAsType().isCanonical() && \"Pack contains non-canonical type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4152, __PRETTY_FUNCTION__))
;
4153 }
4154#endif
4155
4156 llvm::FoldingSetNodeID ID;
4157 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
4158 void *InsertPos = nullptr;
4159 if (SubstTemplateTypeParmPackType *SubstParm
4160 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4161 return QualType(SubstParm, 0);
4162
4163 QualType Canon;
4164 if (!Parm->isCanonicalUnqualified()) {
4165 Canon = getCanonicalType(QualType(Parm, 0));
4166 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4167 ArgPack);
4168 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4169 }
4170
4171 auto *SubstParm
4172 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4173 ArgPack);
4174 Types.push_back(SubstParm);
4175 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4176 return QualType(SubstParm, 0);
4177}
4178
4179/// Retrieve the template type parameter type for a template
4180/// parameter or parameter pack with the given depth, index, and (optionally)
4181/// name.
4182QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4183 bool ParameterPack,
4184 TemplateTypeParmDecl *TTPDecl) const {
4185 llvm::FoldingSetNodeID ID;
4186 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4187 void *InsertPos = nullptr;
4188 TemplateTypeParmType *TypeParm
4189 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4190
4191 if (TypeParm)
4192 return QualType(TypeParm, 0);
4193
4194 if (TTPDecl) {
4195 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4196 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
4197
4198 TemplateTypeParmType *TypeCheck
4199 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4200 assert(!TypeCheck && "Template type parameter canonical type broken")((!TypeCheck && "Template type parameter canonical type broken"
) ? static_cast<void> (0) : __assert_fail ("!TypeCheck && \"Template type parameter canonical type broken\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4200, __PRETTY_FUNCTION__))
;
4201 (void)TypeCheck;
4202 } else
4203 TypeParm = new (*this, TypeAlignment)
4204 TemplateTypeParmType(Depth, Index, ParameterPack);
4205
4206 Types.push_back(TypeParm);
4207 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4208
4209 return QualType(TypeParm, 0);
4210}
4211
4212TypeSourceInfo *
4213ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4214 SourceLocation NameLoc,
4215 const TemplateArgumentListInfo &Args,
4216 QualType Underlying) const {
4217 assert(!Name.getAsDependentTemplateName() &&((!Name.getAsDependentTemplateName() && "No dependent template names here!"
) ? static_cast<void> (0) : __assert_fail ("!Name.getAsDependentTemplateName() && \"No dependent template names here!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4218, __PRETTY_FUNCTION__))
4218 "No dependent template names here!")((!Name.getAsDependentTemplateName() && "No dependent template names here!"
) ? static_cast<void> (0) : __assert_fail ("!Name.getAsDependentTemplateName() && \"No dependent template names here!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4218, __PRETTY_FUNCTION__))
;
4219 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
4220
4221 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
4222 TemplateSpecializationTypeLoc TL =
4223 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
4224 TL.setTemplateKeywordLoc(SourceLocation());
4225 TL.setTemplateNameLoc(NameLoc);
4226 TL.setLAngleLoc(Args.getLAngleLoc());
4227 TL.setRAngleLoc(Args.getRAngleLoc());
4228 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4229 TL.setArgLocInfo(i, Args[i].getLocInfo());
4230 return DI;
4231}
4232
4233QualType
4234ASTContext::getTemplateSpecializationType(TemplateName Template,
4235 const TemplateArgumentListInfo &Args,
4236 QualType Underlying) const {
4237 assert(!Template.getAsDependentTemplateName() &&((!Template.getAsDependentTemplateName() && "No dependent template names here!"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4238, __PRETTY_FUNCTION__))
4238 "No dependent template names here!")((!Template.getAsDependentTemplateName() && "No dependent template names here!"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4238, __PRETTY_FUNCTION__))
;
4239
4240 SmallVector<TemplateArgument, 4> ArgVec;
4241 ArgVec.reserve(Args.size());
4242 for (const TemplateArgumentLoc &Arg : Args.arguments())
4243 ArgVec.push_back(Arg.getArgument());
4244
4245 return getTemplateSpecializationType(Template, ArgVec, Underlying);
4246}
4247
4248#ifndef NDEBUG
4249static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4250 for (const TemplateArgument &Arg : Args)
4251 if (Arg.isPackExpansion())
4252 return true;
4253
4254 return true;
4255}
4256#endif
4257
4258QualType
4259ASTContext::getTemplateSpecializationType(TemplateName Template,
4260 ArrayRef<TemplateArgument> Args,
4261 QualType Underlying) const {
4262 assert(!Template.getAsDependentTemplateName() &&((!Template.getAsDependentTemplateName() && "No dependent template names here!"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4263, __PRETTY_FUNCTION__))
4263 "No dependent template names here!")((!Template.getAsDependentTemplateName() && "No dependent template names here!"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4263, __PRETTY_FUNCTION__))
;
4264 // Look through qualified template names.
4265 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4266 Template = TemplateName(QTN->getTemplateDecl());
4267
4268 bool IsTypeAlias =
4269 Template.getAsTemplateDecl() &&
4270 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
4271 QualType CanonType;
4272 if (!Underlying.isNull())
4273 CanonType = getCanonicalType(Underlying);
4274 else {
4275 // We can get here with an alias template when the specialization contains
4276 // a pack expansion that does not match up with a parameter pack.
4277 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&(((!IsTypeAlias || hasAnyPackExpansions(Args)) && "Caller must compute aliased type"
) ? static_cast<void> (0) : __assert_fail ("(!IsTypeAlias || hasAnyPackExpansions(Args)) && \"Caller must compute aliased type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4278, __PRETTY_FUNCTION__))
4278 "Caller must compute aliased type")(((!IsTypeAlias || hasAnyPackExpansions(Args)) && "Caller must compute aliased type"
) ? static_cast<void> (0) : __assert_fail ("(!IsTypeAlias || hasAnyPackExpansions(Args)) && \"Caller must compute aliased type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4278, __PRETTY_FUNCTION__))
;
4279 IsTypeAlias = false;
4280 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4281 }
4282
4283 // Allocate the (non-canonical) template specialization type, but don't
4284 // try to unique it: these types typically have location information that
4285 // we don't unique and don't want to lose.
4286 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4287 sizeof(TemplateArgument) * Args.size() +
4288 (IsTypeAlias? sizeof(QualType) : 0),
4289 TypeAlignment);
4290 auto *Spec
4291 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4292 IsTypeAlias ? Underlying : QualType());
4293
4294 Types.push_back(Spec);
4295 return QualType(Spec, 0);
4296}
4297
4298QualType ASTContext::getCanonicalTemplateSpecializationType(
4299 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4300 assert(!Template.getAsDependentTemplateName() &&((!Template.getAsDependentTemplateName() && "No dependent template names here!"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4301, __PRETTY_FUNCTION__))
4301 "No dependent template names here!")((!Template.getAsDependentTemplateName() && "No dependent template names here!"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4301, __PRETTY_FUNCTION__))
;
4302
4303 // Look through qualified template names.
4304 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4305 Template = TemplateName(QTN->getTemplateDecl());
4306
4307 // Build the canonical template specialization type.
4308 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4309 SmallVector<TemplateArgument, 4> CanonArgs;
4310 unsigned NumArgs = Args.size();
4311 CanonArgs.reserve(NumArgs);
4312 for (const TemplateArgument &Arg : Args)
4313 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
4314
4315 // Determine whether this canonical template specialization type already
4316 // exists.
4317 llvm::FoldingSetNodeID ID;
4318 TemplateSpecializationType::Profile(ID, CanonTemplate,
4319 CanonArgs, *this);
4320
4321 void *InsertPos = nullptr;
4322 TemplateSpecializationType *Spec
4323 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4324
4325 if (!Spec) {
4326 // Allocate a new canonical template specialization type.
4327 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4328 sizeof(TemplateArgument) * NumArgs),
4329 TypeAlignment);
4330 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
4331 CanonArgs,
4332 QualType(), QualType());
4333 Types.push_back(Spec);
4334 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4335 }
4336
4337 assert(Spec->isDependentType() &&((Spec->isDependentType() && "Non-dependent template-id type must have a canonical type"
) ? static_cast<void> (0) : __assert_fail ("Spec->isDependentType() && \"Non-dependent template-id type must have a canonical type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4338, __PRETTY_FUNCTION__))
4338 "Non-dependent template-id type must have a canonical type")((Spec->isDependentType() && "Non-dependent template-id type must have a canonical type"
) ? static_cast<void> (0) : __assert_fail ("Spec->isDependentType() && \"Non-dependent template-id type must have a canonical type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4338, __PRETTY_FUNCTION__))
;
4339 return QualType(Spec, 0);
4340}
4341
4342QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4343 NestedNameSpecifier *NNS,
4344 QualType NamedType,
4345 TagDecl *OwnedTagDecl) const {
4346 llvm::FoldingSetNodeID ID;
4347 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
4348
4349 void *InsertPos = nullptr;
4350 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4351 if (T)
4352 return QualType(T, 0);
4353
4354 QualType Canon = NamedType;
4355 if (!Canon.isCanonical()) {
4356 Canon = getCanonicalType(NamedType);
4357 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4358 assert(!CheckT && "Elaborated canonical type broken")((!CheckT && "Elaborated canonical type broken") ? static_cast
<void> (0) : __assert_fail ("!CheckT && \"Elaborated canonical type broken\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4358, __PRETTY_FUNCTION__))
;
4359 (void)CheckT;
4360 }
4361
4362 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4363 TypeAlignment);
4364 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4365
4366 Types.push_back(T);
4367 ElaboratedTypes.InsertNode(T, InsertPos);
4368 return QualType(T, 0);
4369}
4370
4371QualType
4372ASTContext::getParenType(QualType InnerType) const {
4373 llvm::FoldingSetNodeID ID;
4374 ParenType::Profile(ID, InnerType);
4375
4376 void *InsertPos = nullptr;
4377 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4378 if (T)
4379 return QualType(T, 0);
4380
4381 QualType Canon = InnerType;
4382 if (!Canon.isCanonical()) {
4383 Canon = getCanonicalType(InnerType);
4384 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4385 assert(!CheckT && "Paren canonical type broken")((!CheckT && "Paren canonical type broken") ? static_cast
<void> (0) : __assert_fail ("!CheckT && \"Paren canonical type broken\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4385, __PRETTY_FUNCTION__))
;
4386 (void)CheckT;
4387 }
4388
4389 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
4390 Types.push_back(T);
4391 ParenTypes.InsertNode(T, InsertPos);
4392 return QualType(T, 0);
4393}
4394
4395QualType
4396ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4397 const IdentifierInfo *MacroII) const {
4398 QualType Canon = UnderlyingTy;
4399 if (!Canon.isCanonical())
4400 Canon = getCanonicalType(UnderlyingTy);
4401
4402 auto *newType = new (*this, TypeAlignment)
4403 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4404 Types.push_back(newType);
4405 return QualType(newType, 0);
4406}
4407
4408QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4409 NestedNameSpecifier *NNS,
4410 const IdentifierInfo *Name,
4411 QualType Canon) const {
4412 if (Canon.isNull()) {
4413 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4414 if (CanonNNS != NNS)
4415 Canon = getDependentNameType(Keyword, CanonNNS, Name);
4416 }
4417
4418 llvm::FoldingSetNodeID ID;
4419 DependentNameType::Profile(ID, Keyword, NNS, Name);
4420
4421 void *InsertPos = nullptr;
4422 DependentNameType *T
4423 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
4424 if (T)
4425 return QualType(T, 0);
4426
4427 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
4428 Types.push_back(T);
4429 DependentNameTypes.InsertNode(T, InsertPos);
4430 return QualType(T, 0);
4431}
4432
4433QualType
4434ASTContext::getDependentTemplateSpecializationType(
4435 ElaboratedTypeKeyword Keyword,
4436 NestedNameSpecifier *NNS,
4437 const IdentifierInfo *Name,
4438 const TemplateArgumentListInfo &Args) const {
4439 // TODO: avoid this copy
4440 SmallVector<TemplateArgument, 16> ArgCopy;
4441 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4442 ArgCopy.push_back(Args[I].getArgument());
4443 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
4444}
4445
4446QualType
4447ASTContext::getDependentTemplateSpecializationType(
4448 ElaboratedTypeKeyword Keyword,
4449 NestedNameSpecifier *NNS,
4450 const IdentifierInfo *Name,
4451 ArrayRef<TemplateArgument> Args) const {
4452 assert((!NNS || NNS->isDependent()) &&(((!NNS || NNS->isDependent()) && "nested-name-specifier must be dependent"
) ? static_cast<void> (0) : __assert_fail ("(!NNS || NNS->isDependent()) && \"nested-name-specifier must be dependent\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4453, __PRETTY_FUNCTION__))
4453 "nested-name-specifier must be dependent")(((!NNS || NNS->isDependent()) && "nested-name-specifier must be dependent"
) ? static_cast<void> (0) : __assert_fail ("(!NNS || NNS->isDependent()) && \"nested-name-specifier must be dependent\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4453, __PRETTY_FUNCTION__))
;
4454
4455 llvm::FoldingSetNodeID ID;
4456 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
4457 Name, Args);
4458
4459 void *InsertPos = nullptr;
4460 DependentTemplateSpecializationType *T
4461 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4462 if (T)
4463 return QualType(T, 0);
4464
4465 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4466
4467 ElaboratedTypeKeyword CanonKeyword = Keyword;
4468 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4469
4470 bool AnyNonCanonArgs = false;
4471 unsigned NumArgs = Args.size();
4472 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
4473 for (unsigned I = 0; I != NumArgs; ++I) {
4474 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4475 if (!CanonArgs[I].structurallyEquals(Args[I]))
4476 AnyNonCanonArgs = true;
4477 }
4478
4479 QualType Canon;
4480 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4481 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
4482 Name,
4483 CanonArgs);
4484
4485 // Find the insert position again.
4486 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4487 }
4488
4489 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4490 sizeof(TemplateArgument) * NumArgs),
4491 TypeAlignment);
4492 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
4493 Name, Args, Canon);
4494 Types.push_back(T);
4495 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
4496 return QualType(T, 0);
4497}
4498
4499TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4500 TemplateArgument Arg;
4501 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4502 QualType ArgType = getTypeDeclType(TTP);
4503 if (TTP->isParameterPack())
4504 ArgType = getPackExpansionType(ArgType, None);
4505
4506 Arg = TemplateArgument(ArgType);
4507 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4508 Expr *E = new (*this) DeclRefExpr(
4509 *this, NTTP, /*enclosing*/ false,
4510 NTTP->getType().getNonLValueExprType(*this),
4511 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4512
4513 if (NTTP->isParameterPack())
4514 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4515 None);
4516 Arg = TemplateArgument(E);
4517 } else {
4518 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4519 if (TTP->isParameterPack())
4520 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4521 else
4522 Arg = TemplateArgument(TemplateName(TTP));
4523 }
4524
4525 if (Param->isTemplateParameterPack())
4526 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4527
4528 return Arg;
4529}
4530
4531void
4532ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4533 SmallVectorImpl<TemplateArgument> &Args) {
4534 Args.reserve(Args.size() + Params->size());
4535
4536 for (NamedDecl *Param : *Params)
4537 Args.push_back(getInjectedTemplateArg(Param));
4538}
4539
4540QualType ASTContext::getPackExpansionType(QualType Pattern,
4541 Optional<unsigned> NumExpansions) {
4542 llvm::FoldingSetNodeID ID;
4543 PackExpansionType::Profile(ID, Pattern, NumExpansions);
4544
4545 // A deduced type can deduce to a pack, eg
4546 // auto ...x = some_pack;
4547 // That declaration isn't (yet) valid, but is created as part of building an
4548 // init-capture pack:
4549 // [...x = some_pack] {}
4550 assert((Pattern->containsUnexpandedParameterPack() ||(((Pattern->containsUnexpandedParameterPack() || Pattern->
getContainedDeducedType()) && "Pack expansions must expand one or more parameter packs"
) ? static_cast<void> (0) : __assert_fail ("(Pattern->containsUnexpandedParameterPack() || Pattern->getContainedDeducedType()) && \"Pack expansions must expand one or more parameter packs\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4552, __PRETTY_FUNCTION__))
4551 Pattern->getContainedDeducedType()) &&(((Pattern->containsUnexpandedParameterPack() || Pattern->
getContainedDeducedType()) && "Pack expansions must expand one or more parameter packs"
) ? static_cast<void> (0) : __assert_fail ("(Pattern->containsUnexpandedParameterPack() || Pattern->getContainedDeducedType()) && \"Pack expansions must expand one or more parameter packs\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4552, __PRETTY_FUNCTION__))
4552 "Pack expansions must expand one or more parameter packs")(((Pattern->containsUnexpandedParameterPack() || Pattern->
getContainedDeducedType()) && "Pack expansions must expand one or more parameter packs"
) ? static_cast<void> (0) : __assert_fail ("(Pattern->containsUnexpandedParameterPack() || Pattern->getContainedDeducedType()) && \"Pack expansions must expand one or more parameter packs\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4552, __PRETTY_FUNCTION__))
;
4553 void *InsertPos = nullptr;
4554 PackExpansionType *T
4555 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4556 if (T)
4557 return QualType(T, 0);
4558
4559 QualType Canon;
4560 if (!Pattern.isCanonical()) {
4561 Canon = getCanonicalType(Pattern);
4562 // The canonical type might not contain an unexpanded parameter pack, if it
4563 // contains an alias template specialization which ignores one of its
4564 // parameters.
4565 if (Canon->containsUnexpandedParameterPack()) {
4566 Canon = getPackExpansionType(Canon, NumExpansions);
4567
4568 // Find the insert position again, in case we inserted an element into
4569 // PackExpansionTypes and invalidated our insert position.
4570 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4571 }
4572 }
4573
4574 T = new (*this, TypeAlignment)
4575 PackExpansionType(Pattern, Canon, NumExpansions);
4576 Types.push_back(T);
4577 PackExpansionTypes.InsertNode(T, InsertPos);
4578 return QualType(T, 0);
4579}
4580
4581/// CmpProtocolNames - Comparison predicate for sorting protocols
4582/// alphabetically.
4583static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4584 ObjCProtocolDecl *const *RHS) {
4585 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
4586}
4587
4588static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4589 if (Protocols.empty()) return true;
4590
4591 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4592 return false;
4593
4594 for (unsigned i = 1; i != Protocols.size(); ++i)
4595 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
4596 Protocols[i]->getCanonicalDecl() != Protocols[i])
4597 return false;
4598 return true;
4599}
4600
4601static void
4602SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
4603 // Sort protocols, keyed by name.
4604 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
4605
4606 // Canonicalize.
4607 for (ObjCProtocolDecl *&P : Protocols)
4608 P = P->getCanonicalDecl();
4609
4610 // Remove duplicates.
4611 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4612 Protocols.erase(ProtocolsEnd, Protocols.end());
4613}
4614
4615QualType ASTContext::getObjCObjectType(QualType BaseType,
4616 ObjCProtocolDecl * const *Protocols,
4617 unsigned NumProtocols) const {
4618 return getObjCObjectType(BaseType, {},
4619 llvm::makeArrayRef(Protocols, NumProtocols),
4620 /*isKindOf=*/false);
4621}
4622
4623QualType ASTContext::getObjCObjectType(
4624 QualType baseType,
4625 ArrayRef<QualType> typeArgs,
4626 ArrayRef<ObjCProtocolDecl *> protocols,
4627 bool isKindOf) const {
4628 // If the base type is an interface and there aren't any protocols or
4629 // type arguments to add, then the interface type will do just fine.
4630 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4631 isa<ObjCInterfaceType>(baseType))
4632 return baseType;
4633
4634 // Look in the folding set for an existing type.
4635 llvm::FoldingSetNodeID ID;
4636 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
4637 void *InsertPos = nullptr;
4638 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4639 return QualType(QT, 0);
4640
4641 // Determine the type arguments to be used for canonicalization,
4642 // which may be explicitly specified here or written on the base
4643 // type.
4644 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4645 if (effectiveTypeArgs.empty()) {
4646 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
4647 effectiveTypeArgs = baseObject->getTypeArgs();
4648 }
4649
4650 // Build the canonical type, which has the canonical base type and a
4651 // sorted-and-uniqued list of protocols and the type arguments
4652 // canonicalized.
4653 QualType canonical;
4654 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4655 effectiveTypeArgs.end(),
4656 [&](QualType type) {
4657 return type.isCanonical();
4658 });
4659 bool protocolsSorted = areSortedAndUniqued(protocols);
4660 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4661 // Determine the canonical type arguments.
4662 ArrayRef<QualType> canonTypeArgs;
4663 SmallVector<QualType, 4> canonTypeArgsVec;
4664 if (!typeArgsAreCanonical) {
4665 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4666 for (auto typeArg : effectiveTypeArgs)
4667 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4668 canonTypeArgs = canonTypeArgsVec;
4669 } else {
4670 canonTypeArgs = effectiveTypeArgs;
4671 }
4672
4673 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4674 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4675 if (!protocolsSorted) {
4676 canonProtocolsVec.append(protocols.begin(), protocols.end());
4677 SortAndUniqueProtocols(canonProtocolsVec);
4678 canonProtocols = canonProtocolsVec;
4679 } else {
4680 canonProtocols = protocols;
4681 }
4682
4683 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
4684 canonProtocols, isKindOf);
4685
4686 // Regenerate InsertPos.
4687 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4688 }
4689
4690 unsigned size = sizeof(ObjCObjectTypeImpl);
4691 size += typeArgs.size() * sizeof(QualType);
4692 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4693 void *mem = Allocate(size, TypeAlignment);
4694 auto *T =
4695 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4696 isKindOf);
4697
4698 Types.push_back(T);
4699 ObjCObjectTypes.InsertNode(T, InsertPos);
4700 return QualType(T, 0);
4701}
4702
4703/// Apply Objective-C protocol qualifiers to the given type.
4704/// If this is for the canonical type of a type parameter, we can apply
4705/// protocol qualifiers on the ObjCObjectPointerType.
4706QualType
4707ASTContext::applyObjCProtocolQualifiers(QualType type,
4708 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4709 bool allowOnPointerType) const {
4710 hasError = false;
4711
4712 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4713 return getObjCTypeParamType(objT->getDecl(), protocols);
4714 }
4715
4716 // Apply protocol qualifiers to ObjCObjectPointerType.
4717 if (allowOnPointerType) {
4718 if (const auto *objPtr =
4719 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4720 const ObjCObjectType *objT = objPtr->getObjectType();
4721 // Merge protocol lists and construct ObjCObjectType.
4722 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4723 protocolsVec.append(objT->qual_begin(),
4724 objT->qual_end());
4725 protocolsVec.append(protocols.begin(), protocols.end());
4726 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4727 type = getObjCObjectType(
4728 objT->getBaseType(),
4729 objT->getTypeArgsAsWritten(),
4730 protocols,
4731 objT->isKindOfTypeAsWritten());
4732 return getObjCObjectPointerType(type);
4733 }
4734 }
4735
4736 // Apply protocol qualifiers to ObjCObjectType.
4737 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4738 // FIXME: Check for protocols to which the class type is already
4739 // known to conform.
4740
4741 return getObjCObjectType(objT->getBaseType(),
4742 objT->getTypeArgsAsWritten(),
4743 protocols,
4744 objT->isKindOfTypeAsWritten());
4745 }
4746
4747 // If the canonical type is ObjCObjectType, ...
4748 if (type->isObjCObjectType()) {
4749 // Silently overwrite any existing protocol qualifiers.
4750 // TODO: determine whether that's the right thing to do.
4751
4752 // FIXME: Check for protocols to which the class type is already
4753 // known to conform.
4754 return getObjCObjectType(type, {}, protocols, false);
4755 }
4756
4757 // id<protocol-list>
4758 if (type->isObjCIdType()) {
4759 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
4760 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
4761 objPtr->isKindOfType());
4762 return getObjCObjectPointerType(type);
4763 }
4764
4765 // Class<protocol-list>
4766 if (type->isObjCClassType()) {
4767 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
4768 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
4769 objPtr->isKindOfType());
4770 return getObjCObjectPointerType(type);
4771 }
4772
4773 hasError = true;
4774 return type;
4775}
4776
4777QualType
4778ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4779 ArrayRef<ObjCProtocolDecl *> protocols) const {
4780 // Look in the folding set for an existing type.
4781 llvm::FoldingSetNodeID ID;
4782 ObjCTypeParamType::Profile(ID, Decl, protocols);
4783 void *InsertPos = nullptr;
4784 if (ObjCTypeParamType *TypeParam =
4785 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4786 return QualType(TypeParam, 0);
4787
4788 // We canonicalize to the underlying type.
4789 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
4790 if (!protocols.empty()) {
4791 // Apply the protocol qualifers.
4792 bool hasError;
4793 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
4794 Canonical, protocols, hasError, true /*allowOnPointerType*/));
4795 assert(!hasError && "Error when apply protocol qualifier to bound type")((!hasError && "Error when apply protocol qualifier to bound type"
) ? static_cast<void> (0) : __assert_fail ("!hasError && \"Error when apply protocol qualifier to bound type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4795, __PRETTY_FUNCTION__))
;
4796 }
4797
4798 unsigned size = sizeof(ObjCTypeParamType);
4799 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4800 void *mem = Allocate(size, TypeAlignment);
4801 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
4802
4803 Types.push_back(newType);
4804 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4805 return QualType(newType, 0);
4806}
4807
4808/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4809/// protocol list adopt all protocols in QT's qualified-id protocol
4810/// list.
4811bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4812 ObjCInterfaceDecl *IC) {
4813 if (!QT->isObjCQualifiedIdType())
4814 return false;
4815
4816 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
4817 // If both the right and left sides have qualifiers.
4818 for (auto *Proto : OPT->quals()) {
4819 if (!IC->ClassImplementsProtocol(Proto, false))
4820 return false;
4821 }
4822 return true;
4823 }
4824 return false;
4825}
4826
4827/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4828/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4829/// of protocols.
4830bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4831 ObjCInterfaceDecl *IDecl) {
4832 if (!QT->isObjCQualifiedIdType())
4833 return false;
4834 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
4835 if (!OPT)
4836 return false;
4837 if (!IDecl->hasDefinition())
4838 return false;
4839 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4840 CollectInheritedProtocols(IDecl, InheritedProtocols);
4841 if (InheritedProtocols.empty())
4842 return false;
4843 // Check that if every protocol in list of id<plist> conforms to a protocol
4844 // of IDecl's, then bridge casting is ok.
4845 bool Conforms = false;
4846 for (auto *Proto : OPT->quals()) {
4847 Conforms = false;
4848 for (auto *PI : InheritedProtocols) {
4849 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4850 Conforms = true;
4851 break;
4852 }
4853 }
4854 if (!Conforms)
4855 break;
4856 }
4857 if (Conforms)
4858 return true;
4859
4860 for (auto *PI : InheritedProtocols) {
4861 // If both the right and left sides have qualifiers.
4862 bool Adopts = false;
4863 for (auto *Proto : OPT->quals()) {
4864 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
4865 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
4866 break;
4867 }
4868 if (!Adopts)
4869 return false;
4870 }
4871 return true;
4872}
4873
4874/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4875/// the given object type.
4876QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
4877 llvm::FoldingSetNodeID ID;
4878 ObjCObjectPointerType::Profile(ID, ObjectT);
4879
4880 void *InsertPos = nullptr;
4881 if (ObjCObjectPointerType *QT =
4882 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4883 return QualType(QT, 0);
4884
4885 // Find the canonical object type.
4886 QualType Canonical;
4887 if (!ObjectT.isCanonical()) {
4888 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4889
4890 // Regenerate InsertPos.
4891 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4892 }
4893
4894 // No match.
4895 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4896 auto *QType =
4897 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
4898
4899 Types.push_back(QType);
4900 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
4901 return QualType(QType, 0);
4902}
4903
4904/// getObjCInterfaceType - Return the unique reference to the type for the
4905/// specified ObjC interface decl. The list of protocols is optional.
4906QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4907 ObjCInterfaceDecl *PrevDecl) const {
4908 if (Decl->TypeForDecl)
4909 return QualType(Decl->TypeForDecl, 0);
4910
4911 if (PrevDecl) {
4912 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl")((PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"
) ? static_cast<void> (0) : __assert_fail ("PrevDecl->TypeForDecl && \"previous decl has no TypeForDecl\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 4912, __PRETTY_FUNCTION__))
;
4913 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4914 return QualType(PrevDecl->TypeForDecl, 0);
4915 }
4916
4917 // Prefer the definition, if there is one.
4918 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4919 Decl = Def;
4920
4921 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4922 auto *T = new (Mem) ObjCInterfaceType(Decl);
4923 Decl->TypeForDecl = T;
4924 Types.push_back(T);
4925 return QualType(T, 0);
4926}
4927
4928/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4929/// TypeOfExprType AST's (since expression's are never shared). For example,
4930/// multiple declarations that refer to "typeof(x)" all contain different
4931/// DeclRefExpr's. This doesn't effect the type checker, since it operates
4932/// on canonical type's (which are always unique).
4933QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
4934 TypeOfExprType *toe;
4935 if (tofExpr->isTypeDependent()) {
4936 llvm::FoldingSetNodeID ID;
4937 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
4938
4939 void *InsertPos = nullptr;
4940 DependentTypeOfExprType *Canon
4941 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4942 if (Canon) {
4943 // We already have a "canonical" version of an identical, dependent
4944 // typeof(expr) type. Use that as our canonical type.
4945 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
4946 QualType((TypeOfExprType*)Canon, 0));
4947 } else {
4948 // Build a new, canonical typeof(expr) type.
4949 Canon
4950 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
4951 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4952 toe = Canon;
4953 }
4954 } else {
4955 QualType Canonical = getCanonicalType(tofExpr->getType());
4956 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
4957 }
4958 Types.push_back(toe);
4959 return QualType(toe, 0);
4960}
4961
4962/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
4963/// TypeOfType nodes. The only motivation to unique these nodes would be
4964/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
4965/// an issue. This doesn't affect the type checker, since it operates
4966/// on canonical types (which are always unique).
4967QualType ASTContext::getTypeOfType(QualType tofType) const {
4968 QualType Canonical = getCanonicalType(tofType);
4969 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
4970 Types.push_back(tot);
4971 return QualType(tot, 0);
4972}
4973
4974/// Unlike many "get<Type>" functions, we don't unique DecltypeType
4975/// nodes. This would never be helpful, since each such type has its own
4976/// expression, and would not give a significant memory saving, since there
4977/// is an Expr tree under each such type.
4978QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
4979 DecltypeType *dt;
4980
4981 // C++11 [temp.type]p2:
4982 // If an expression e involves a template parameter, decltype(e) denotes a
4983 // unique dependent type. Two such decltype-specifiers refer to the same
4984 // type only if their expressions are equivalent (14.5.6.1).
4985 if (e->isInstantiationDependent()) {
4986 llvm::FoldingSetNodeID ID;
4987 DependentDecltypeType::Profile(ID, *this, e);
4988
4989 void *InsertPos = nullptr;
4990 DependentDecltypeType *Canon
4991 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
4992 if (!Canon) {
4993 // Build a new, canonical decltype(expr) type.
4994 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
4995 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
4996 }
4997 dt = new (*this, TypeAlignment)
4998 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
4999 } else {
5000 dt = new (*this, TypeAlignment)
5001 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
5002 }
5003 Types.push_back(dt);
5004 return QualType(dt, 0);
5005}
5006
5007/// getUnaryTransformationType - We don't unique these, since the memory
5008/// savings are minimal and these are rare.
5009QualType ASTContext::getUnaryTransformType(QualType BaseType,
5010 QualType UnderlyingType,
5011 UnaryTransformType::UTTKind Kind)
5012 const {
5013 UnaryTransformType *ut = nullptr;
5014
5015 if (BaseType->isDependentType()) {
5016 // Look in the folding set for an existing type.
5017 llvm::FoldingSetNodeID ID;
5018 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
5019
5020 void *InsertPos = nullptr;
5021 DependentUnaryTransformType *Canon
5022 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5023
5024 if (!Canon) {
5025 // Build a new, canonical __underlying_type(type) type.
5026 Canon = new (*this, TypeAlignment)
5027 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
5028 Kind);
5029 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5030 }
5031 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5032 QualType(), Kind,
5033 QualType(Canon, 0));
5034 } else {
5035 QualType CanonType = getCanonicalType(UnderlyingType);
5036 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5037 UnderlyingType, Kind,
5038 CanonType);
5039 }
5040 Types.push_back(ut);
5041 return QualType(ut, 0);
5042}
5043
5044/// getAutoType - Return the uniqued reference to the 'auto' type which has been
5045/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5046/// canonical deduced-but-dependent 'auto' type.
5047QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
5048 bool IsDependent, bool IsPack) const {
5049 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack")(((!IsPack || IsDependent) && "only use IsPack for a dependent pack"
) ? static_cast<void> (0) : __assert_fail ("(!IsPack || IsDependent) && \"only use IsPack for a dependent pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5049, __PRETTY_FUNCTION__))
;
5050 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
5051 return getAutoDeductType();
5052
5053 // Look in the folding set for an existing type.
5054 void *InsertPos = nullptr;
5055 llvm::FoldingSetNodeID ID;
5056 AutoType::Profile(ID, DeducedType, Keyword, IsDependent, IsPack);
5057 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5058 return QualType(AT, 0);
5059
5060 auto *AT = new (*this, TypeAlignment)
5061 AutoType(DeducedType, Keyword, IsDependent, IsPack);
5062 Types.push_back(AT);
5063 if (InsertPos)
5064 AutoTypes.InsertNode(AT, InsertPos);
5065 return QualType(AT, 0);
5066}
5067
5068/// Return the uniqued reference to the deduced template specialization type
5069/// which has been deduced to the given type, or to the canonical undeduced
5070/// such type, or the canonical deduced-but-dependent such type.
5071QualType ASTContext::getDeducedTemplateSpecializationType(
5072 TemplateName Template, QualType DeducedType, bool IsDependent) const {
5073 // Look in the folding set for an existing type.
5074 void *InsertPos = nullptr;
5075 llvm::FoldingSetNodeID ID;
5076 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5077 IsDependent);
5078 if (DeducedTemplateSpecializationType *DTST =
5079 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5080 return QualType(DTST, 0);
5081
5082 auto *DTST = new (*this, TypeAlignment)
5083 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5084 Types.push_back(DTST);
5085 if (InsertPos)
5086 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5087 return QualType(DTST, 0);
5088}
5089
5090/// getAtomicType - Return the uniqued reference to the atomic type for
5091/// the given value type.
5092QualType ASTContext::getAtomicType(QualType T) const {
5093 // Unique pointers, to guarantee there is only one pointer of a particular
5094 // structure.
5095 llvm::FoldingSetNodeID ID;
5096 AtomicType::Profile(ID, T);
5097
5098 void *InsertPos = nullptr;
5099 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5100 return QualType(AT, 0);
5101
5102 // If the atomic value type isn't canonical, this won't be a canonical type
5103 // either, so fill in the canonical type field.
5104 QualType Canonical;
5105 if (!T.isCanonical()) {
5106 Canonical = getAtomicType(getCanonicalType(T));
5107
5108 // Get the new insert position for the node we care about.
5109 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
5110 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5110, __PRETTY_FUNCTION__))
; (void)NewIP;
5111 }
5112 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
5113 Types.push_back(New);
5114 AtomicTypes.InsertNode(New, InsertPos);
5115 return QualType(New, 0);
5116}
5117
5118/// getAutoDeductType - Get type pattern for deducing against 'auto'.
5119QualType ASTContext::getAutoDeductType() const {
5120 if (AutoDeductTy.isNull())
5121 AutoDeductTy = QualType(
5122 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
5123 /*dependent*/false, /*pack*/false),
5124 0);
5125 return AutoDeductTy;
5126}
5127
5128/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5129QualType ASTContext::getAutoRRefDeductType() const {
5130 if (AutoRRefDeductTy.isNull())
5131 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5132 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern")((!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"
) ? static_cast<void> (0) : __assert_fail ("!AutoRRefDeductTy.isNull() && \"can't build 'auto &&' pattern\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5132, __PRETTY_FUNCTION__))
;
5133 return AutoRRefDeductTy;
5134}
5135
5136/// getTagDeclType - Return the unique reference to the type for the
5137/// specified TagDecl (struct/union/class/enum) decl.
5138QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
5139 assert(Decl)((Decl) ? static_cast<void> (0) : __assert_fail ("Decl"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5139, __PRETTY_FUNCTION__))
;
5140 // FIXME: What is the design on getTagDeclType when it requires casting
5141 // away const? mutable?
5142 return getTypeDeclType(const_cast<TagDecl*>(Decl));
5143}
5144
5145/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5146/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5147/// needs to agree with the definition in <stddef.h>.
5148CanQualType ASTContext::getSizeType() const {
5149 return getFromTargetType(Target->getSizeType());
5150}
5151
5152/// Return the unique signed counterpart of the integer type
5153/// corresponding to size_t.
5154CanQualType ASTContext::getSignedSizeType() const {
5155 return getFromTargetType(Target->getSignedSizeType());
5156}
5157
5158/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5159CanQualType ASTContext::getIntMaxType() const {
5160 return getFromTargetType(Target->getIntMaxType());
5161}
5162
5163/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5164CanQualType ASTContext::getUIntMaxType() const {
5165 return getFromTargetType(Target->getUIntMaxType());
5166}
5167
5168/// getSignedWCharType - Return the type of "signed wchar_t".
5169/// Used when in C++, as a GCC extension.
5170QualType ASTContext::getSignedWCharType() const {
5171 // FIXME: derive from "Target" ?
5172 return WCharTy;
5173}
5174
5175/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5176/// Used when in C++, as a GCC extension.
5177QualType ASTContext::getUnsignedWCharType() const {
5178 // FIXME: derive from "Target" ?
5179 return UnsignedIntTy;
5180}
5181
5182QualType ASTContext::getIntPtrType() const {
5183 return getFromTargetType(Target->getIntPtrType());
5184}
5185
5186QualType ASTContext::getUIntPtrType() const {
5187 return getCorrespondingUnsignedType(getIntPtrType());
5188}
5189
5190/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
5191/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5192QualType ASTContext::getPointerDiffType() const {
5193 return getFromTargetType(Target->getPtrDiffType(0));
5194}
5195
5196/// Return the unique unsigned counterpart of "ptrdiff_t"
5197/// integer type. The standard (C11 7.21.6.1p7) refers to this type
5198/// in the definition of %tu format specifier.
5199QualType ASTContext::getUnsignedPointerDiffType() const {
5200 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5201}
5202
5203/// Return the unique type for "pid_t" defined in
5204/// <sys/types.h>. We need this to compute the correct type for vfork().
5205QualType ASTContext::getProcessIDType() const {
5206 return getFromTargetType(Target->getProcessIDType());
5207}
5208
5209//===----------------------------------------------------------------------===//
5210// Type Operators
5211//===----------------------------------------------------------------------===//
5212
5213CanQualType ASTContext::getCanonicalParamType(QualType T) const {
5214 // Push qualifiers into arrays, and then discard any remaining
5215 // qualifiers.
5216 T = getCanonicalType(T);
5217 T = getVariableArrayDecayedType(T);
5218 const Type *Ty = T.getTypePtr();
5219 QualType Result;
5220 if (isa<ArrayType>(Ty)) {
5221 Result = getArrayDecayedType(QualType(Ty,0));
5222 } else if (isa<FunctionType>(Ty)) {
5223 Result = getPointerType(QualType(Ty, 0));
5224 } else {
5225 Result = QualType(Ty, 0);
5226 }
5227
5228 return CanQualType::CreateUnsafe(Result);
5229}
5230
5231QualType ASTContext::getUnqualifiedArrayType(QualType type,
5232 Qualifiers &quals) {
5233 SplitQualType splitType = type.getSplitUnqualifiedType();
5234
5235 // FIXME: getSplitUnqualifiedType() actually walks all the way to
5236 // the unqualified desugared type and then drops it on the floor.
5237 // We then have to strip that sugar back off with
5238 // getUnqualifiedDesugaredType(), which is silly.
5239 const auto *AT =
5240 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
5241
5242 // If we don't have an array, just use the results in splitType.
5243 if (!AT) {
5244 quals = splitType.Quals;
5245 return QualType(splitType.Ty, 0);
5246 }
5247
5248 // Otherwise, recurse on the array's element type.
5249 QualType elementType = AT->getElementType();
5250 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5251
5252 // If that didn't change the element type, AT has no qualifiers, so we
5253 // can just use the results in splitType.
5254 if (elementType == unqualElementType) {
5255 assert(quals.empty())((quals.empty()) ? static_cast<void> (0) : __assert_fail
("quals.empty()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5255, __PRETTY_FUNCTION__))
; // from the recursive call
5256 quals = splitType.Quals;
5257 return QualType(splitType.Ty, 0);
5258 }
5259
5260 // Otherwise, add in the qualifiers from the outermost type, then
5261 // build the type back up.
5262 quals.addConsistentQualifiers(splitType.Quals);
5263
5264 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
5265 return getConstantArrayType(unqualElementType, CAT->getSize(),
5266 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
5267 }
5268
5269 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
5270 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
5271 }
5272
5273 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
5274 return getVariableArrayType(unqualElementType,
5275 VAT->getSizeExpr(),
5276 VAT->getSizeModifier(),
5277 VAT->getIndexTypeCVRQualifiers(),
5278 VAT->getBracketsRange());
5279 }
5280
5281 const auto *DSAT = cast<DependentSizedArrayType>(AT);
5282 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
5283 DSAT->getSizeModifier(), 0,
5284 SourceRange());
5285}
5286
5287/// Attempt to unwrap two types that may both be array types with the same bound
5288/// (or both be array types of unknown bound) for the purpose of comparing the
5289/// cv-decomposition of two types per C++ [conv.qual].
5290bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5291 bool UnwrappedAny = false;
5292 while (true) {
5293 auto *AT1 = getAsArrayType(T1);
5294 if (!AT1) return UnwrappedAny;
5295
5296 auto *AT2 = getAsArrayType(T2);
5297 if (!AT2) return UnwrappedAny;
5298
5299 // If we don't have two array types with the same constant bound nor two
5300 // incomplete array types, we've unwrapped everything we can.
5301 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5302 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5303 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
5304 return UnwrappedAny;
5305 } else if (!isa<IncompleteArrayType>(AT1) ||
5306 !isa<IncompleteArrayType>(AT2)) {
5307 return UnwrappedAny;
5308 }
5309
5310 T1 = AT1->getElementType();
5311 T2 = AT2->getElementType();
5312 UnwrappedAny = true;
5313 }
5314}
5315
5316/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5317///
5318/// If T1 and T2 are both pointer types of the same kind, or both array types
5319/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5320/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5321///
5322/// This function will typically be called in a loop that successively
5323/// "unwraps" pointer and pointer-to-member types to compare them at each
5324/// level.
5325///
5326/// \return \c true if a pointer type was unwrapped, \c false if we reached a
5327/// pair of types that can't be unwrapped further.
5328bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
5329 UnwrapSimilarArrayTypes(T1, T2);
5330
5331 const auto *T1PtrType = T1->getAs<PointerType>();
5332 const auto *T2PtrType = T2->getAs<PointerType>();
5333 if (T1PtrType && T2PtrType) {
5334 T1 = T1PtrType->getPointeeType();
5335 T2 = T2PtrType->getPointeeType();
5336 return true;
5337 }
5338
5339 const auto *T1MPType = T1->getAs<MemberPointerType>();
5340 const auto *T2MPType = T2->getAs<MemberPointerType>();
5341 if (T1MPType && T2MPType &&
5342 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
5343 QualType(T2MPType->getClass(), 0))) {
5344 T1 = T1MPType->getPointeeType();
5345 T2 = T2MPType->getPointeeType();
5346 return true;
5347 }
5348
5349 if (getLangOpts().ObjC) {
5350 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5351 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
5352 if (T1OPType && T2OPType) {
5353 T1 = T1OPType->getPointeeType();
5354 T2 = T2OPType->getPointeeType();
5355 return true;
5356 }
5357 }
5358
5359 // FIXME: Block pointers, too?
5360
5361 return false;
5362}
5363
5364bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5365 while (true) {
5366 Qualifiers Quals;
5367 T1 = getUnqualifiedArrayType(T1, Quals);
5368 T2 = getUnqualifiedArrayType(T2, Quals);
5369 if (hasSameType(T1, T2))
5370 return true;
5371 if (!UnwrapSimilarTypes(T1, T2))
5372 return false;
5373 }
5374}
5375
5376bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5377 while (true) {
5378 Qualifiers Quals1, Quals2;
5379 T1 = getUnqualifiedArrayType(T1, Quals1);
5380 T2 = getUnqualifiedArrayType(T2, Quals2);
5381
5382 Quals1.removeCVRQualifiers();
5383 Quals2.removeCVRQualifiers();
5384 if (Quals1 != Quals2)
5385 return false;
5386
5387 if (hasSameType(T1, T2))
5388 return true;
5389
5390 if (!UnwrapSimilarTypes(T1, T2))
5391 return false;
5392 }
5393}
5394
5395DeclarationNameInfo
5396ASTContext::getNameForTemplate(TemplateName Name,
5397 SourceLocation NameLoc) const {
5398 switch (Name.getKind()) {
5399 case TemplateName::QualifiedTemplate:
5400 case TemplateName::Template:
5401 // DNInfo work in progress: CHECKME: what about DNLoc?
5402 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5403 NameLoc);
5404
5405 case TemplateName::OverloadedTemplate: {
5406 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5407 // DNInfo work in progress: CHECKME: what about DNLoc?
5408 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5409 }
5410
5411 case TemplateName::AssumedTemplate: {
5412 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5413 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5414 }
5415
5416 case TemplateName::DependentTemplate: {
5417 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5418 DeclarationName DName;
5419 if (DTN->isIdentifier()) {
5420 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5421 return DeclarationNameInfo(DName, NameLoc);
5422 } else {
5423 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5424 // DNInfo work in progress: FIXME: source locations?
5425 DeclarationNameLoc DNLoc;
5426 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5427 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5428 return DeclarationNameInfo(DName, NameLoc, DNLoc);
5429 }
5430 }
5431
5432 case TemplateName::SubstTemplateTemplateParm: {
5433 SubstTemplateTemplateParmStorage *subst
5434 = Name.getAsSubstTemplateTemplateParm();
5435 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5436 NameLoc);
5437 }
5438
5439 case TemplateName::SubstTemplateTemplateParmPack: {
5440 SubstTemplateTemplateParmPackStorage *subst
5441 = Name.getAsSubstTemplateTemplateParmPack();
5442 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5443 NameLoc);
5444 }
5445 }
5446
5447 llvm_unreachable("bad template name kind!")::llvm::llvm_unreachable_internal("bad template name kind!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5447)
;
5448}
5449
5450TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
5451 switch (Name.getKind()) {
5452 case TemplateName::QualifiedTemplate:
5453 case TemplateName::Template: {
5454 TemplateDecl *Template = Name.getAsTemplateDecl();
5455 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
5456 Template = getCanonicalTemplateTemplateParmDecl(TTP);
5457
5458 // The canonical template name is the canonical template declaration.
5459 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
5460 }
5461
5462 case TemplateName::OverloadedTemplate:
5463 case TemplateName::AssumedTemplate:
5464 llvm_unreachable("cannot canonicalize unresolved template")::llvm::llvm_unreachable_internal("cannot canonicalize unresolved template"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5464)
;
5465
5466 case TemplateName::DependentTemplate: {
5467 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5468 assert(DTN && "Non-dependent template names must refer to template decls.")((DTN && "Non-dependent template names must refer to template decls."
) ? static_cast<void> (0) : __assert_fail ("DTN && \"Non-dependent template names must refer to template decls.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5468, __PRETTY_FUNCTION__))
;
5469 return DTN->CanonicalTemplateName;
5470 }
5471
5472 case TemplateName::SubstTemplateTemplateParm: {
5473 SubstTemplateTemplateParmStorage *subst
5474 = Name.getAsSubstTemplateTemplateParm();
5475 return getCanonicalTemplateName(subst->getReplacement());
5476 }
5477
5478 case TemplateName::SubstTemplateTemplateParmPack: {
5479 SubstTemplateTemplateParmPackStorage *subst
5480 = Name.getAsSubstTemplateTemplateParmPack();
5481 TemplateTemplateParmDecl *canonParameter
5482 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5483 TemplateArgument canonArgPack
5484 = getCanonicalTemplateArgument(subst->getArgumentPack());
5485 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5486 }
5487 }
5488
5489 llvm_unreachable("bad template name!")::llvm::llvm_unreachable_internal("bad template name!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5489)
;
5490}
5491
5492bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5493 X = getCanonicalTemplateName(X);
5494 Y = getCanonicalTemplateName(Y);
5495 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5496}
5497
5498TemplateArgument
5499ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
5500 switch (Arg.getKind()) {
5501 case TemplateArgument::Null:
5502 return Arg;
5503
5504 case TemplateArgument::Expression:
5505 return Arg;
5506
5507 case TemplateArgument::Declaration: {
5508 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
5509 return TemplateArgument(D, Arg.getParamTypeForDecl());
5510 }
5511
5512 case TemplateArgument::NullPtr:
5513 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5514 /*isNullPtr*/true);
5515
5516 case TemplateArgument::Template:
5517 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
5518
5519 case TemplateArgument::TemplateExpansion:
5520 return TemplateArgument(getCanonicalTemplateName(
5521 Arg.getAsTemplateOrTemplatePattern()),
5522 Arg.getNumTemplateExpansions());
5523
5524 case TemplateArgument::Integral:
5525 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
5526
5527 case TemplateArgument::Type:
5528 return TemplateArgument(getCanonicalType(Arg.getAsType()));
5529
5530 case TemplateArgument::Pack: {
5531 if (Arg.pack_size() == 0)
5532 return Arg;
5533
5534 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
5535 unsigned Idx = 0;
5536 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
5537 AEnd = Arg.pack_end();
5538 A != AEnd; (void)++A, ++Idx)
5539 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
5540
5541 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
5542 }
5543 }
5544
5545 // Silence GCC warning
5546 llvm_unreachable("Unhandled template argument kind")::llvm::llvm_unreachable_internal("Unhandled template argument kind"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5546)
;
5547}
5548
5549NestedNameSpecifier *
5550ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
5551 if (!NNS)
5552 return nullptr;
5553
5554 switch (NNS->getKind()) {
5555 case NestedNameSpecifier::Identifier:
5556 // Canonicalize the prefix but keep the identifier the same.
5557 return NestedNameSpecifier::Create(*this,
5558 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5559 NNS->getAsIdentifier());
5560
5561 case NestedNameSpecifier::Namespace:
5562 // A namespace is canonical; build a nested-name-specifier with
5563 // this namespace and no prefix.
5564 return NestedNameSpecifier::Create(*this, nullptr,
5565 NNS->getAsNamespace()->getOriginalNamespace());
5566
5567 case NestedNameSpecifier::NamespaceAlias:
5568 // A namespace is canonical; build a nested-name-specifier with
5569 // this namespace and no prefix.
5570 return NestedNameSpecifier::Create(*this, nullptr,
5571 NNS->getAsNamespaceAlias()->getNamespace()
5572 ->getOriginalNamespace());
5573
5574 case NestedNameSpecifier::TypeSpec:
5575 case NestedNameSpecifier::TypeSpecWithTemplate: {
5576 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
5577
5578 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5579 // break it apart into its prefix and identifier, then reconsititute those
5580 // as the canonical nested-name-specifier. This is required to canonicalize
5581 // a dependent nested-name-specifier involving typedefs of dependent-name
5582 // types, e.g.,
5583 // typedef typename T::type T1;
5584 // typedef typename T1::type T2;
5585 if (const auto *DNT = T->getAs<DependentNameType>())
5586 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
5587 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
5588
5589 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5590 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5591 // first place?
5592 return NestedNameSpecifier::Create(*this, nullptr, false,
5593 const_cast<Type *>(T.getTypePtr()));
5594 }
5595
5596 case NestedNameSpecifier::Global:
5597 case NestedNameSpecifier::Super:
5598 // The global specifier and __super specifer are canonical and unique.
5599 return NNS;
5600 }
5601
5602 llvm_unreachable("Invalid NestedNameSpecifier::Kind!")::llvm::llvm_unreachable_internal("Invalid NestedNameSpecifier::Kind!"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5602)
;
5603}
5604
5605const ArrayType *ASTContext::getAsArrayType(QualType T) const {
5606 // Handle the non-qualified case efficiently.
5607 if (!T.hasLocalQualifiers()) {
5608 // Handle the common positive case fast.
5609 if (const auto *AT = dyn_cast<ArrayType>(T))
5610 return AT;
5611 }
5612
5613 // Handle the common negative case fast.
5614 if (!isa<ArrayType>(T.getCanonicalType()))
5615 return nullptr;
5616
5617 // Apply any qualifiers from the array type to the element type. This
5618 // implements C99 6.7.3p8: "If the specification of an array type includes
5619 // any type qualifiers, the element type is so qualified, not the array type."
5620
5621 // If we get here, we either have type qualifiers on the type, or we have
5622 // sugar such as a typedef in the way. If we have type qualifiers on the type
5623 // we must propagate them down into the element type.
5624
5625 SplitQualType split = T.getSplitDesugaredType();
5626 Qualifiers qs = split.Quals;
5627
5628 // If we have a simple case, just return now.
5629 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
5630 if (!ATy || qs.empty())
5631 return ATy;
5632
5633 // Otherwise, we have an array and we have qualifiers on it. Push the
5634 // qualifiers into the array element type and return a new array type.
5635 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
5636
5637 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
5638 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5639 CAT->getSizeExpr(),
5640 CAT->getSizeModifier(),
5641 CAT->getIndexTypeCVRQualifiers()));
5642 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
5643 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5644 IAT->getSizeModifier(),
5645 IAT->getIndexTypeCVRQualifiers()));
5646
5647 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
5648 return cast<ArrayType>(
5649 getDependentSizedArrayType(NewEltTy,
5650 DSAT->getSizeExpr(),
5651 DSAT->getSizeModifier(),
5652 DSAT->getIndexTypeCVRQualifiers(),
5653 DSAT->getBracketsRange()));
5654
5655 const auto *VAT = cast<VariableArrayType>(ATy);
5656 return cast<ArrayType>(getVariableArrayType(NewEltTy,
5657 VAT->getSizeExpr(),
5658 VAT->getSizeModifier(),
5659 VAT->getIndexTypeCVRQualifiers(),
5660 VAT->getBracketsRange()));
5661}
5662
5663QualType ASTContext::getAdjustedParameterType(QualType T) const {
5664 if (T->isArrayType() || T->isFunctionType())
5665 return getDecayedType(T);
5666 return T;
5667}
5668
5669QualType ASTContext::getSignatureParameterType(QualType T) const {
5670 T = getVariableArrayDecayedType(T);
5671 T = getAdjustedParameterType(T);
5672 return T.getUnqualifiedType();
5673}
5674
5675QualType ASTContext::getExceptionObjectType(QualType T) const {
5676 // C++ [except.throw]p3:
5677 // A throw-expression initializes a temporary object, called the exception
5678 // object, the type of which is determined by removing any top-level
5679 // cv-qualifiers from the static type of the operand of throw and adjusting
5680 // the type from "array of T" or "function returning T" to "pointer to T"
5681 // or "pointer to function returning T", [...]
5682 T = getVariableArrayDecayedType(T);
5683 if (T->isArrayType() || T->isFunctionType())
5684 T = getDecayedType(T);
5685 return T.getUnqualifiedType();
5686}
5687
5688/// getArrayDecayedType - Return the properly qualified result of decaying the
5689/// specified array type to a pointer. This operation is non-trivial when
5690/// handling typedefs etc. The canonical type of "T" must be an array type,
5691/// this returns a pointer to a properly qualified element of the array.
5692///
5693/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
5694QualType ASTContext::getArrayDecayedType(QualType Ty) const {
5695 // Get the element type with 'getAsArrayType' so that we don't lose any
5696 // typedefs in the element type of the array. This also handles propagation
5697 // of type qualifiers from the array type into the element type if present
5698 // (C99 6.7.3p8).
5699 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5700 assert(PrettyArrayType && "Not an array type!")((PrettyArrayType && "Not an array type!") ? static_cast
<void> (0) : __assert_fail ("PrettyArrayType && \"Not an array type!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5700, __PRETTY_FUNCTION__))
;
5701
5702 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
5703
5704 // int x[restrict 4] -> int *restrict
5705 QualType Result = getQualifiedType(PtrTy,
5706 PrettyArrayType->getIndexTypeQualifiers());
5707
5708 // int x[_Nullable] -> int * _Nullable
5709 if (auto Nullability = Ty->getNullability(*this)) {
5710 Result = const_cast<ASTContext *>(this)->getAttributedType(
5711 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5712 }
5713 return Result;
5714}
5715
5716QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5717 return getBaseElementType(array->getElementType());
5718}
5719
5720QualType ASTContext::getBaseElementType(QualType type) const {
5721 Qualifiers qs;
5722 while (true) {
5723 SplitQualType split = type.getSplitDesugaredType();
5724 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
5725 if (!array) break;
5726
5727 type = array->getElementType();
5728 qs.addConsistentQualifiers(split.Quals);
5729 }
5730
5731 return getQualifiedType(type, qs);
5732}
5733
5734/// getConstantArrayElementCount - Returns number of constant array elements.
5735uint64_t
5736ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5737 uint64_t ElementCount = 1;
5738 do {
5739 ElementCount *= CA->getSize().getZExtValue();
5740 CA = dyn_cast_or_null<ConstantArrayType>(
5741 CA->getElementType()->getAsArrayTypeUnsafe());
5742 } while (CA);
5743 return ElementCount;
5744}
5745
5746/// getFloatingRank - Return a relative rank for floating point types.
5747/// This routine will assert if passed a built-in type that isn't a float.
5748static FloatingRank getFloatingRank(QualType T) {
5749 if (const auto *CT = T->getAs<ComplexType>())
5750 return getFloatingRank(CT->getElementType());
5751
5752 switch (T->castAs<BuiltinType>()->getKind()) {
5753 default: llvm_unreachable("getFloatingRank(): not a floating type")::llvm::llvm_unreachable_internal("getFloatingRank(): not a floating type"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5753)
;
5754 case BuiltinType::Float16: return Float16Rank;
5755 case BuiltinType::Half: return HalfRank;
5756 case BuiltinType::Float: return FloatRank;
5757 case BuiltinType::Double: return DoubleRank;
5758 case BuiltinType::LongDouble: return LongDoubleRank;
5759 case BuiltinType::Float128: return Float128Rank;
5760 }
5761}
5762
5763/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5764/// point or a complex type (based on typeDomain/typeSize).
5765/// 'typeDomain' is a real floating point or complex type.
5766/// 'typeSize' is a real floating point or complex type.
5767QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5768 QualType Domain) const {
5769 FloatingRank EltRank = getFloatingRank(Size);
5770 if (Domain->isComplexType()) {
5771 switch (EltRank) {
5772 case Float16Rank:
5773 case HalfRank: llvm_unreachable("Complex half is not supported")::llvm::llvm_unreachable_internal("Complex half is not supported"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5773)
;
5774 case FloatRank: return FloatComplexTy;
5775 case DoubleRank: return DoubleComplexTy;
5776 case LongDoubleRank: return LongDoubleComplexTy;
5777 case Float128Rank: return Float128ComplexTy;
5778 }
5779 }
5780
5781 assert(Domain->isRealFloatingType() && "Unknown domain!")((Domain->isRealFloatingType() && "Unknown domain!"
) ? static_cast<void> (0) : __assert_fail ("Domain->isRealFloatingType() && \"Unknown domain!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5781, __PRETTY_FUNCTION__))
;
5782 switch (EltRank) {
5783 case Float16Rank: return HalfTy;
5784 case HalfRank: return HalfTy;
5785 case FloatRank: return FloatTy;
5786 case DoubleRank: return DoubleTy;
5787 case LongDoubleRank: return LongDoubleTy;
5788 case Float128Rank: return Float128Ty;
5789 }
5790 llvm_unreachable("getFloatingRank(): illegal value for rank")::llvm::llvm_unreachable_internal("getFloatingRank(): illegal value for rank"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5790)
;
5791}
5792
5793/// getFloatingTypeOrder - Compare the rank of the two specified floating
5794/// point types, ignoring the domain of the type (i.e. 'double' ==
5795/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
5796/// LHS < RHS, return -1.
5797int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
5798 FloatingRank LHSR = getFloatingRank(LHS);
5799 FloatingRank RHSR = getFloatingRank(RHS);
5800
5801 if (LHSR == RHSR)
5802 return 0;
5803 if (LHSR > RHSR)
5804 return 1;
5805 return -1;
5806}
5807
5808int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
5809 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
5810 return 0;
5811 return getFloatingTypeOrder(LHS, RHS);
5812}
5813
5814/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5815/// routine will assert if passed a built-in type that isn't an integer or enum,
5816/// or if it is not canonicalized.
5817unsigned ASTContext::getIntegerRank(const Type *T) const {
5818 assert(T->isCanonicalUnqualified() && "T should be canonicalized")((T->isCanonicalUnqualified() && "T should be canonicalized"
) ? static_cast<void> (0) : __assert_fail ("T->isCanonicalUnqualified() && \"T should be canonicalized\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5818, __PRETTY_FUNCTION__))
;
5819
5820 switch (cast<BuiltinType>(T)->getKind()) {
5821 default: llvm_unreachable("getIntegerRank(): not a built-in integer")::llvm::llvm_unreachable_internal("getIntegerRank(): not a built-in integer"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTContext.cpp"
, 5821)
;
5822 case BuiltinType::Bool:
5823 return 1 + (getIntWidth(BoolTy) << 3);
5824 case BuiltinType::Char_S:
5825 case BuiltinType::Char_U:
5826 case BuiltinType::SChar:
5827 case BuiltinType::UChar:
5828 return 2 + (getIntWidth(CharTy) << 3);
5829 case BuiltinType::Short:
5830 case BuiltinType::UShort:
5831 return 3 + (getIntWidth(ShortTy) << 3);
5832 case BuiltinType::Int:
5833 case BuiltinType::UInt:
5834 return 4 + (getIntWidth(IntTy) << 3);
5835