Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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