Bug Summary

File:tools/clang/lib/AST/ASTContext.cpp
Warning:line 9847, column 15
Potential leak of memory pointed to by 'Vector'

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