Bug Summary

File:tools/clang/lib/AST/ASTContext.cpp
Warning:line 10246, column 5
Potential memory leak

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