Bug Summary

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

Annotated Source Code

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/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Comment.h"
20#include "clang/AST/CommentCommandTraits.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclContextInternals.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/DeclTemplate.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExternalASTSource.h"
28#include "clang/AST/Mangle.h"
29#include "clang/AST/MangleNumberingContext.h"
30#include "clang/AST/RecordLayout.h"
31#include "clang/AST/RecursiveASTVisitor.h"
32#include "clang/AST/TypeLoc.h"
33#include "clang/AST/VTableBuilder.h"
34#include "clang/Basic/Builtins.h"
35#include "clang/Basic/SourceManager.h"
36#include "clang/Basic/TargetInfo.h"
37#include "llvm/ADT/StringExtras.h"
38#include "llvm/ADT/Triple.h"
39#include "llvm/Support/Capacity.h"
40#include "llvm/Support/MathExtras.h"
41#include "llvm/Support/raw_ostream.h"
42#include <map>
43
44using namespace clang;
45
46unsigned ASTContext::NumImplicitDefaultConstructors;
47unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
48unsigned ASTContext::NumImplicitCopyConstructors;
49unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
50unsigned ASTContext::NumImplicitMoveConstructors;
51unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
52unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
54unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
56unsigned ASTContext::NumImplicitDestructors;
57unsigned ASTContext::NumImplicitDestructorsDeclared;
58
59enum FloatingRank {
60 HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
61};
62
63RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
64 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
66
67#ifndef NDEBUG
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),((std::is_sorted(RawComments.begin(), RawComments.end(), BeforeThanCompare
<RawComment>(SourceMgr))) ? static_cast<void> (0)
: __assert_fail ("std::is_sorted(RawComments.begin(), RawComments.end(), BeforeThanCompare<RawComment>(SourceMgr))"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 70, __PRETTY_FUNCTION__))
70 BeforeThanCompare<RawComment>(SourceMgr)))((std::is_sorted(RawComments.begin(), RawComments.end(), BeforeThanCompare
<RawComment>(SourceMgr))) ? static_cast<void> (0)
: __assert_fail ("std::is_sorted(RawComments.begin(), RawComments.end(), BeforeThanCompare<RawComment>(SourceMgr))"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 70, __PRETTY_FUNCTION__))
;
71#endif
72
73 CommentsLoaded = true;
74 }
75
76 assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 76, __PRETTY_FUNCTION__))
;
77
78 // User can not attach documentation to implicit declarations.
79 if (D->isImplicit())
80 return nullptr;
81
82 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
85 return nullptr;
86 }
87
88 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
91 return nullptr;
92 }
93
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
96 return nullptr;
97 }
98
99 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
104 return nullptr;
105 }
106
107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
109 return nullptr;
110 }
111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112 // When tag declaration (but not definition!) is part of the
113 // decl-specifier-seq of some other declaration, it doesn't get comment
114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
115 return nullptr;
116 }
117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
119 return nullptr;
120
121 // TODO: we could look up template parameter documentation in the template
122 // documentation.
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
126 return nullptr;
127
128 ArrayRef<RawComment *> RawComments = Comments.getComments();
129
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
132 return nullptr;
133
134 // Find declaration location.
135 // For Objective-C declarations we generally don't expect to have multiple
136 // declarators, thus use declaration starting location as the "declaration
137 // location".
138 // For all other declarations multiple declarators are used quite frequently,
139 // so we use the location of the identifier as the "declaration location".
140 SourceLocation DeclLoc;
141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
142 isa<ObjCPropertyDecl>(D) ||
143 isa<RedeclarableTemplateDecl>(D) ||
144 isa<ClassTemplateSpecializationDecl>(D))
145 DeclLoc = D->getLocStart();
146 else {
147 DeclLoc = D->getLocation();
148 if (DeclLoc.isMacroID()) {
149 if (isa<TypedefDecl>(D)) {
150 // If location of the typedef name is in a macro, it is because being
151 // declared via a macro. Try using declaration's starting location as
152 // the "declaration location".
153 DeclLoc = D->getLocStart();
154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155 // If location of the tag decl is inside a macro, but the spelling of
156 // the tag name comes from a macro argument, it looks like a special
157 // macro like NS_ENUM is being used to define the tag decl. In that
158 // case, adjust the source location to the expansion loc so that we can
159 // attach the comment to the tag decl.
160 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161 TD->isCompleteDefinition())
162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
163 }
164 }
165 }
166
167 // If the declaration doesn't map directly to a location in a file, we
168 // can't find the comment.
169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
170 return nullptr;
171
172 // Find the comment that occurs just after this declaration.
173 ArrayRef<RawComment *>::iterator Comment;
174 {
175 // When searching for comments during parsing, the comment we are looking
176 // for is usually among the last two comments we parsed -- check them
177 // first.
178 RawComment CommentAtDeclLoc(
179 SourceMgr, SourceRange(DeclLoc), false,
180 LangOpts.CommentOpts.ParseAllComments);
181 BeforeThanCompare<RawComment> Compare(SourceMgr);
182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184 if (!Found && RawComments.size() >= 2) {
185 MaybeBeforeDecl--;
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
187 }
188
189 if (Found) {
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),((Comment == std::lower_bound(RawComments.begin(), RawComments
.end(), &CommentAtDeclLoc, Compare)) ? static_cast<void
> (0) : __assert_fail ("Comment == std::lower_bound(RawComments.begin(), RawComments.end(), &CommentAtDeclLoc, Compare)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 192, __PRETTY_FUNCTION__))
192 &CommentAtDeclLoc, Compare))((Comment == std::lower_bound(RawComments.begin(), RawComments
.end(), &CommentAtDeclLoc, Compare)) ? static_cast<void
> (0) : __assert_fail ("Comment == std::lower_bound(RawComments.begin(), RawComments.end(), &CommentAtDeclLoc, Compare)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 192, __PRETTY_FUNCTION__))
;
193 } else {
194 // Slow path.
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
197 }
198 }
199
200 // Decompose the location for the declaration and find the beginning of the
201 // file buffer.
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
203
204 // First check whether we have a trailing comment.
205 if (Comment != RawComments.end() &&
206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
209 std::pair<FileID, unsigned> CommentBeginDecomp
210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
211 // Check that Doxygen trailing comment comes after the declaration, starts
212 // on the same line and in the same file as the declaration.
213 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216 CommentBeginDecomp.second)) {
217 return *Comment;
218 }
219 }
220
221 // The comment just after the declaration was not a trailing comment.
222 // Let's look at the previous comment.
223 if (Comment == RawComments.begin())
224 return nullptr;
225 --Comment;
226
227 // Check that we actually have a non-member Doxygen comment.
228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
229 return nullptr;
230
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
234
235 // If the comment and the declaration aren't in the same file, then they
236 // aren't related.
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
238 return nullptr;
239
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
243 &Invalid).data();
244 if (Invalid)
245 return nullptr;
246
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
250
251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
253 if (Text.find_first_of(";{}#@") != StringRef::npos)
254 return nullptr;
255
256 return *Comment;
257}
258
259namespace {
260/// If we have a 'templated' declaration for a template, adjust 'D' to
261/// refer to the actual template.
262/// If we have an implicit instantiation, adjust 'D' to refer to template.
263const Decl *adjustDeclToTemplate(const Decl *D) {
264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
265 // Is this function declaration part of a function template?
266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
267 return FTD;
268
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
271 return D;
272
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
275 return FTD;
276
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
280 return MemberDecl;
281
282 return D;
283 }
284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
286 // template?
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
289 return MemberDecl;
290
291 return D;
292 }
293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294 // Is this class declaration part of a class template?
295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
296 return CTD;
297
298 // Class is an implicit instantiation of a class template or partial
299 // specialization?
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
303 return D;
304 llvm::PointerUnion<ClassTemplateDecl *,
305 ClassTemplatePartialSpecializationDecl *>
306 PU = CTSD->getSpecializedTemplateOrPartial();
307 return PU.is<ClassTemplateDecl*>() ?
308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309 static_cast<const Decl*>(
310 PU.get<ClassTemplatePartialSpecializationDecl *>());
311 }
312
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
317
318 return D;
319 }
320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321 // Enum is instantiated from a member definition of a class template?
322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
323 return MemberDecl;
324
325 return D;
326 }
327 // FIXME: Adjust alias templates?
328 return D;
329}
330} // anonymous namespace
331
332const RawComment *ASTContext::getRawCommentForAnyRedecl(
333 const Decl *D,
334 const Decl **OriginalDecl) const {
335 D = adjustDeclToTemplate(D);
336
337 // Check whether we have cached a comment for this declaration already.
338 {
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
344 if (OriginalDecl)
345 *OriginalDecl = Raw.getOriginalDecl();
346 return Raw.getRaw();
347 }
348 }
349 }
350
351 // Search for comments attached to declarations in the redeclaration chain.
352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
354 for (auto I : D->redecls()) {
355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
356 RedeclComments.find(I);
357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
360 RC = Raw.getRaw();
361 OriginalDeclForRC = Raw.getOriginalDecl();
362 break;
363 }
364 } else {
365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
367 RawCommentAndCacheFlags Raw;
368 if (RC) {
369 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
370 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
371 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
372 Raw.setRaw(RC);
373 } else
374 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
375 Raw.setOriginalDecl(I);
376 RedeclComments[I] = Raw;
377 if (RC)
378 break;
379 }
380 }
381
382 // If we found a comment, it should be a documentation comment.
383 assert(!RC || RC->isDocumentation())((!RC || RC->isDocumentation()) ? static_cast<void> (
0) : __assert_fail ("!RC || RC->isDocumentation()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 383, __PRETTY_FUNCTION__))
;
384
385 if (OriginalDecl)
386 *OriginalDecl = OriginalDeclForRC;
387
388 // Update cache for every declaration in the redeclaration chain.
389 RawCommentAndCacheFlags Raw;
390 Raw.setRaw(RC);
391 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
392 Raw.setOriginalDecl(OriginalDeclForRC);
393
394 for (auto I : D->redecls()) {
395 RawCommentAndCacheFlags &R = RedeclComments[I];
396 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
397 R = Raw;
398 }
399
400 return RC;
401}
402
403static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
404 SmallVectorImpl<const NamedDecl *> &Redeclared) {
405 const DeclContext *DC = ObjCMethod->getDeclContext();
406 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
407 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
408 if (!ID)
409 return;
410 // Add redeclared method here.
411 for (const auto *Ext : ID->known_extensions()) {
412 if (ObjCMethodDecl *RedeclaredMethod =
413 Ext->getMethod(ObjCMethod->getSelector(),
414 ObjCMethod->isInstanceMethod()))
415 Redeclared.push_back(RedeclaredMethod);
416 }
417 }
418}
419
420comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
421 const Decl *D) const {
422 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
423 ThisDeclInfo->CommentDecl = D;
424 ThisDeclInfo->IsFilled = false;
425 ThisDeclInfo->fill();
426 ThisDeclInfo->CommentDecl = FC->getDecl();
427 if (!ThisDeclInfo->TemplateParameters)
428 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
429 comments::FullComment *CFC =
430 new (*this) comments::FullComment(FC->getBlocks(),
431 ThisDeclInfo);
432 return CFC;
433}
434
435comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
436 const RawComment *RC = getRawCommentForDeclNoCache(D);
437 return RC ? RC->parse(*this, nullptr, D) : nullptr;
438}
439
440comments::FullComment *ASTContext::getCommentForDecl(
441 const Decl *D,
442 const Preprocessor *PP) const {
443 if (D->isInvalidDecl())
444 return nullptr;
445 D = adjustDeclToTemplate(D);
446
447 const Decl *Canonical = D->getCanonicalDecl();
448 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
449 ParsedComments.find(Canonical);
450
451 if (Pos != ParsedComments.end()) {
452 if (Canonical != D) {
453 comments::FullComment *FC = Pos->second;
454 comments::FullComment *CFC = cloneFullComment(FC, D);
455 return CFC;
456 }
457 return Pos->second;
458 }
459
460 const Decl *OriginalDecl;
461
462 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
463 if (!RC) {
464 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
465 SmallVector<const NamedDecl*, 8> Overridden;
466 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
467 if (OMD && OMD->isPropertyAccessor())
468 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
469 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
470 return cloneFullComment(FC, D);
471 if (OMD)
472 addRedeclaredMethods(OMD, Overridden);
473 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
474 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
475 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
476 return cloneFullComment(FC, D);
477 }
478 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
479 // Attach any tag type's documentation to its typedef if latter
480 // does not have one of its own.
481 QualType QT = TD->getUnderlyingType();
482 if (const TagType *TT = QT->getAs<TagType>())
483 if (const Decl *TD = TT->getDecl())
484 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
485 return cloneFullComment(FC, D);
486 }
487 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
488 while (IC->getSuperClass()) {
489 IC = IC->getSuperClass();
490 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
491 return cloneFullComment(FC, D);
492 }
493 }
494 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
495 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
496 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
497 return cloneFullComment(FC, D);
498 }
499 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
500 if (!(RD = RD->getDefinition()))
501 return nullptr;
502 // Check non-virtual bases.
503 for (const auto &I : RD->bases()) {
504 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
505 continue;
506 QualType Ty = I.getType();
507 if (Ty.isNull())
508 continue;
509 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
510 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
511 continue;
512
513 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
514 return cloneFullComment(FC, D);
515 }
516 }
517 // Check virtual bases.
518 for (const auto &I : RD->vbases()) {
519 if (I.getAccessSpecifier() != AS_public)
520 continue;
521 QualType Ty = I.getType();
522 if (Ty.isNull())
523 continue;
524 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
525 if (!(VirtualBase= VirtualBase->getDefinition()))
526 continue;
527 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
528 return cloneFullComment(FC, D);
529 }
530 }
531 }
532 return nullptr;
533 }
534
535 // If the RawComment was attached to other redeclaration of this Decl, we
536 // should parse the comment in context of that other Decl. This is important
537 // because comments can contain references to parameter names which can be
538 // different across redeclarations.
539 if (D != OriginalDecl)
540 return getCommentForDecl(OriginalDecl, PP);
541
542 comments::FullComment *FC = RC->parse(*this, PP, D);
543 ParsedComments[Canonical] = FC;
544 return FC;
545}
546
547void
548ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
549 TemplateTemplateParmDecl *Parm) {
550 ID.AddInteger(Parm->getDepth());
551 ID.AddInteger(Parm->getPosition());
552 ID.AddBoolean(Parm->isParameterPack());
553
554 TemplateParameterList *Params = Parm->getTemplateParameters();
555 ID.AddInteger(Params->size());
556 for (TemplateParameterList::const_iterator P = Params->begin(),
557 PEnd = Params->end();
558 P != PEnd; ++P) {
559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
560 ID.AddInteger(0);
561 ID.AddBoolean(TTP->isParameterPack());
562 continue;
563 }
564
565 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
566 ID.AddInteger(1);
567 ID.AddBoolean(NTTP->isParameterPack());
568 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
569 if (NTTP->isExpandedParameterPack()) {
570 ID.AddBoolean(true);
571 ID.AddInteger(NTTP->getNumExpansionTypes());
572 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
573 QualType T = NTTP->getExpansionType(I);
574 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
575 }
576 } else
577 ID.AddBoolean(false);
578 continue;
579 }
580
581 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
582 ID.AddInteger(2);
583 Profile(ID, TTP);
584 }
585}
586
587TemplateTemplateParmDecl *
588ASTContext::getCanonicalTemplateTemplateParmDecl(
589 TemplateTemplateParmDecl *TTP) const {
590 // Check if we already have a canonical template template parameter.
591 llvm::FoldingSetNodeID ID;
592 CanonicalTemplateTemplateParm::Profile(ID, TTP);
593 void *InsertPos = nullptr;
594 CanonicalTemplateTemplateParm *Canonical
595 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
596 if (Canonical)
597 return Canonical->getParam();
598
599 // Build a canonical template parameter list.
600 TemplateParameterList *Params = TTP->getTemplateParameters();
601 SmallVector<NamedDecl *, 4> CanonParams;
602 CanonParams.reserve(Params->size());
603 for (TemplateParameterList::const_iterator P = Params->begin(),
604 PEnd = Params->end();
605 P != PEnd; ++P) {
606 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
607 CanonParams.push_back(
608 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
609 SourceLocation(),
610 SourceLocation(),
611 TTP->getDepth(),
612 TTP->getIndex(), nullptr, false,
613 TTP->isParameterPack()));
614 else if (NonTypeTemplateParmDecl *NTTP
615 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
616 QualType T = getCanonicalType(NTTP->getType());
617 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
618 NonTypeTemplateParmDecl *Param;
619 if (NTTP->isExpandedParameterPack()) {
620 SmallVector<QualType, 2> ExpandedTypes;
621 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
622 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
623 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
624 ExpandedTInfos.push_back(
625 getTrivialTypeSourceInfo(ExpandedTypes.back()));
626 }
627
628 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
629 SourceLocation(),
630 SourceLocation(),
631 NTTP->getDepth(),
632 NTTP->getPosition(), nullptr,
633 T,
634 TInfo,
635 ExpandedTypes,
636 ExpandedTInfos);
637 } else {
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
639 SourceLocation(),
640 SourceLocation(),
641 NTTP->getDepth(),
642 NTTP->getPosition(), nullptr,
643 T,
644 NTTP->isParameterPack(),
645 TInfo);
646 }
647 CanonParams.push_back(Param);
648
649 } else
650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
652 }
653
654 assert(!TTP->getRequiresClause() &&((!TTP->getRequiresClause() && "Unexpected requires-clause on template template-parameter"
) ? static_cast<void> (0) : __assert_fail ("!TTP->getRequiresClause() && \"Unexpected requires-clause on template template-parameter\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 655, __PRETTY_FUNCTION__))
655 "Unexpected requires-clause on template template-parameter")((!TTP->getRequiresClause() && "Unexpected requires-clause on template template-parameter"
) ? static_cast<void> (0) : __assert_fail ("!TTP->getRequiresClause() && \"Unexpected requires-clause on template template-parameter\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 655, __PRETTY_FUNCTION__))
;
656 Expr *const CanonRequiresClause = nullptr;
657
658 TemplateTemplateParmDecl *CanonTTP
659 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
660 SourceLocation(), TTP->getDepth(),
661 TTP->getPosition(),
662 TTP->isParameterPack(),
663 nullptr,
664 TemplateParameterList::Create(*this, SourceLocation(),
665 SourceLocation(),
666 CanonParams,
667 SourceLocation(),
668 CanonRequiresClause));
669
670 // Get the new insert position for the node we care about.
671 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
672 assert(!Canonical && "Shouldn't be in the map!")((!Canonical && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!Canonical && \"Shouldn't be in the map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 672, __PRETTY_FUNCTION__))
;
673 (void)Canonical;
674
675 // Create the canonical template template parameter entry.
676 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
677 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
678 return CanonTTP;
679}
680
681CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
682 if (!LangOpts.CPlusPlus) return nullptr;
683
684 switch (T.getCXXABI().getKind()) {
685 case TargetCXXABI::GenericARM: // Same as Itanium at this level
686 case TargetCXXABI::iOS:
687 case TargetCXXABI::iOS64:
688 case TargetCXXABI::WatchOS:
689 case TargetCXXABI::GenericAArch64:
690 case TargetCXXABI::GenericMIPS:
691 case TargetCXXABI::GenericItanium:
692 case TargetCXXABI::WebAssembly:
693 return CreateItaniumCXXABI(*this);
694 case TargetCXXABI::Microsoft:
695 return CreateMicrosoftCXXABI(*this);
696 }
697 llvm_unreachable("Invalid CXXABI type!")::llvm::llvm_unreachable_internal("Invalid CXXABI type!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 697)
;
698}
699
700static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
701 const LangOptions &LOpts) {
702 if (LOpts.FakeAddressSpaceMap) {
703 // The fake address space map must have a distinct entry for each
704 // language-specific address space.
705 static const unsigned FakeAddrSpaceMap[] = {
706 0, // Default
707 1, // opencl_global
708 3, // opencl_local
709 2, // opencl_constant
710 4, // opencl_generic
711 5, // cuda_device
712 6, // cuda_constant
713 7 // cuda_shared
714 };
715 return &FakeAddrSpaceMap;
716 } else {
717 return &T.getAddressSpaceMap();
718 }
719}
720
721static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
722 const LangOptions &LangOpts) {
723 switch (LangOpts.getAddressSpaceMapMangling()) {
724 case LangOptions::ASMM_Target:
725 return TI.useAddressSpaceMapMangling();
726 case LangOptions::ASMM_On:
727 return true;
728 case LangOptions::ASMM_Off:
729 return false;
730 }
731 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.")::llvm::llvm_unreachable_internal("getAddressSpaceMapMangling() doesn't cover anything."
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 731)
;
732}
733
734ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
735 IdentifierTable &idents, SelectorTable &sels,
736 Builtin::Context &builtins)
737 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
738 DependentTemplateSpecializationTypes(this_()),
739 SubstTemplateTemplateParmPacks(this_()),
740 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
741 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
742 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
743 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
744 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
745 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
746 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
747 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
748 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
749 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
750 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
751 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
752 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
753 LangOpts.XRayNeverInstrumentFiles, SM)),
754 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
755 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
756 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
757 Listener(nullptr), Comments(SM), CommentsLoaded(false),
758 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
759 TUDecl = TranslationUnitDecl::Create(*this);
760}
761
762ASTContext::~ASTContext() {
763 ReleaseParentMapEntries();
764
765 // Release the DenseMaps associated with DeclContext objects.
766 // FIXME: Is this the ideal solution?
767 ReleaseDeclContextMaps();
768
769 // Call all of the deallocation functions on all of their targets.
770 for (auto &Pair : Deallocations)
771 (Pair.first)(Pair.second);
772
773 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
774 // because they can contain DenseMaps.
775 for (llvm::DenseMap<const ObjCContainerDecl*,
776 const ASTRecordLayout*>::iterator
777 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
778 // Increment in loop to prevent using deallocated memory.
779 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
780 R->Destroy(*this);
781
782 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
783 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
784 // Increment in loop to prevent using deallocated memory.
785 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
786 R->Destroy(*this);
787 }
788
789 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
790 AEnd = DeclAttrs.end();
791 A != AEnd; ++A)
792 A->second->~AttrVec();
793
794 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
795 MaterializedTemporaryValues)
796 MTVPair.second->~APValue();
797
798 for (const auto &Value : ModuleInitializers)
799 Value.second->~PerModuleInitializers();
800}
801
802void ASTContext::ReleaseParentMapEntries() {
803 if (!PointerParents) return;
804 for (const auto &Entry : *PointerParents) {
805 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
806 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
807 } else if (Entry.second.is<ParentVector *>()) {
808 delete Entry.second.get<ParentVector *>();
809 }
810 }
811 for (const auto &Entry : *OtherParents) {
812 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
813 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
814 } else if (Entry.second.is<ParentVector *>()) {
815 delete Entry.second.get<ParentVector *>();
816 }
817 }
818}
819
820void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
821 Deallocations.push_back({Callback, Data});
822}
823
824void
825ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
826 ExternalSource = std::move(Source);
827}
828
829void ASTContext::PrintStats() const {
830 llvm::errs() << "\n*** AST Context Stats:\n";
831 llvm::errs() << " " << Types.size() << " types total.\n";
832
833 unsigned counts[] = {
834#define TYPE(Name, Parent) 0,
835#define ABSTRACT_TYPE(Name, Parent)
836#include "clang/AST/TypeNodes.def"
837 0 // Extra
838 };
839
840 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
841 Type *T = Types[i];
842 counts[(unsigned)T->getTypeClass()]++;
843 }
844
845 unsigned Idx = 0;
846 unsigned TotalBytes = 0;
847#define TYPE(Name, Parent) \
848 if (counts[Idx]) \
849 llvm::errs() << " " << counts[Idx] << " " << #Name \
850 << " types\n"; \
851 TotalBytes += counts[Idx] * sizeof(Name##Type); \
852 ++Idx;
853#define ABSTRACT_TYPE(Name, Parent)
854#include "clang/AST/TypeNodes.def"
855
856 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
857
858 // Implicit special member functions.
859 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
860 << NumImplicitDefaultConstructors
861 << " implicit default constructors created\n";
862 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
863 << NumImplicitCopyConstructors
864 << " implicit copy constructors created\n";
865 if (getLangOpts().CPlusPlus)
866 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
867 << NumImplicitMoveConstructors
868 << " implicit move constructors created\n";
869 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
870 << NumImplicitCopyAssignmentOperators
871 << " implicit copy assignment operators created\n";
872 if (getLangOpts().CPlusPlus)
873 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
874 << NumImplicitMoveAssignmentOperators
875 << " implicit move assignment operators created\n";
876 llvm::errs() << NumImplicitDestructorsDeclared << "/"
877 << NumImplicitDestructors
878 << " implicit destructors created\n";
879
880 if (ExternalSource) {
881 llvm::errs() << "\n";
882 ExternalSource->PrintStats();
883 }
884
885 BumpAlloc.PrintStats();
886}
887
888void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
889 bool NotifyListeners) {
890 if (NotifyListeners)
891 if (auto *Listener = getASTMutationListener())
892 Listener->RedefinedHiddenDefinition(ND, M);
893
894 if (getLangOpts().ModulesLocalVisibility)
895 MergedDefModules[ND].push_back(M);
896 else
897 ND->setVisibleDespiteOwningModule();
898}
899
900void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
901 auto It = MergedDefModules.find(ND);
902 if (It == MergedDefModules.end())
903 return;
904
905 auto &Merged = It->second;
906 llvm::DenseSet<Module*> Found;
907 for (Module *&M : Merged)
908 if (!Found.insert(M).second)
909 M = nullptr;
910 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
911}
912
913void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
914 if (LazyInitializers.empty())
915 return;
916
917 auto *Source = Ctx.getExternalSource();
918 assert(Source && "lazy initializers but no external source")((Source && "lazy initializers but no external source"
) ? static_cast<void> (0) : __assert_fail ("Source && \"lazy initializers but no external source\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 918, __PRETTY_FUNCTION__))
;
919
920 auto LazyInits = std::move(LazyInitializers);
921 LazyInitializers.clear();
922
923 for (auto ID : LazyInits)
924 Initializers.push_back(Source->GetExternalDecl(ID));
925
926 assert(LazyInitializers.empty() &&((LazyInitializers.empty() && "GetExternalDecl for lazy module initializer added more inits"
) ? static_cast<void> (0) : __assert_fail ("LazyInitializers.empty() && \"GetExternalDecl for lazy module initializer added more inits\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 927, __PRETTY_FUNCTION__))
927 "GetExternalDecl for lazy module initializer added more inits")((LazyInitializers.empty() && "GetExternalDecl for lazy module initializer added more inits"
) ? static_cast<void> (0) : __assert_fail ("LazyInitializers.empty() && \"GetExternalDecl for lazy module initializer added more inits\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 927, __PRETTY_FUNCTION__))
;
928}
929
930void ASTContext::addModuleInitializer(Module *M, Decl *D) {
931 // One special case: if we add a module initializer that imports another
932 // module, and that module's only initializer is an ImportDecl, simplify.
933 if (auto *ID = dyn_cast<ImportDecl>(D)) {
934 auto It = ModuleInitializers.find(ID->getImportedModule());
935
936 // Maybe the ImportDecl does nothing at all. (Common case.)
937 if (It == ModuleInitializers.end())
938 return;
939
940 // Maybe the ImportDecl only imports another ImportDecl.
941 auto &Imported = *It->second;
942 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
943 Imported.resolve(*this);
944 auto *OnlyDecl = Imported.Initializers.front();
945 if (isa<ImportDecl>(OnlyDecl))
946 D = OnlyDecl;
947 }
948 }
949
950 auto *&Inits = ModuleInitializers[M];
951 if (!Inits)
952 Inits = new (*this) PerModuleInitializers;
953 Inits->Initializers.push_back(D);
954}
955
956void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
957 auto *&Inits = ModuleInitializers[M];
958 if (!Inits)
959 Inits = new (*this) PerModuleInitializers;
960 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
961 IDs.begin(), IDs.end());
962}
963
964ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
965 auto It = ModuleInitializers.find(M);
966 if (It == ModuleInitializers.end())
967 return None;
968
969 auto *Inits = It->second;
970 Inits->resolve(*this);
971 return Inits->Initializers;
972}
973
974ExternCContextDecl *ASTContext::getExternCContextDecl() const {
975 if (!ExternCContext)
976 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
977
978 return ExternCContext;
979}
980
981BuiltinTemplateDecl *
982ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
983 const IdentifierInfo *II) const {
984 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
985 BuiltinTemplate->setImplicit();
986 TUDecl->addDecl(BuiltinTemplate);
987
988 return BuiltinTemplate;
989}
990
991BuiltinTemplateDecl *
992ASTContext::getMakeIntegerSeqDecl() const {
993 if (!MakeIntegerSeqDecl)
994 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
995 getMakeIntegerSeqName());
996 return MakeIntegerSeqDecl;
997}
998
999BuiltinTemplateDecl *
1000ASTContext::getTypePackElementDecl() const {
1001 if (!TypePackElementDecl)
1002 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1003 getTypePackElementName());
1004 return TypePackElementDecl;
1005}
1006
1007RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1008 RecordDecl::TagKind TK) const {
1009 SourceLocation Loc;
1010 RecordDecl *NewDecl;
1011 if (getLangOpts().CPlusPlus)
1012 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1013 Loc, &Idents.get(Name));
1014 else
1015 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1016 &Idents.get(Name));
1017 NewDecl->setImplicit();
1018 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1019 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1020 return NewDecl;
1021}
1022
1023TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1024 StringRef Name) const {
1025 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1026 TypedefDecl *NewDecl = TypedefDecl::Create(
1027 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1028 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1029 NewDecl->setImplicit();
1030 return NewDecl;
1031}
1032
1033TypedefDecl *ASTContext::getInt128Decl() const {
1034 if (!Int128Decl)
1035 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1036 return Int128Decl;
1037}
1038
1039TypedefDecl *ASTContext::getUInt128Decl() const {
1040 if (!UInt128Decl)
1041 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1042 return UInt128Decl;
1043}
1044
1045void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1046 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
1047 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1048 Types.push_back(Ty);
1049}
1050
1051void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1052 const TargetInfo *AuxTarget) {
1053 assert((!this->Target || this->Target == &Target) &&(((!this->Target || this->Target == &Target) &&
"Incorrect target reinitialization") ? static_cast<void>
(0) : __assert_fail ("(!this->Target || this->Target == &Target) && \"Incorrect target reinitialization\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1054, __PRETTY_FUNCTION__))
1054 "Incorrect target reinitialization")(((!this->Target || this->Target == &Target) &&
"Incorrect target reinitialization") ? static_cast<void>
(0) : __assert_fail ("(!this->Target || this->Target == &Target) && \"Incorrect target reinitialization\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1054, __PRETTY_FUNCTION__))
;
1055 assert(VoidTy.isNull() && "Context reinitialized?")((VoidTy.isNull() && "Context reinitialized?") ? static_cast
<void> (0) : __assert_fail ("VoidTy.isNull() && \"Context reinitialized?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1055, __PRETTY_FUNCTION__))
;
1056
1057 this->Target = &Target;
1058 this->AuxTarget = AuxTarget;
1059
1060 ABI.reset(createCXXABI(Target));
1061 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1062 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1063
1064 // C99 6.2.5p19.
1065 InitBuiltinType(VoidTy, BuiltinType::Void);
1066
1067 // C99 6.2.5p2.
1068 InitBuiltinType(BoolTy, BuiltinType::Bool);
1069 // C99 6.2.5p3.
1070 if (LangOpts.CharIsSigned)
1071 InitBuiltinType(CharTy, BuiltinType::Char_S);
1072 else
1073 InitBuiltinType(CharTy, BuiltinType::Char_U);
1074 // C99 6.2.5p4.
1075 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1076 InitBuiltinType(ShortTy, BuiltinType::Short);
1077 InitBuiltinType(IntTy, BuiltinType::Int);
1078 InitBuiltinType(LongTy, BuiltinType::Long);
1079 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1080
1081 // C99 6.2.5p6.
1082 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1083 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1084 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1085 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1086 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1087
1088 // C99 6.2.5p10.
1089 InitBuiltinType(FloatTy, BuiltinType::Float);
1090 InitBuiltinType(DoubleTy, BuiltinType::Double);
1091 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1092
1093 // GNU extension, __float128 for IEEE quadruple precision
1094 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1095
1096 // GNU extension, 128-bit integers.
1097 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1098 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1099
1100 // C++ 3.9.1p5
1101 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1102 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1103 else // -fshort-wchar makes wchar_t be unsigned.
1104 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1105 if (LangOpts.CPlusPlus && LangOpts.WChar)
1106 WideCharTy = WCharTy;
1107 else {
1108 // C99 (or C++ using -fno-wchar).
1109 WideCharTy = getFromTargetType(Target.getWCharType());
1110 }
1111
1112 WIntTy = getFromTargetType(Target.getWIntType());
1113
1114 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1115 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1116 else // C99
1117 Char16Ty = getFromTargetType(Target.getChar16Type());
1118
1119 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1120 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1121 else // C99
1122 Char32Ty = getFromTargetType(Target.getChar32Type());
1123
1124 // Placeholder type for type-dependent expressions whose type is
1125 // completely unknown. No code should ever check a type against
1126 // DependentTy and users should never see it; however, it is here to
1127 // help diagnose failures to properly check for type-dependent
1128 // expressions.
1129 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1130
1131 // Placeholder type for functions.
1132 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1133
1134 // Placeholder type for bound members.
1135 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1136
1137 // Placeholder type for pseudo-objects.
1138 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1139
1140 // "any" type; useful for debugger-like clients.
1141 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1142
1143 // Placeholder type for unbridged ARC casts.
1144 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1145
1146 // Placeholder type for builtin functions.
1147 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1148
1149 // Placeholder type for OMP array sections.
1150 if (LangOpts.OpenMP)
1151 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1152
1153 // C99 6.2.5p11.
1154 FloatComplexTy = getComplexType(FloatTy);
1155 DoubleComplexTy = getComplexType(DoubleTy);
1156 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1157 Float128ComplexTy = getComplexType(Float128Ty);
1158
1159 // Builtin types for 'id', 'Class', and 'SEL'.
1160 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1161 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1162 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1163
1164 if (LangOpts.OpenCL) {
1165#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1166 InitBuiltinType(SingletonId, BuiltinType::Id);
1167#include "clang/Basic/OpenCLImageTypes.def"
1168
1169 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1170 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1171 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1172 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1173 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1174 }
1175
1176 // Builtin type for __objc_yes and __objc_no
1177 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1178 SignedCharTy : BoolTy);
1179
1180 ObjCConstantStringType = QualType();
1181
1182 ObjCSuperType = QualType();
1183
1184 // void * type
1185 VoidPtrTy = getPointerType(VoidTy);
1186
1187 // nullptr type (C++0x 2.14.7)
1188 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1189
1190 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1191 InitBuiltinType(HalfTy, BuiltinType::Half);
1192
1193 // Builtin type used to help define __builtin_va_list.
1194 VaListTagDecl = nullptr;
1195}
1196
1197DiagnosticsEngine &ASTContext::getDiagnostics() const {
1198 return SourceMgr.getDiagnostics();
1199}
1200
1201AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1202 AttrVec *&Result = DeclAttrs[D];
1203 if (!Result) {
1204 void *Mem = Allocate(sizeof(AttrVec));
1205 Result = new (Mem) AttrVec;
1206 }
1207
1208 return *Result;
1209}
1210
1211/// \brief Erase the attributes corresponding to the given declaration.
1212void ASTContext::eraseDeclAttrs(const Decl *D) {
1213 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1214 if (Pos != DeclAttrs.end()) {
1215 Pos->second->~AttrVec();
1216 DeclAttrs.erase(Pos);
1217 }
1218}
1219
1220// FIXME: Remove ?
1221MemberSpecializationInfo *
1222ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1223 assert(Var->isStaticDataMember() && "Not a static data member")((Var->isStaticDataMember() && "Not a static data member"
) ? static_cast<void> (0) : __assert_fail ("Var->isStaticDataMember() && \"Not a static data member\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1223, __PRETTY_FUNCTION__))
;
1224 return getTemplateOrSpecializationInfo(Var)
1225 .dyn_cast<MemberSpecializationInfo *>();
1226}
1227
1228ASTContext::TemplateOrSpecializationInfo
1229ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1230 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1231 TemplateOrInstantiation.find(Var);
1232 if (Pos == TemplateOrInstantiation.end())
1233 return TemplateOrSpecializationInfo();
1234
1235 return Pos->second;
1236}
1237
1238void
1239ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1240 TemplateSpecializationKind TSK,
1241 SourceLocation PointOfInstantiation) {
1242 assert(Inst->isStaticDataMember() && "Not a static data member")((Inst->isStaticDataMember() && "Not a static data member"
) ? static_cast<void> (0) : __assert_fail ("Inst->isStaticDataMember() && \"Not a static data member\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1242, __PRETTY_FUNCTION__))
;
1243 assert(Tmpl->isStaticDataMember() && "Not a static data member")((Tmpl->isStaticDataMember() && "Not a static data member"
) ? static_cast<void> (0) : __assert_fail ("Tmpl->isStaticDataMember() && \"Not a static data member\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1243, __PRETTY_FUNCTION__))
;
1244 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1245 Tmpl, TSK, PointOfInstantiation));
1246}
1247
1248void
1249ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1250 TemplateOrSpecializationInfo TSI) {
1251 assert(!TemplateOrInstantiation[Inst] &&((!TemplateOrInstantiation[Inst] && "Already noted what the variable was instantiated from"
) ? static_cast<void> (0) : __assert_fail ("!TemplateOrInstantiation[Inst] && \"Already noted what the variable was instantiated from\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1252, __PRETTY_FUNCTION__))
1252 "Already noted what the variable was instantiated from")((!TemplateOrInstantiation[Inst] && "Already noted what the variable was instantiated from"
) ? static_cast<void> (0) : __assert_fail ("!TemplateOrInstantiation[Inst] && \"Already noted what the variable was instantiated from\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1252, __PRETTY_FUNCTION__))
;
1253 TemplateOrInstantiation[Inst] = TSI;
1254}
1255
1256FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1257 const FunctionDecl *FD){
1258 assert(FD && "Specialization is 0")((FD && "Specialization is 0") ? static_cast<void>
(0) : __assert_fail ("FD && \"Specialization is 0\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1258, __PRETTY_FUNCTION__))
;
1259 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1260 = ClassScopeSpecializationPattern.find(FD);
1261 if (Pos == ClassScopeSpecializationPattern.end())
1262 return nullptr;
1263
1264 return Pos->second;
1265}
1266
1267void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1268 FunctionDecl *Pattern) {
1269 assert(FD && "Specialization is 0")((FD && "Specialization is 0") ? static_cast<void>
(0) : __assert_fail ("FD && \"Specialization is 0\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1269, __PRETTY_FUNCTION__))
;
1270 assert(Pattern && "Class scope specialization pattern is 0")((Pattern && "Class scope specialization pattern is 0"
) ? static_cast<void> (0) : __assert_fail ("Pattern && \"Class scope specialization pattern is 0\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1270, __PRETTY_FUNCTION__))
;
1271 ClassScopeSpecializationPattern[FD] = Pattern;
1272}
1273
1274NamedDecl *
1275ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1276 auto Pos = InstantiatedFromUsingDecl.find(UUD);
1277 if (Pos == InstantiatedFromUsingDecl.end())
1278 return nullptr;
1279
1280 return Pos->second;
1281}
1282
1283void
1284ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1285 assert((isa<UsingDecl>(Pattern) ||(((isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl
>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern
)) && "pattern decl is not a using decl") ? static_cast
<void> (0) : __assert_fail ("(isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern)) && \"pattern decl is not a using decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1288, __PRETTY_FUNCTION__))
1286 isa<UnresolvedUsingValueDecl>(Pattern) ||(((isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl
>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern
)) && "pattern decl is not a using decl") ? static_cast
<void> (0) : __assert_fail ("(isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern)) && \"pattern decl is not a using decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1288, __PRETTY_FUNCTION__))
1287 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&(((isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl
>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern
)) && "pattern decl is not a using decl") ? static_cast
<void> (0) : __assert_fail ("(isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern)) && \"pattern decl is not a using decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1288, __PRETTY_FUNCTION__))
1288 "pattern decl is not a using decl")(((isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl
>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern
)) && "pattern decl is not a using decl") ? static_cast
<void> (0) : __assert_fail ("(isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern)) && \"pattern decl is not a using decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1288, __PRETTY_FUNCTION__))
;
1289 assert((isa<UsingDecl>(Inst) ||(((isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl
>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) &&
"instantiation did not produce a using decl") ? static_cast<
void> (0) : __assert_fail ("(isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) && \"instantiation did not produce a using decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1292, __PRETTY_FUNCTION__))
1290 isa<UnresolvedUsingValueDecl>(Inst) ||(((isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl
>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) &&
"instantiation did not produce a using decl") ? static_cast<
void> (0) : __assert_fail ("(isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) && \"instantiation did not produce a using decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1292, __PRETTY_FUNCTION__))
1291 isa<UnresolvedUsingTypenameDecl>(Inst)) &&(((isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl
>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) &&
"instantiation did not produce a using decl") ? static_cast<
void> (0) : __assert_fail ("(isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) && \"instantiation did not produce a using decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1292, __PRETTY_FUNCTION__))
1292 "instantiation did not produce a using decl")(((isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl
>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) &&
"instantiation did not produce a using decl") ? static_cast<
void> (0) : __assert_fail ("(isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) && \"instantiation did not produce a using decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1292, __PRETTY_FUNCTION__))
;
1293 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists")((!InstantiatedFromUsingDecl[Inst] && "pattern already exists"
) ? static_cast<void> (0) : __assert_fail ("!InstantiatedFromUsingDecl[Inst] && \"pattern already exists\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1293, __PRETTY_FUNCTION__))
;
1294 InstantiatedFromUsingDecl[Inst] = Pattern;
1295}
1296
1297UsingShadowDecl *
1298ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1299 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1300 = InstantiatedFromUsingShadowDecl.find(Inst);
1301 if (Pos == InstantiatedFromUsingShadowDecl.end())
1302 return nullptr;
1303
1304 return Pos->second;
1305}
1306
1307void
1308ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1309 UsingShadowDecl *Pattern) {
1310 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists")((!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"
) ? static_cast<void> (0) : __assert_fail ("!InstantiatedFromUsingShadowDecl[Inst] && \"pattern already exists\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1310, __PRETTY_FUNCTION__))
;
1311 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1312}
1313
1314FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1315 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1316 = InstantiatedFromUnnamedFieldDecl.find(Field);
1317 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1318 return nullptr;
1319
1320 return Pos->second;
1321}
1322
1323void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1324 FieldDecl *Tmpl) {
1325 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed")((!Inst->getDeclName() && "Instantiated field decl is not unnamed"
) ? static_cast<void> (0) : __assert_fail ("!Inst->getDeclName() && \"Instantiated field decl is not unnamed\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1325, __PRETTY_FUNCTION__))
;
1326 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed")((!Tmpl->getDeclName() && "Template field decl is not unnamed"
) ? static_cast<void> (0) : __assert_fail ("!Tmpl->getDeclName() && \"Template field decl is not unnamed\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1326, __PRETTY_FUNCTION__))
;
1327 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&((!InstantiatedFromUnnamedFieldDecl[Inst] && "Already noted what unnamed field was instantiated from"
) ? static_cast<void> (0) : __assert_fail ("!InstantiatedFromUnnamedFieldDecl[Inst] && \"Already noted what unnamed field was instantiated from\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1328, __PRETTY_FUNCTION__))
1328 "Already noted what unnamed field was instantiated from")((!InstantiatedFromUnnamedFieldDecl[Inst] && "Already noted what unnamed field was instantiated from"
) ? static_cast<void> (0) : __assert_fail ("!InstantiatedFromUnnamedFieldDecl[Inst] && \"Already noted what unnamed field was instantiated from\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1328, __PRETTY_FUNCTION__))
;
1329
1330 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1331}
1332
1333ASTContext::overridden_cxx_method_iterator
1334ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1335 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1336 OverriddenMethods.find(Method->getCanonicalDecl());
1337 if (Pos == OverriddenMethods.end())
1338 return nullptr;
1339 return Pos->second.begin();
1340}
1341
1342ASTContext::overridden_cxx_method_iterator
1343ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1344 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1345 OverriddenMethods.find(Method->getCanonicalDecl());
1346 if (Pos == OverriddenMethods.end())
1347 return nullptr;
1348 return Pos->second.end();
1349}
1350
1351unsigned
1352ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1353 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1354 OverriddenMethods.find(Method->getCanonicalDecl());
1355 if (Pos == OverriddenMethods.end())
1356 return 0;
1357 return Pos->second.size();
1358}
1359
1360ASTContext::overridden_method_range
1361ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1362 return overridden_method_range(overridden_methods_begin(Method),
1363 overridden_methods_end(Method));
1364}
1365
1366void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1367 const CXXMethodDecl *Overridden) {
1368 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl())((Method->isCanonicalDecl() && Overridden->isCanonicalDecl
()) ? static_cast<void> (0) : __assert_fail ("Method->isCanonicalDecl() && Overridden->isCanonicalDecl()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1368, __PRETTY_FUNCTION__))
;
1369 OverriddenMethods[Method].push_back(Overridden);
1370}
1371
1372void ASTContext::getOverriddenMethods(
1373 const NamedDecl *D,
1374 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1375 assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1375, __PRETTY_FUNCTION__))
;
1376
1377 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1378 Overridden.append(overridden_methods_begin(CXXMethod),
1379 overridden_methods_end(CXXMethod));
1380 return;
1381 }
1382
1383 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1384 if (!Method)
1385 return;
1386
1387 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1388 Method->getOverriddenMethods(OverDecls);
1389 Overridden.append(OverDecls.begin(), OverDecls.end());
1390}
1391
1392void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1393 assert(!Import->NextLocalImport && "Import declaration already in the chain")((!Import->NextLocalImport && "Import declaration already in the chain"
) ? static_cast<void> (0) : __assert_fail ("!Import->NextLocalImport && \"Import declaration already in the chain\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1393, __PRETTY_FUNCTION__))
;
1394 assert(!Import->isFromASTFile() && "Non-local import declaration")((!Import->isFromASTFile() && "Non-local import declaration"
) ? static_cast<void> (0) : __assert_fail ("!Import->isFromASTFile() && \"Non-local import declaration\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1394, __PRETTY_FUNCTION__))
;
1395 if (!FirstLocalImport) {
1396 FirstLocalImport = Import;
1397 LastLocalImport = Import;
1398 return;
1399 }
1400
1401 LastLocalImport->NextLocalImport = Import;
1402 LastLocalImport = Import;
1403}
1404
1405//===----------------------------------------------------------------------===//
1406// Type Sizing and Analysis
1407//===----------------------------------------------------------------------===//
1408
1409/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1410/// scalar floating point type.
1411const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1412 const BuiltinType *BT = T->getAs<BuiltinType>();
1413 assert(BT && "Not a floating point type!")((BT && "Not a floating point type!") ? static_cast<
void> (0) : __assert_fail ("BT && \"Not a floating point type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1413, __PRETTY_FUNCTION__))
;
1414 switch (BT->getKind()) {
1415 default: llvm_unreachable("Not a floating point type!")::llvm::llvm_unreachable_internal("Not a floating point type!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1415)
;
1416 case BuiltinType::Half: return Target->getHalfFormat();
1417 case BuiltinType::Float: return Target->getFloatFormat();
1418 case BuiltinType::Double: return Target->getDoubleFormat();
1419 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1420 case BuiltinType::Float128: return Target->getFloat128Format();
1421 }
1422}
1423
1424CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1425 unsigned Align = Target->getCharWidth();
1426
1427 bool UseAlignAttrOnly = false;
1428 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1429 Align = AlignFromAttr;
1430
1431 // __attribute__((aligned)) can increase or decrease alignment
1432 // *except* on a struct or struct member, where it only increases
1433 // alignment unless 'packed' is also specified.
1434 //
1435 // It is an error for alignas to decrease alignment, so we can
1436 // ignore that possibility; Sema should diagnose it.
1437 if (isa<FieldDecl>(D)) {
1438 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1439 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1440 } else {
1441 UseAlignAttrOnly = true;
1442 }
1443 }
1444 else if (isa<FieldDecl>(D))
1445 UseAlignAttrOnly =
1446 D->hasAttr<PackedAttr>() ||
1447 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1448
1449 // If we're using the align attribute only, just ignore everything
1450 // else about the declaration and its type.
1451 if (UseAlignAttrOnly) {
1452 // do nothing
1453
1454 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1455 QualType T = VD->getType();
1456 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
1457 if (ForAlignof)
1458 T = RT->getPointeeType();
1459 else
1460 T = getPointerType(RT->getPointeeType());
1461 }
1462 QualType BaseT = getBaseElementType(T);
1463 if (T->isFunctionType())
1464 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1465 else if (!BaseT->isIncompleteType()) {
1466 // Adjust alignments of declarations with array type by the
1467 // large-array alignment on the target.
1468 if (const ArrayType *arrayType = getAsArrayType(T)) {
1469 unsigned MinWidth = Target->getLargeArrayMinWidth();
1470 if (!ForAlignof && MinWidth) {
1471 if (isa<VariableArrayType>(arrayType))
1472 Align = std::max(Align, Target->getLargeArrayAlign());
1473 else if (isa<ConstantArrayType>(arrayType) &&
1474 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1475 Align = std::max(Align, Target->getLargeArrayAlign());
1476 }
1477 }
1478 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1479 if (BaseT.getQualifiers().hasUnaligned())
1480 Align = Target->getCharWidth();
1481 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1482 if (VD->hasGlobalStorage() && !ForAlignof)
1483 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1484 }
1485 }
1486
1487 // Fields can be subject to extra alignment constraints, like if
1488 // the field is packed, the struct is packed, or the struct has a
1489 // a max-field-alignment constraint (#pragma pack). So calculate
1490 // the actual alignment of the field within the struct, and then
1491 // (as we're expected to) constrain that by the alignment of the type.
1492 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1493 const RecordDecl *Parent = Field->getParent();
1494 // We can only produce a sensible answer if the record is valid.
1495 if (!Parent->isInvalidDecl()) {
1496 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1497
1498 // Start with the record's overall alignment.
1499 unsigned FieldAlign = toBits(Layout.getAlignment());
1500
1501 // Use the GCD of that and the offset within the record.
1502 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1503 if (Offset > 0) {
1504 // Alignment is always a power of 2, so the GCD will be a power of 2,
1505 // which means we get to do this crazy thing instead of Euclid's.
1506 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1507 if (LowBitOfOffset < FieldAlign)
1508 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1509 }
1510
1511 Align = std::min(Align, FieldAlign);
1512 }
1513 }
1514 }
1515
1516 return toCharUnitsFromBits(Align);
1517}
1518
1519// getTypeInfoDataSizeInChars - Return the size of a type, in
1520// chars. If the type is a record, its data size is returned. This is
1521// the size of the memcpy that's performed when assigning this type
1522// using a trivial copy/move assignment operator.
1523std::pair<CharUnits, CharUnits>
1524ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1525 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1526
1527 // In C++, objects can sometimes be allocated into the tail padding
1528 // of a base-class subobject. We decide whether that's possible
1529 // during class layout, so here we can just trust the layout results.
1530 if (getLangOpts().CPlusPlus) {
1531 if (const RecordType *RT = T->getAs<RecordType>()) {
1532 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1533 sizeAndAlign.first = layout.getDataSize();
1534 }
1535 }
1536
1537 return sizeAndAlign;
1538}
1539
1540/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1541/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1542std::pair<CharUnits, CharUnits>
1543static getConstantArrayInfoInChars(const ASTContext &Context,
1544 const ConstantArrayType *CAT) {
1545 std::pair<CharUnits, CharUnits> EltInfo =
1546 Context.getTypeInfoInChars(CAT->getElementType());
1547 uint64_t Size = CAT->getSize().getZExtValue();
1548 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=(((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity
()) <= (uint64_t)(-1)/Size) && "Overflow in array type char size evaluation"
) ? static_cast<void> (0) : __assert_fail ("(Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <= (uint64_t)(-1)/Size) && \"Overflow in array type char size evaluation\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1550, __PRETTY_FUNCTION__))
1549 (uint64_t)(-1)/Size) &&(((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity
()) <= (uint64_t)(-1)/Size) && "Overflow in array type char size evaluation"
) ? static_cast<void> (0) : __assert_fail ("(Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <= (uint64_t)(-1)/Size) && \"Overflow in array type char size evaluation\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1550, __PRETTY_FUNCTION__))
1550 "Overflow in array type char size evaluation")(((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity
()) <= (uint64_t)(-1)/Size) && "Overflow in array type char size evaluation"
) ? static_cast<void> (0) : __assert_fail ("(Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <= (uint64_t)(-1)/Size) && \"Overflow in array type char size evaluation\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1550, __PRETTY_FUNCTION__))
;
1551 uint64_t Width = EltInfo.first.getQuantity() * Size;
1552 unsigned Align = EltInfo.second.getQuantity();
1553 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1554 Context.getTargetInfo().getPointerWidth(0) == 64)
1555 Width = llvm::alignTo(Width, Align);
1556 return std::make_pair(CharUnits::fromQuantity(Width),
1557 CharUnits::fromQuantity(Align));
1558}
1559
1560std::pair<CharUnits, CharUnits>
1561ASTContext::getTypeInfoInChars(const Type *T) const {
1562 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1563 return getConstantArrayInfoInChars(*this, CAT);
1564 TypeInfo Info = getTypeInfo(T);
1565 return std::make_pair(toCharUnitsFromBits(Info.Width),
1566 toCharUnitsFromBits(Info.Align));
1567}
1568
1569std::pair<CharUnits, CharUnits>
1570ASTContext::getTypeInfoInChars(QualType T) const {
1571 return getTypeInfoInChars(T.getTypePtr());
1572}
1573
1574bool ASTContext::isAlignmentRequired(const Type *T) const {
1575 return getTypeInfo(T).AlignIsRequired;
1576}
1577
1578bool ASTContext::isAlignmentRequired(QualType T) const {
1579 return isAlignmentRequired(T.getTypePtr());
1580}
1581
1582unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1583 // An alignment on a typedef overrides anything else.
1584 if (auto *TT = T->getAs<TypedefType>())
1585 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1586 return Align;
1587
1588 // If we have an (array of) complete type, we're done.
1589 T = getBaseElementType(T);
1590 if (!T->isIncompleteType())
1591 return getTypeAlign(T);
1592
1593 // If we had an array type, its element type might be a typedef
1594 // type with an alignment attribute.
1595 if (auto *TT = T->getAs<TypedefType>())
1596 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1597 return Align;
1598
1599 // Otherwise, see if the declaration of the type had an attribute.
1600 if (auto *TT = T->getAs<TagType>())
1601 return TT->getDecl()->getMaxAlignment();
1602
1603 return 0;
1604}
1605
1606TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1607 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1608 if (I != MemoizedTypeInfo.end())
1609 return I->second;
1610
1611 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1612 TypeInfo TI = getTypeInfoImpl(T);
1613 MemoizedTypeInfo[T] = TI;
1614 return TI;
1615}
1616
1617/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1618/// method does not work on incomplete types.
1619///
1620/// FIXME: Pointers into different addr spaces could have different sizes and
1621/// alignment requirements: getPointerInfo should take an AddrSpace, this
1622/// should take a QualType, &c.
1623TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1624 uint64_t Width = 0;
1625 unsigned Align = 8;
1626 bool AlignIsRequired = false;
1627 switch (T->getTypeClass()) {
1628#define TYPE(Class, Base)
1629#define ABSTRACT_TYPE(Class, Base)
1630#define NON_CANONICAL_TYPE(Class, Base)
1631#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1632#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1633 case Type::Class: \
1634 assert(!T->isDependentType() && "should not see dependent types here")((!T->isDependentType() && "should not see dependent types here"
) ? static_cast<void> (0) : __assert_fail ("!T->isDependentType() && \"should not see dependent types here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1634, __PRETTY_FUNCTION__))
; \
1635 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1636#include "clang/AST/TypeNodes.def"
1637 llvm_unreachable("Should not see dependent types")::llvm::llvm_unreachable_internal("Should not see dependent types"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1637)
;
1638
1639 case Type::FunctionNoProto:
1640 case Type::FunctionProto:
1641 // GCC extension: alignof(function) = 32 bits
1642 Width = 0;
1643 Align = 32;
1644 break;
1645
1646 case Type::IncompleteArray:
1647 case Type::VariableArray:
1648 Width = 0;
1649 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1650 break;
1651
1652 case Type::ConstantArray: {
1653 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1654
1655 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1656 uint64_t Size = CAT->getSize().getZExtValue();
1657 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&(((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
"Overflow in array type bit size evaluation") ? static_cast<
void> (0) : __assert_fail ("(Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && \"Overflow in array type bit size evaluation\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1658, __PRETTY_FUNCTION__))
1658 "Overflow in array type bit size evaluation")(((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
"Overflow in array type bit size evaluation") ? static_cast<
void> (0) : __assert_fail ("(Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && \"Overflow in array type bit size evaluation\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1658, __PRETTY_FUNCTION__))
;
1659 Width = EltInfo.Width * Size;
1660 Align = EltInfo.Align;
1661 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1662 getTargetInfo().getPointerWidth(0) == 64)
1663 Width = llvm::alignTo(Width, Align);
1664 break;
1665 }
1666 case Type::ExtVector:
1667 case Type::Vector: {
1668 const VectorType *VT = cast<VectorType>(T);
1669 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1670 Width = EltInfo.Width * VT->getNumElements();
1671 Align = Width;
1672 // If the alignment is not a power of 2, round up to the next power of 2.
1673 // This happens for non-power-of-2 length vectors.
1674 if (Align & (Align-1)) {
1675 Align = llvm::NextPowerOf2(Align);
1676 Width = llvm::alignTo(Width, Align);
1677 }
1678 // Adjust the alignment based on the target max.
1679 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1680 if (TargetVectorAlign && TargetVectorAlign < Align)
1681 Align = TargetVectorAlign;
1682 break;
1683 }
1684
1685 case Type::Builtin:
1686 switch (cast<BuiltinType>(T)->getKind()) {
1687 default: llvm_unreachable("Unknown builtin type!")::llvm::llvm_unreachable_internal("Unknown builtin type!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1687)
;
1688 case BuiltinType::Void:
1689 // GCC extension: alignof(void) = 8 bits.
1690 Width = 0;
1691 Align = 8;
1692 break;
1693
1694 case BuiltinType::Bool:
1695 Width = Target->getBoolWidth();
1696 Align = Target->getBoolAlign();
1697 break;
1698 case BuiltinType::Char_S:
1699 case BuiltinType::Char_U:
1700 case BuiltinType::UChar:
1701 case BuiltinType::SChar:
1702 Width = Target->getCharWidth();
1703 Align = Target->getCharAlign();
1704 break;
1705 case BuiltinType::WChar_S:
1706 case BuiltinType::WChar_U:
1707 Width = Target->getWCharWidth();
1708 Align = Target->getWCharAlign();
1709 break;
1710 case BuiltinType::Char16:
1711 Width = Target->getChar16Width();
1712 Align = Target->getChar16Align();
1713 break;
1714 case BuiltinType::Char32:
1715 Width = Target->getChar32Width();
1716 Align = Target->getChar32Align();
1717 break;
1718 case BuiltinType::UShort:
1719 case BuiltinType::Short:
1720 Width = Target->getShortWidth();
1721 Align = Target->getShortAlign();
1722 break;
1723 case BuiltinType::UInt:
1724 case BuiltinType::Int:
1725 Width = Target->getIntWidth();
1726 Align = Target->getIntAlign();
1727 break;
1728 case BuiltinType::ULong:
1729 case BuiltinType::Long:
1730 Width = Target->getLongWidth();
1731 Align = Target->getLongAlign();
1732 break;
1733 case BuiltinType::ULongLong:
1734 case BuiltinType::LongLong:
1735 Width = Target->getLongLongWidth();
1736 Align = Target->getLongLongAlign();
1737 break;
1738 case BuiltinType::Int128:
1739 case BuiltinType::UInt128:
1740 Width = 128;
1741 Align = 128; // int128_t is 128-bit aligned on all targets.
1742 break;
1743 case BuiltinType::Half:
1744 Width = Target->getHalfWidth();
1745 Align = Target->getHalfAlign();
1746 break;
1747 case BuiltinType::Float:
1748 Width = Target->getFloatWidth();
1749 Align = Target->getFloatAlign();
1750 break;
1751 case BuiltinType::Double:
1752 Width = Target->getDoubleWidth();
1753 Align = Target->getDoubleAlign();
1754 break;
1755 case BuiltinType::LongDouble:
1756 Width = Target->getLongDoubleWidth();
1757 Align = Target->getLongDoubleAlign();
1758 break;
1759 case BuiltinType::Float128:
1760 Width = Target->getFloat128Width();
1761 Align = Target->getFloat128Align();
1762 break;
1763 case BuiltinType::NullPtr:
1764 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1765 Align = Target->getPointerAlign(0); // == sizeof(void*)
1766 break;
1767 case BuiltinType::ObjCId:
1768 case BuiltinType::ObjCClass:
1769 case BuiltinType::ObjCSel:
1770 Width = Target->getPointerWidth(0);
1771 Align = Target->getPointerAlign(0);
1772 break;
1773 case BuiltinType::OCLSampler: {
1774 auto AS = getTargetAddressSpace(LangAS::opencl_constant);
1775 Width = Target->getPointerWidth(AS);
1776 Align = Target->getPointerAlign(AS);
1777 break;
1778 }
1779 case BuiltinType::OCLEvent:
1780 case BuiltinType::OCLClkEvent:
1781 case BuiltinType::OCLQueue:
1782 case BuiltinType::OCLReserveID:
1783 // Currently these types are pointers to opaque types.
1784 Width = Target->getPointerWidth(0);
1785 Align = Target->getPointerAlign(0);
1786 break;
1787#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1788 case BuiltinType::Id:
1789#include "clang/Basic/OpenCLImageTypes.def"
1790 {
1791 auto AS = getTargetAddressSpace(Target->getOpenCLImageAddrSpace());
1792 Width = Target->getPointerWidth(AS);
1793 Align = Target->getPointerAlign(AS);
1794 }
1795 }
1796 break;
1797 case Type::ObjCObjectPointer:
1798 Width = Target->getPointerWidth(0);
1799 Align = Target->getPointerAlign(0);
1800 break;
1801 case Type::BlockPointer: {
1802 unsigned AS = getTargetAddressSpace(
1803 cast<BlockPointerType>(T)->getPointeeType());
1804 Width = Target->getPointerWidth(AS);
1805 Align = Target->getPointerAlign(AS);
1806 break;
1807 }
1808 case Type::LValueReference:
1809 case Type::RValueReference: {
1810 // alignof and sizeof should never enter this code path here, so we go
1811 // the pointer route.
1812 unsigned AS = getTargetAddressSpace(
1813 cast<ReferenceType>(T)->getPointeeType());
1814 Width = Target->getPointerWidth(AS);
1815 Align = Target->getPointerAlign(AS);
1816 break;
1817 }
1818 case Type::Pointer: {
1819 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1820 Width = Target->getPointerWidth(AS);
1821 Align = Target->getPointerAlign(AS);
1822 break;
1823 }
1824 case Type::MemberPointer: {
1825 const MemberPointerType *MPT = cast<MemberPointerType>(T);
1826 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1827 break;
1828 }
1829 case Type::Complex: {
1830 // Complex types have the same alignment as their elements, but twice the
1831 // size.
1832 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1833 Width = EltInfo.Width * 2;
1834 Align = EltInfo.Align;
1835 break;
1836 }
1837 case Type::ObjCObject:
1838 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1839 case Type::Adjusted:
1840 case Type::Decayed:
1841 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
1842 case Type::ObjCInterface: {
1843 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1844 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1845 Width = toBits(Layout.getSize());
1846 Align = toBits(Layout.getAlignment());
1847 break;
1848 }
1849 case Type::Record:
1850 case Type::Enum: {
1851 const TagType *TT = cast<TagType>(T);
1852
1853 if (TT->getDecl()->isInvalidDecl()) {
1854 Width = 8;
1855 Align = 8;
1856 break;
1857 }
1858
1859 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1860 const EnumDecl *ED = ET->getDecl();
1861 TypeInfo Info =
1862 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1863 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1864 Info.Align = AttrAlign;
1865 Info.AlignIsRequired = true;
1866 }
1867 return Info;
1868 }
1869
1870 const RecordType *RT = cast<RecordType>(TT);
1871 const RecordDecl *RD = RT->getDecl();
1872 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
1873 Width = toBits(Layout.getSize());
1874 Align = toBits(Layout.getAlignment());
1875 AlignIsRequired = RD->hasAttr<AlignedAttr>();
1876 break;
1877 }
1878
1879 case Type::SubstTemplateTypeParm:
1880 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1881 getReplacementType().getTypePtr());
1882
1883 case Type::Auto:
1884 case Type::DeducedTemplateSpecialization: {
1885 const DeducedType *A = cast<DeducedType>(T);
1886 assert(!A->getDeducedType().isNull() &&((!A->getDeducedType().isNull() && "cannot request the size of an undeduced or dependent auto type"
) ? static_cast<void> (0) : __assert_fail ("!A->getDeducedType().isNull() && \"cannot request the size of an undeduced or dependent auto type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1887, __PRETTY_FUNCTION__))
1887 "cannot request the size of an undeduced or dependent auto type")((!A->getDeducedType().isNull() && "cannot request the size of an undeduced or dependent auto type"
) ? static_cast<void> (0) : __assert_fail ("!A->getDeducedType().isNull() && \"cannot request the size of an undeduced or dependent auto type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1887, __PRETTY_FUNCTION__))
;
1888 return getTypeInfo(A->getDeducedType().getTypePtr());
1889 }
1890
1891 case Type::Paren:
1892 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1893
1894 case Type::ObjCTypeParam:
1895 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1896
1897 case Type::Typedef: {
1898 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1899 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1900 // If the typedef has an aligned attribute on it, it overrides any computed
1901 // alignment we have. This violates the GCC documentation (which says that
1902 // attribute(aligned) can only round up) but matches its implementation.
1903 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
1904 Align = AttrAlign;
1905 AlignIsRequired = true;
1906 } else {
1907 Align = Info.Align;
1908 AlignIsRequired = Info.AlignIsRequired;
1909 }
1910 Width = Info.Width;
1911 break;
1912 }
1913
1914 case Type::Elaborated:
1915 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1916
1917 case Type::Attributed:
1918 return getTypeInfo(
1919 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1920
1921 case Type::Atomic: {
1922 // Start with the base type information.
1923 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1924 Width = Info.Width;
1925 Align = Info.Align;
1926
1927 // If the size of the type doesn't exceed the platform's max
1928 // atomic promotion width, make the size and alignment more
1929 // favorable to atomic operations:
1930 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1931 // Round the size up to a power of 2.
1932 if (!llvm::isPowerOf2_64(Width))
1933 Width = llvm::NextPowerOf2(Width);
1934
1935 // Set the alignment equal to the size.
1936 Align = static_cast<unsigned>(Width);
1937 }
1938 }
1939 break;
1940
1941 case Type::Pipe: {
1942 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
1943 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
1944 }
1945
1946 }
1947
1948 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2")((llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"
) ? static_cast<void> (0) : __assert_fail ("llvm::isPowerOf2_32(Align) && \"Alignment must be power of 2\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 1948, __PRETTY_FUNCTION__))
;
1949 return TypeInfo(Width, Align, AlignIsRequired);
1950}
1951
1952unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1953 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1954 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1955 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1956 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1957 getTargetInfo().getABI() == "elfv1-qpx" &&
1958 T->isSpecificBuiltinType(BuiltinType::Double))
1959 SimdAlign = 256;
1960 return SimdAlign;
1961}
1962
1963/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1964CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1965 return CharUnits::fromQuantity(BitSize / getCharWidth());
1966}
1967
1968/// toBits - Convert a size in characters to a size in characters.
1969int64_t ASTContext::toBits(CharUnits CharSize) const {
1970 return CharSize.getQuantity() * getCharWidth();
1971}
1972
1973/// getTypeSizeInChars - Return the size of the specified type, in characters.
1974/// This method does not work on incomplete types.
1975CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1976 return getTypeInfoInChars(T).first;
1977}
1978CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1979 return getTypeInfoInChars(T).first;
1980}
1981
1982/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1983/// characters. This method does not work on incomplete types.
1984CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1985 return toCharUnitsFromBits(getTypeAlign(T));
1986}
1987CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1988 return toCharUnitsFromBits(getTypeAlign(T));
1989}
1990
1991/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1992/// type for the current target in bits. This can be different than the ABI
1993/// alignment in cases where it is beneficial for performance to overalign
1994/// a data type.
1995unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1996 TypeInfo TI = getTypeInfo(T);
1997 unsigned ABIAlign = TI.Align;
1998
1999 T = T->getBaseElementTypeUnsafe();
2000
2001 // The preferred alignment of member pointers is that of a pointer.
2002 if (T->isMemberPointerType())
2003 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2004
2005 if (!Target->allowsLargerPreferedTypeAlignment())
2006 return ABIAlign;
2007
2008 // Double and long long should be naturally aligned if possible.
2009 if (const ComplexType *CT = T->getAs<ComplexType>())
2010 T = CT->getElementType().getTypePtr();
2011 if (const EnumType *ET = T->getAs<EnumType>())
2012 T = ET->getDecl()->getIntegerType().getTypePtr();
2013 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2014 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2015 T->isSpecificBuiltinType(BuiltinType::ULongLong))
2016 // Don't increase the alignment if an alignment attribute was specified on a
2017 // typedef declaration.
2018 if (!TI.AlignIsRequired)
2019 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2020
2021 return ABIAlign;
2022}
2023
2024/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2025/// for __attribute__((aligned)) on this target, to be used if no alignment
2026/// value is specified.
2027unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2028 return getTargetInfo().getDefaultAlignForAttributeAligned();
2029}
2030
2031/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2032/// to a global variable of the specified type.
2033unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2034 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2035}
2036
2037/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2038/// should be given to a global variable of the specified type.
2039CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2040 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2041}
2042
2043CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2044 CharUnits Offset = CharUnits::Zero();
2045 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2046 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2047 Offset += Layout->getBaseClassOffset(Base);
2048 Layout = &getASTRecordLayout(Base);
2049 }
2050 return Offset;
2051}
2052
2053/// DeepCollectObjCIvars -
2054/// This routine first collects all declared, but not synthesized, ivars in
2055/// super class and then collects all ivars, including those synthesized for
2056/// current class. This routine is used for implementation of current class
2057/// when all ivars, declared and synthesized are known.
2058///
2059void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2060 bool leafClass,
2061 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2062 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2063 DeepCollectObjCIvars(SuperClass, false, Ivars);
2064 if (!leafClass) {
2065 for (const auto *I : OI->ivars())
2066 Ivars.push_back(I);
2067 } else {
2068 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2069 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2070 Iv= Iv->getNextIvar())
2071 Ivars.push_back(Iv);
2072 }
2073}
2074
2075/// CollectInheritedProtocols - Collect all protocols in current class and
2076/// those inherited by it.
2077void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2078 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2079 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2080 // We can use protocol_iterator here instead of
2081 // all_referenced_protocol_iterator since we are walking all categories.
2082 for (auto *Proto : OI->all_referenced_protocols()) {
2083 CollectInheritedProtocols(Proto, Protocols);
2084 }
2085
2086 // Categories of this Interface.
2087 for (const auto *Cat : OI->visible_categories())
2088 CollectInheritedProtocols(Cat, Protocols);
2089
2090 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2091 while (SD) {
2092 CollectInheritedProtocols(SD, Protocols);
2093 SD = SD->getSuperClass();
2094 }
2095 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2096 for (auto *Proto : OC->protocols()) {
2097 CollectInheritedProtocols(Proto, Protocols);
2098 }
2099 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2100 // Insert the protocol.
2101 if (!Protocols.insert(
2102 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2103 return;
2104
2105 for (auto *Proto : OP->protocols())
2106 CollectInheritedProtocols(Proto, Protocols);
2107 }
2108}
2109
2110unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2111 unsigned count = 0;
2112 // Count ivars declared in class extension.
2113 for (const auto *Ext : OI->known_extensions())
2114 count += Ext->ivar_size();
2115
2116 // Count ivar defined in this class's implementation. This
2117 // includes synthesized ivars.
2118 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2119 count += ImplDecl->ivar_size();
2120
2121 return count;
2122}
2123
2124bool ASTContext::isSentinelNullExpr(const Expr *E) {
2125 if (!E)
2126 return false;
2127
2128 // nullptr_t is always treated as null.
2129 if (E->getType()->isNullPtrType()) return true;
2130
2131 if (E->getType()->isAnyPointerType() &&
2132 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2133 Expr::NPC_ValueDependentIsNull))
2134 return true;
2135
2136 // Unfortunately, __null has type 'int'.
2137 if (isa<GNUNullExpr>(E)) return true;
2138
2139 return false;
2140}
2141
2142/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2143ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2144 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2145 I = ObjCImpls.find(D);
2146 if (I != ObjCImpls.end())
2147 return cast<ObjCImplementationDecl>(I->second);
2148 return nullptr;
2149}
2150/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2151ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2152 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2153 I = ObjCImpls.find(D);
2154 if (I != ObjCImpls.end())
2155 return cast<ObjCCategoryImplDecl>(I->second);
2156 return nullptr;
2157}
2158
2159/// \brief Set the implementation of ObjCInterfaceDecl.
2160void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2161 ObjCImplementationDecl *ImplD) {
2162 assert(IFaceD && ImplD && "Passed null params")((IFaceD && ImplD && "Passed null params") ? static_cast
<void> (0) : __assert_fail ("IFaceD && ImplD && \"Passed null params\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2162, __PRETTY_FUNCTION__))
;
2163 ObjCImpls[IFaceD] = ImplD;
2164}
2165/// \brief Set the implementation of ObjCCategoryDecl.
2166void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2167 ObjCCategoryImplDecl *ImplD) {
2168 assert(CatD && ImplD && "Passed null params")((CatD && ImplD && "Passed null params") ? static_cast
<void> (0) : __assert_fail ("CatD && ImplD && \"Passed null params\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2168, __PRETTY_FUNCTION__))
;
2169 ObjCImpls[CatD] = ImplD;
2170}
2171
2172const ObjCMethodDecl *
2173ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2174 return ObjCMethodRedecls.lookup(MD);
2175}
2176
2177void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2178 const ObjCMethodDecl *Redecl) {
2179 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration")((!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"
) ? static_cast<void> (0) : __assert_fail ("!getObjCMethodRedeclaration(MD) && \"MD already has a redeclaration\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2179, __PRETTY_FUNCTION__))
;
2180 ObjCMethodRedecls[MD] = Redecl;
2181}
2182
2183const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2184 const NamedDecl *ND) const {
2185 if (const ObjCInterfaceDecl *ID =
2186 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2187 return ID;
2188 if (const ObjCCategoryDecl *CD =
2189 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2190 return CD->getClassInterface();
2191 if (const ObjCImplDecl *IMD =
2192 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2193 return IMD->getClassInterface();
2194
2195 return nullptr;
2196}
2197
2198/// \brief Get the copy initialization expression of VarDecl,or NULL if
2199/// none exists.
2200Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
2201 assert(VD && "Passed null params")((VD && "Passed null params") ? static_cast<void>
(0) : __assert_fail ("VD && \"Passed null params\"",
"/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2201, __PRETTY_FUNCTION__))
;
2202 assert(VD->hasAttr<BlocksAttr>() &&((VD->hasAttr<BlocksAttr>() && "getBlockVarCopyInits - not __block var"
) ? static_cast<void> (0) : __assert_fail ("VD->hasAttr<BlocksAttr>() && \"getBlockVarCopyInits - not __block var\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2203, __PRETTY_FUNCTION__))
2203 "getBlockVarCopyInits - not __block var")((VD->hasAttr<BlocksAttr>() && "getBlockVarCopyInits - not __block var"
) ? static_cast<void> (0) : __assert_fail ("VD->hasAttr<BlocksAttr>() && \"getBlockVarCopyInits - not __block var\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2203, __PRETTY_FUNCTION__))
;
2204 llvm::DenseMap<const VarDecl*, Expr*>::iterator
2205 I = BlockVarCopyInits.find(VD);
2206 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
2207}
2208
2209/// \brief Set the copy inialization expression of a block var decl.
2210void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2211 assert(VD && Init && "Passed null params")((VD && Init && "Passed null params") ? static_cast
<void> (0) : __assert_fail ("VD && Init && \"Passed null params\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2211, __PRETTY_FUNCTION__))
;
2212 assert(VD->hasAttr<BlocksAttr>() &&((VD->hasAttr<BlocksAttr>() && "setBlockVarCopyInits - not __block var"
) ? static_cast<void> (0) : __assert_fail ("VD->hasAttr<BlocksAttr>() && \"setBlockVarCopyInits - not __block var\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2213, __PRETTY_FUNCTION__))
2213 "setBlockVarCopyInits - not __block var")((VD->hasAttr<BlocksAttr>() && "setBlockVarCopyInits - not __block var"
) ? static_cast<void> (0) : __assert_fail ("VD->hasAttr<BlocksAttr>() && \"setBlockVarCopyInits - not __block var\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2213, __PRETTY_FUNCTION__))
;
2214 BlockVarCopyInits[VD] = Init;
2215}
2216
2217TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2218 unsigned DataSize) const {
2219 if (!DataSize)
2220 DataSize = TypeLoc::getFullDataSizeForType(T);
2221 else
2222 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&((DataSize == TypeLoc::getFullDataSizeForType(T) && "incorrect data size provided to CreateTypeSourceInfo!"
) ? static_cast<void> (0) : __assert_fail ("DataSize == TypeLoc::getFullDataSizeForType(T) && \"incorrect data size provided to CreateTypeSourceInfo!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2223, __PRETTY_FUNCTION__))
2223 "incorrect data size provided to CreateTypeSourceInfo!")((DataSize == TypeLoc::getFullDataSizeForType(T) && "incorrect data size provided to CreateTypeSourceInfo!"
) ? static_cast<void> (0) : __assert_fail ("DataSize == TypeLoc::getFullDataSizeForType(T) && \"incorrect data size provided to CreateTypeSourceInfo!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2223, __PRETTY_FUNCTION__))
;
2224
2225 TypeSourceInfo *TInfo =
2226 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2227 new (TInfo) TypeSourceInfo(T);
2228 return TInfo;
2229}
2230
2231TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2232 SourceLocation L) const {
2233 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2234 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2235 return DI;
2236}
2237
2238const ASTRecordLayout &
2239ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2240 return getObjCLayout(D, nullptr);
2241}
2242
2243const ASTRecordLayout &
2244ASTContext::getASTObjCImplementationLayout(
2245 const ObjCImplementationDecl *D) const {
2246 return getObjCLayout(D->getClassInterface(), D);
2247}
2248
2249//===----------------------------------------------------------------------===//
2250// Type creation/memoization methods
2251//===----------------------------------------------------------------------===//
2252
2253QualType
2254ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2255 unsigned fastQuals = quals.getFastQualifiers();
2256 quals.removeFastQualifiers();
2257
2258 // Check if we've already instantiated this type.
2259 llvm::FoldingSetNodeID ID;
2260 ExtQuals::Profile(ID, baseType, quals);
2261 void *insertPos = nullptr;
2262 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2263 assert(eq->getQualifiers() == quals)((eq->getQualifiers() == quals) ? static_cast<void> (
0) : __assert_fail ("eq->getQualifiers() == quals", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2263, __PRETTY_FUNCTION__))
;
2264 return QualType(eq, fastQuals);
2265 }
2266
2267 // If the base type is not canonical, make the appropriate canonical type.
2268 QualType canon;
2269 if (!baseType->isCanonicalUnqualified()) {
2270 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2271 canonSplit.Quals.addConsistentQualifiers(quals);
2272 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2273
2274 // Re-find the insert position.
2275 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2276 }
2277
2278 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2279 ExtQualNodes.InsertNode(eq, insertPos);
2280 return QualType(eq, fastQuals);
2281}
2282
2283QualType
2284ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2285 QualType CanT = getCanonicalType(T);
2286 if (CanT.getAddressSpace() == AddressSpace)
2287 return T;
2288
2289 // If we are composing extended qualifiers together, merge together
2290 // into one ExtQuals node.
2291 QualifierCollector Quals;
2292 const Type *TypeNode = Quals.strip(T);
2293
2294 // If this type already has an address space specified, it cannot get
2295 // another one.
2296 assert(!Quals.hasAddressSpace() &&((!Quals.hasAddressSpace() && "Type cannot be in multiple addr spaces!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasAddressSpace() && \"Type cannot be in multiple addr spaces!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2297, __PRETTY_FUNCTION__))
2297 "Type cannot be in multiple addr spaces!")((!Quals.hasAddressSpace() && "Type cannot be in multiple addr spaces!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasAddressSpace() && \"Type cannot be in multiple addr spaces!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2297, __PRETTY_FUNCTION__))
;
2298 Quals.addAddressSpace(AddressSpace);
2299
2300 return getExtQualType(TypeNode, Quals);
2301}
2302
2303QualType ASTContext::getObjCGCQualType(QualType T,
2304 Qualifiers::GC GCAttr) const {
2305 QualType CanT = getCanonicalType(T);
2306 if (CanT.getObjCGCAttr() == GCAttr)
2307 return T;
2308
2309 if (const PointerType *ptr = T->getAs<PointerType>()) {
2310 QualType Pointee = ptr->getPointeeType();
2311 if (Pointee->isAnyPointerType()) {
2312 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2313 return getPointerType(ResultType);
2314 }
2315 }
2316
2317 // If we are composing extended qualifiers together, merge together
2318 // into one ExtQuals node.
2319 QualifierCollector Quals;
2320 const Type *TypeNode = Quals.strip(T);
2321
2322 // If this type already has an ObjCGC specified, it cannot get
2323 // another one.
2324 assert(!Quals.hasObjCGCAttr() &&((!Quals.hasObjCGCAttr() && "Type cannot have multiple ObjCGCs!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasObjCGCAttr() && \"Type cannot have multiple ObjCGCs!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2325, __PRETTY_FUNCTION__))
2325 "Type cannot have multiple ObjCGCs!")((!Quals.hasObjCGCAttr() && "Type cannot have multiple ObjCGCs!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasObjCGCAttr() && \"Type cannot have multiple ObjCGCs!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2325, __PRETTY_FUNCTION__))
;
2326 Quals.addObjCGCAttr(GCAttr);
2327
2328 return getExtQualType(TypeNode, Quals);
2329}
2330
2331const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2332 FunctionType::ExtInfo Info) {
2333 if (T->getExtInfo() == Info)
2334 return T;
2335
2336 QualType Result;
2337 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2338 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2339 } else {
2340 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2341 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2342 EPI.ExtInfo = Info;
2343 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2344 }
2345
2346 return cast<FunctionType>(Result.getTypePtr());
2347}
2348
2349void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2350 QualType ResultType) {
2351 FD = FD->getMostRecentDecl();
2352 while (true) {
2353 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2354 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2355 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2356 if (FunctionDecl *Next = FD->getPreviousDecl())
2357 FD = Next;
2358 else
2359 break;
2360 }
2361 if (ASTMutationListener *L = getASTMutationListener())
2362 L->DeducedReturnType(FD, ResultType);
2363}
2364
2365/// Get a function type and produce the equivalent function type with the
2366/// specified exception specification. Type sugar that can be present on a
2367/// declaration of a function with an exception specification is permitted
2368/// and preserved. Other type sugar (for instance, typedefs) is not.
2369static QualType getFunctionTypeWithExceptionSpec(
2370 ASTContext &Context, QualType Orig,
2371 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2372 // Might have some parens.
2373 if (auto *PT = dyn_cast<ParenType>(Orig))
2374 return Context.getParenType(
2375 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2376
2377 // Might have a calling-convention attribute.
2378 if (auto *AT = dyn_cast<AttributedType>(Orig))
2379 return Context.getAttributedType(
2380 AT->getAttrKind(),
2381 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2382 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2383 ESI));
2384
2385 // Anything else must be a function type. Rebuild it with the new exception
2386 // specification.
2387 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2388 return Context.getFunctionType(
2389 Proto->getReturnType(), Proto->getParamTypes(),
2390 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2391}
2392
2393bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2394 QualType U) {
2395 return hasSameType(T, U) ||
2396 (getLangOpts().CPlusPlus1z &&
2397 hasSameType(getFunctionTypeWithExceptionSpec(*this, T, EST_None),
2398 getFunctionTypeWithExceptionSpec(*this, U, EST_None)));
2399}
2400
2401void ASTContext::adjustExceptionSpec(
2402 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2403 bool AsWritten) {
2404 // Update the type.
2405 QualType Updated =
2406 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2407 FD->setType(Updated);
2408
2409 if (!AsWritten)
2410 return;
2411
2412 // Update the type in the type source information too.
2413 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2414 // If the type and the type-as-written differ, we may need to update
2415 // the type-as-written too.
2416 if (TSInfo->getType() != FD->getType())
2417 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2418
2419 // FIXME: When we get proper type location information for exceptions,
2420 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2421 // up the TypeSourceInfo;
2422 assert(TypeLoc::getFullDataSizeForType(Updated) ==((TypeLoc::getFullDataSizeForType(Updated) == TypeLoc::getFullDataSizeForType
(TSInfo->getType()) && "TypeLoc size mismatch from updating exception specification"
) ? static_cast<void> (0) : __assert_fail ("TypeLoc::getFullDataSizeForType(Updated) == TypeLoc::getFullDataSizeForType(TSInfo->getType()) && \"TypeLoc size mismatch from updating exception specification\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2424, __PRETTY_FUNCTION__))
2423 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&((TypeLoc::getFullDataSizeForType(Updated) == TypeLoc::getFullDataSizeForType
(TSInfo->getType()) && "TypeLoc size mismatch from updating exception specification"
) ? static_cast<void> (0) : __assert_fail ("TypeLoc::getFullDataSizeForType(Updated) == TypeLoc::getFullDataSizeForType(TSInfo->getType()) && \"TypeLoc size mismatch from updating exception specification\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2424, __PRETTY_FUNCTION__))
2424 "TypeLoc size mismatch from updating exception specification")((TypeLoc::getFullDataSizeForType(Updated) == TypeLoc::getFullDataSizeForType
(TSInfo->getType()) && "TypeLoc size mismatch from updating exception specification"
) ? static_cast<void> (0) : __assert_fail ("TypeLoc::getFullDataSizeForType(Updated) == TypeLoc::getFullDataSizeForType(TSInfo->getType()) && \"TypeLoc size mismatch from updating exception specification\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2424, __PRETTY_FUNCTION__))
;
2425 TSInfo->overrideType(Updated);
2426 }
2427}
2428
2429/// getComplexType - Return the uniqued reference to the type for a complex
2430/// number with the specified element type.
2431QualType ASTContext::getComplexType(QualType T) const {
2432 // Unique pointers, to guarantee there is only one pointer of a particular
2433 // structure.
2434 llvm::FoldingSetNodeID ID;
2435 ComplexType::Profile(ID, T);
2436
2437 void *InsertPos = nullptr;
2438 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2439 return QualType(CT, 0);
2440
2441 // If the pointee type isn't canonical, this won't be a canonical type either,
2442 // so fill in the canonical type field.
2443 QualType Canonical;
2444 if (!T.isCanonical()) {
2445 Canonical = getComplexType(getCanonicalType(T));
2446
2447 // Get the new insert position for the node we care about.
2448 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2449 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2449, __PRETTY_FUNCTION__))
; (void)NewIP;
2450 }
2451 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2452 Types.push_back(New);
2453 ComplexTypes.InsertNode(New, InsertPos);
2454 return QualType(New, 0);
2455}
2456
2457/// getPointerType - Return the uniqued reference to the type for a pointer to
2458/// the specified type.
2459QualType ASTContext::getPointerType(QualType T) const {
2460 // Unique pointers, to guarantee there is only one pointer of a particular
2461 // structure.
2462 llvm::FoldingSetNodeID ID;
2463 PointerType::Profile(ID, T);
2464
2465 void *InsertPos = nullptr;
2466 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2467 return QualType(PT, 0);
2468
2469 // If the pointee type isn't canonical, this won't be a canonical type either,
2470 // so fill in the canonical type field.
2471 QualType Canonical;
2472 if (!T.isCanonical()) {
2473 Canonical = getPointerType(getCanonicalType(T));
2474
2475 // Get the new insert position for the node we care about.
2476 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2477 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2477, __PRETTY_FUNCTION__))
; (void)NewIP;
2478 }
2479 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2480 Types.push_back(New);
2481 PointerTypes.InsertNode(New, InsertPos);
2482 return QualType(New, 0);
2483}
2484
2485QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2486 llvm::FoldingSetNodeID ID;
2487 AdjustedType::Profile(ID, Orig, New);
2488 void *InsertPos = nullptr;
2489 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2490 if (AT)
2491 return QualType(AT, 0);
2492
2493 QualType Canonical = getCanonicalType(New);
2494
2495 // Get the new insert position for the node we care about.
2496 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2497 assert(!AT && "Shouldn't be in the map!")((!AT && "Shouldn't be in the map!") ? static_cast<
void> (0) : __assert_fail ("!AT && \"Shouldn't be in the map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2497, __PRETTY_FUNCTION__))
;
2498
2499 AT = new (*this, TypeAlignment)
2500 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2501 Types.push_back(AT);
2502 AdjustedTypes.InsertNode(AT, InsertPos);
2503 return QualType(AT, 0);
2504}
2505
2506QualType ASTContext::getDecayedType(QualType T) const {
2507 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay")(((T->isArrayType() || T->isFunctionType()) && "T does not decay"
) ? static_cast<void> (0) : __assert_fail ("(T->isArrayType() || T->isFunctionType()) && \"T does not decay\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2507, __PRETTY_FUNCTION__))
;
2508
2509 QualType Decayed;
2510
2511 // C99 6.7.5.3p7:
2512 // A declaration of a parameter as "array of type" shall be
2513 // adjusted to "qualified pointer to type", where the type
2514 // qualifiers (if any) are those specified within the [ and ] of
2515 // the array type derivation.
2516 if (T->isArrayType())
2517 Decayed = getArrayDecayedType(T);
2518
2519 // C99 6.7.5.3p8:
2520 // A declaration of a parameter as "function returning type"
2521 // shall be adjusted to "pointer to function returning type", as
2522 // in 6.3.2.1.
2523 if (T->isFunctionType())
2524 Decayed = getPointerType(T);
2525
2526 llvm::FoldingSetNodeID ID;
2527 AdjustedType::Profile(ID, T, Decayed);
2528 void *InsertPos = nullptr;
2529 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2530 if (AT)
2531 return QualType(AT, 0);
2532
2533 QualType Canonical = getCanonicalType(Decayed);
2534
2535 // Get the new insert position for the node we care about.
2536 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2537 assert(!AT && "Shouldn't be in the map!")((!AT && "Shouldn't be in the map!") ? static_cast<
void> (0) : __assert_fail ("!AT && \"Shouldn't be in the map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2537, __PRETTY_FUNCTION__))
;
2538
2539 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2540 Types.push_back(AT);
2541 AdjustedTypes.InsertNode(AT, InsertPos);
2542 return QualType(AT, 0);
2543}
2544
2545/// getBlockPointerType - Return the uniqued reference to the type for
2546/// a pointer to the specified block.
2547QualType ASTContext::getBlockPointerType(QualType T) const {
2548 assert(T->isFunctionType() && "block of function types only")((T->isFunctionType() && "block of function types only"
) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"block of function types only\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2548, __PRETTY_FUNCTION__))
;
2549 // Unique pointers, to guarantee there is only one block of a particular
2550 // structure.
2551 llvm::FoldingSetNodeID ID;
2552 BlockPointerType::Profile(ID, T);
2553
2554 void *InsertPos = nullptr;
2555 if (BlockPointerType *PT =
2556 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2557 return QualType(PT, 0);
2558
2559 // If the block pointee type isn't canonical, this won't be a canonical
2560 // type either so fill in the canonical type field.
2561 QualType Canonical;
2562 if (!T.isCanonical()) {
2563 Canonical = getBlockPointerType(getCanonicalType(T));
2564
2565 // Get the new insert position for the node we care about.
2566 BlockPointerType *NewIP =
2567 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2568 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2568, __PRETTY_FUNCTION__))
; (void)NewIP;
2569 }
2570 BlockPointerType *New
2571 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2572 Types.push_back(New);
2573 BlockPointerTypes.InsertNode(New, InsertPos);
2574 return QualType(New, 0);
2575}
2576
2577/// getLValueReferenceType - Return the uniqued reference to the type for an
2578/// lvalue reference to the specified type.
2579QualType
2580ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2581 assert(getCanonicalType(T) != OverloadTy &&((getCanonicalType(T) != OverloadTy && "Unresolved overloaded function type"
) ? static_cast<void> (0) : __assert_fail ("getCanonicalType(T) != OverloadTy && \"Unresolved overloaded function type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2582, __PRETTY_FUNCTION__))
2582 "Unresolved overloaded function type")((getCanonicalType(T) != OverloadTy && "Unresolved overloaded function type"
) ? static_cast<void> (0) : __assert_fail ("getCanonicalType(T) != OverloadTy && \"Unresolved overloaded function type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2582, __PRETTY_FUNCTION__))
;
2583
2584 // Unique pointers, to guarantee there is only one pointer of a particular
2585 // structure.
2586 llvm::FoldingSetNodeID ID;
2587 ReferenceType::Profile(ID, T, SpelledAsLValue);
2588
2589 void *InsertPos = nullptr;
2590 if (LValueReferenceType *RT =
2591 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2592 return QualType(RT, 0);
2593
2594 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2595
2596 // If the referencee type isn't canonical, this won't be a canonical type
2597 // either, so fill in the canonical type field.
2598 QualType Canonical;
2599 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2600 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2601 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2602
2603 // Get the new insert position for the node we care about.
2604 LValueReferenceType *NewIP =
2605 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2606 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2606, __PRETTY_FUNCTION__))
; (void)NewIP;
2607 }
2608
2609 LValueReferenceType *New
2610 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2611 SpelledAsLValue);
2612 Types.push_back(New);
2613 LValueReferenceTypes.InsertNode(New, InsertPos);
2614
2615 return QualType(New, 0);
2616}
2617
2618/// getRValueReferenceType - Return the uniqued reference to the type for an
2619/// rvalue reference to the specified type.
2620QualType ASTContext::getRValueReferenceType(QualType T) const {
2621 // Unique pointers, to guarantee there is only one pointer of a particular
2622 // structure.
2623 llvm::FoldingSetNodeID ID;
2624 ReferenceType::Profile(ID, T, false);
2625
2626 void *InsertPos = nullptr;
2627 if (RValueReferenceType *RT =
2628 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2629 return QualType(RT, 0);
2630
2631 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2632
2633 // If the referencee type isn't canonical, this won't be a canonical type
2634 // either, so fill in the canonical type field.
2635 QualType Canonical;
2636 if (InnerRef || !T.isCanonical()) {
2637 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2638 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2639
2640 // Get the new insert position for the node we care about.
2641 RValueReferenceType *NewIP =
2642 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2643 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2643, __PRETTY_FUNCTION__))
; (void)NewIP;
2644 }
2645
2646 RValueReferenceType *New
2647 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2648 Types.push_back(New);
2649 RValueReferenceTypes.InsertNode(New, InsertPos);
2650 return QualType(New, 0);
2651}
2652
2653/// getMemberPointerType - Return the uniqued reference to the type for a
2654/// member pointer to the specified type, in the specified class.
2655QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2656 // Unique pointers, to guarantee there is only one pointer of a particular
2657 // structure.
2658 llvm::FoldingSetNodeID ID;
2659 MemberPointerType::Profile(ID, T, Cls);
2660
2661 void *InsertPos = nullptr;
2662 if (MemberPointerType *PT =
2663 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2664 return QualType(PT, 0);
2665
2666 // If the pointee or class type isn't canonical, this won't be a canonical
2667 // type either, so fill in the canonical type field.
2668 QualType Canonical;
2669 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2670 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2671
2672 // Get the new insert position for the node we care about.
2673 MemberPointerType *NewIP =
2674 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2675 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2675, __PRETTY_FUNCTION__))
; (void)NewIP;
2676 }
2677 MemberPointerType *New
2678 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2679 Types.push_back(New);
2680 MemberPointerTypes.InsertNode(New, InsertPos);
2681 return QualType(New, 0);
2682}
2683
2684/// getConstantArrayType - Return the unique reference to the type for an
2685/// array of the specified element type.
2686QualType ASTContext::getConstantArrayType(QualType EltTy,
2687 const llvm::APInt &ArySizeIn,
2688 ArrayType::ArraySizeModifier ASM,
2689 unsigned IndexTypeQuals) const {
2690 assert((EltTy->isDependentType() ||(((EltTy->isDependentType() || EltTy->isIncompleteType(
) || EltTy->isConstantSizeType()) && "Constant array of VLAs is illegal!"
) ? static_cast<void> (0) : __assert_fail ("(EltTy->isDependentType() || EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && \"Constant array of VLAs is illegal!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2692, __PRETTY_FUNCTION__))
2691 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&(((EltTy->isDependentType() || EltTy->isIncompleteType(
) || EltTy->isConstantSizeType()) && "Constant array of VLAs is illegal!"
) ? static_cast<void> (0) : __assert_fail ("(EltTy->isDependentType() || EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && \"Constant array of VLAs is illegal!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2692, __PRETTY_FUNCTION__))
2692 "Constant array of VLAs is illegal!")(((EltTy->isDependentType() || EltTy->isIncompleteType(
) || EltTy->isConstantSizeType()) && "Constant array of VLAs is illegal!"
) ? static_cast<void> (0) : __assert_fail ("(EltTy->isDependentType() || EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && \"Constant array of VLAs is illegal!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2692, __PRETTY_FUNCTION__))
;
2693
2694 // Convert the array size into a canonical width matching the pointer size for
2695 // the target.
2696 llvm::APInt ArySize(ArySizeIn);
2697 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
2698
2699 llvm::FoldingSetNodeID ID;
2700 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2701
2702 void *InsertPos = nullptr;
2703 if (ConstantArrayType *ATP =
2704 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2705 return QualType(ATP, 0);
2706
2707 // If the element type isn't canonical or has qualifiers, this won't
2708 // be a canonical type either, so fill in the canonical type field.
2709 QualType Canon;
2710 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2711 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2712 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2713 ASM, IndexTypeQuals);
2714 Canon = getQualifiedType(Canon, canonSplit.Quals);
2715
2716 // Get the new insert position for the node we care about.
2717 ConstantArrayType *NewIP =
2718 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2719 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2719, __PRETTY_FUNCTION__))
; (void)NewIP;
2720 }
2721
2722 ConstantArrayType *New = new(*this,TypeAlignment)
2723 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2724 ConstantArrayTypes.InsertNode(New, InsertPos);
2725 Types.push_back(New);
2726 return QualType(New, 0);
2727}
2728
2729/// getVariableArrayDecayedType - Turns the given type, which may be
2730/// variably-modified, into the corresponding type with all the known
2731/// sizes replaced with [*].
2732QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2733 // Vastly most common case.
2734 if (!type->isVariablyModifiedType()) return type;
2735
2736 QualType result;
2737
2738 SplitQualType split = type.getSplitDesugaredType();
2739 const Type *ty = split.Ty;
2740 switch (ty->getTypeClass()) {
2741#define TYPE(Class, Base)
2742#define ABSTRACT_TYPE(Class, Base)
2743#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2744#include "clang/AST/TypeNodes.def"
2745 llvm_unreachable("didn't desugar past all non-canonical types?")::llvm::llvm_unreachable_internal("didn't desugar past all non-canonical types?"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2745)
;
2746
2747 // These types should never be variably-modified.
2748 case Type::Builtin:
2749 case Type::Complex:
2750 case Type::Vector:
2751 case Type::ExtVector:
2752 case Type::DependentSizedExtVector:
2753 case Type::ObjCObject:
2754 case Type::ObjCInterface:
2755 case Type::ObjCObjectPointer:
2756 case Type::Record:
2757 case Type::Enum:
2758 case Type::UnresolvedUsing:
2759 case Type::TypeOfExpr:
2760 case Type::TypeOf:
2761 case Type::Decltype:
2762 case Type::UnaryTransform:
2763 case Type::DependentName:
2764 case Type::InjectedClassName:
2765 case Type::TemplateSpecialization:
2766 case Type::DependentTemplateSpecialization:
2767 case Type::TemplateTypeParm:
2768 case Type::SubstTemplateTypeParmPack:
2769 case Type::Auto:
2770 case Type::DeducedTemplateSpecialization:
2771 case Type::PackExpansion:
2772 llvm_unreachable("type should never be variably-modified")::llvm::llvm_unreachable_internal("type should never be variably-modified"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2772)
;
2773
2774 // These types can be variably-modified but should never need to
2775 // further decay.
2776 case Type::FunctionNoProto:
2777 case Type::FunctionProto:
2778 case Type::BlockPointer:
2779 case Type::MemberPointer:
2780 case Type::Pipe:
2781 return type;
2782
2783 // These types can be variably-modified. All these modifications
2784 // preserve structure except as noted by comments.
2785 // TODO: if we ever care about optimizing VLAs, there are no-op
2786 // optimizations available here.
2787 case Type::Pointer:
2788 result = getPointerType(getVariableArrayDecayedType(
2789 cast<PointerType>(ty)->getPointeeType()));
2790 break;
2791
2792 case Type::LValueReference: {
2793 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2794 result = getLValueReferenceType(
2795 getVariableArrayDecayedType(lv->getPointeeType()),
2796 lv->isSpelledAsLValue());
2797 break;
2798 }
2799
2800 case Type::RValueReference: {
2801 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2802 result = getRValueReferenceType(
2803 getVariableArrayDecayedType(lv->getPointeeType()));
2804 break;
2805 }
2806
2807 case Type::Atomic: {
2808 const AtomicType *at = cast<AtomicType>(ty);
2809 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2810 break;
2811 }
2812
2813 case Type::ConstantArray: {
2814 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2815 result = getConstantArrayType(
2816 getVariableArrayDecayedType(cat->getElementType()),
2817 cat->getSize(),
2818 cat->getSizeModifier(),
2819 cat->getIndexTypeCVRQualifiers());
2820 break;
2821 }
2822
2823 case Type::DependentSizedArray: {
2824 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2825 result = getDependentSizedArrayType(
2826 getVariableArrayDecayedType(dat->getElementType()),
2827 dat->getSizeExpr(),
2828 dat->getSizeModifier(),
2829 dat->getIndexTypeCVRQualifiers(),
2830 dat->getBracketsRange());
2831 break;
2832 }
2833
2834 // Turn incomplete types into [*] types.
2835 case Type::IncompleteArray: {
2836 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2837 result = getVariableArrayType(
2838 getVariableArrayDecayedType(iat->getElementType()),
2839 /*size*/ nullptr,
2840 ArrayType::Normal,
2841 iat->getIndexTypeCVRQualifiers(),
2842 SourceRange());
2843 break;
2844 }
2845
2846 // Turn VLA types into [*] types.
2847 case Type::VariableArray: {
2848 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2849 result = getVariableArrayType(
2850 getVariableArrayDecayedType(vat->getElementType()),
2851 /*size*/ nullptr,
2852 ArrayType::Star,
2853 vat->getIndexTypeCVRQualifiers(),
2854 vat->getBracketsRange());
2855 break;
2856 }
2857 }
2858
2859 // Apply the top-level qualifiers from the original.
2860 return getQualifiedType(result, split.Quals);
2861}
2862
2863/// getVariableArrayType - Returns a non-unique reference to the type for a
2864/// variable array of the specified element type.
2865QualType ASTContext::getVariableArrayType(QualType EltTy,
2866 Expr *NumElts,
2867 ArrayType::ArraySizeModifier ASM,
2868 unsigned IndexTypeQuals,
2869 SourceRange Brackets) const {
2870 // Since we don't unique expressions, it isn't possible to unique VLA's
2871 // that have an expression provided for their size.
2872 QualType Canon;
2873
2874 // Be sure to pull qualifiers off the element type.
2875 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2876 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2877 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2878 IndexTypeQuals, Brackets);
2879 Canon = getQualifiedType(Canon, canonSplit.Quals);
2880 }
2881
2882 VariableArrayType *New = new(*this, TypeAlignment)
2883 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2884
2885 VariableArrayTypes.push_back(New);
2886 Types.push_back(New);
2887 return QualType(New, 0);
2888}
2889
2890/// getDependentSizedArrayType - Returns a non-unique reference to
2891/// the type for a dependently-sized array of the specified element
2892/// type.
2893QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2894 Expr *numElements,
2895 ArrayType::ArraySizeModifier ASM,
2896 unsigned elementTypeQuals,
2897 SourceRange brackets) const {
2898 assert((!numElements || numElements->isTypeDependent() ||(((!numElements || numElements->isTypeDependent() || numElements
->isValueDependent()) && "Size must be type- or value-dependent!"
) ? static_cast<void> (0) : __assert_fail ("(!numElements || numElements->isTypeDependent() || numElements->isValueDependent()) && \"Size must be type- or value-dependent!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2900, __PRETTY_FUNCTION__))
2899 numElements->isValueDependent()) &&(((!numElements || numElements->isTypeDependent() || numElements
->isValueDependent()) && "Size must be type- or value-dependent!"
) ? static_cast<void> (0) : __assert_fail ("(!numElements || numElements->isTypeDependent() || numElements->isValueDependent()) && \"Size must be type- or value-dependent!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2900, __PRETTY_FUNCTION__))
2900 "Size must be type- or value-dependent!")(((!numElements || numElements->isTypeDependent() || numElements
->isValueDependent()) && "Size must be type- or value-dependent!"
) ? static_cast<void> (0) : __assert_fail ("(!numElements || numElements->isTypeDependent() || numElements->isValueDependent()) && \"Size must be type- or value-dependent!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2900, __PRETTY_FUNCTION__))
;
2901
2902 // Dependently-sized array types that do not have a specified number
2903 // of elements will have their sizes deduced from a dependent
2904 // initializer. We do no canonicalization here at all, which is okay
2905 // because they can't be used in most locations.
2906 if (!numElements) {
2907 DependentSizedArrayType *newType
2908 = new (*this, TypeAlignment)
2909 DependentSizedArrayType(*this, elementType, QualType(),
2910 numElements, ASM, elementTypeQuals,
2911 brackets);
2912 Types.push_back(newType);
2913 return QualType(newType, 0);
2914 }
2915
2916 // Otherwise, we actually build a new type every time, but we
2917 // also build a canonical type.
2918
2919 SplitQualType canonElementType = getCanonicalType(elementType).split();
2920
2921 void *insertPos = nullptr;
2922 llvm::FoldingSetNodeID ID;
2923 DependentSizedArrayType::Profile(ID, *this,
2924 QualType(canonElementType.Ty, 0),
2925 ASM, elementTypeQuals, numElements);
2926
2927 // Look for an existing type with these properties.
2928 DependentSizedArrayType *canonTy =
2929 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2930
2931 // If we don't have one, build one.
2932 if (!canonTy) {
2933 canonTy = new (*this, TypeAlignment)
2934 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2935 QualType(), numElements, ASM, elementTypeQuals,
2936 brackets);
2937 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2938 Types.push_back(canonTy);
2939 }
2940
2941 // Apply qualifiers from the element type to the array.
2942 QualType canon = getQualifiedType(QualType(canonTy,0),
2943 canonElementType.Quals);
2944
2945 // If we didn't need extra canonicalization for the element type or the size
2946 // expression, then just use that as our result.
2947 if (QualType(canonElementType.Ty, 0) == elementType &&
2948 canonTy->getSizeExpr() == numElements)
2949 return canon;
2950
2951 // Otherwise, we need to build a type which follows the spelling
2952 // of the element type.
2953 DependentSizedArrayType *sugaredType
2954 = new (*this, TypeAlignment)
2955 DependentSizedArrayType(*this, elementType, canon, numElements,
2956 ASM, elementTypeQuals, brackets);
2957 Types.push_back(sugaredType);
2958 return QualType(sugaredType, 0);
2959}
2960
2961QualType ASTContext::getIncompleteArrayType(QualType elementType,
2962 ArrayType::ArraySizeModifier ASM,
2963 unsigned elementTypeQuals) const {
2964 llvm::FoldingSetNodeID ID;
2965 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2966
2967 void *insertPos = nullptr;
2968 if (IncompleteArrayType *iat =
2969 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2970 return QualType(iat, 0);
2971
2972 // If the element type isn't canonical, this won't be a canonical type
2973 // either, so fill in the canonical type field. We also have to pull
2974 // qualifiers off the element type.
2975 QualType canon;
2976
2977 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2978 SplitQualType canonSplit = getCanonicalType(elementType).split();
2979 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2980 ASM, elementTypeQuals);
2981 canon = getQualifiedType(canon, canonSplit.Quals);
2982
2983 // Get the new insert position for the node we care about.
2984 IncompleteArrayType *existing =
2985 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2986 assert(!existing && "Shouldn't be in the map!")((!existing && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!existing && \"Shouldn't be in the map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 2986, __PRETTY_FUNCTION__))
; (void) existing;
2987 }
2988
2989 IncompleteArrayType *newType = new (*this, TypeAlignment)
2990 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2991
2992 IncompleteArrayTypes.InsertNode(newType, insertPos);
2993 Types.push_back(newType);
2994 return QualType(newType, 0);
2995}
2996
2997/// getVectorType - Return the unique reference to a vector type of
2998/// the specified element type and size. VectorType must be a built-in type.
2999QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3000 VectorType::VectorKind VecKind) const {
3001 assert(vecType->isBuiltinType())((vecType->isBuiltinType()) ? static_cast<void> (0) :
__assert_fail ("vecType->isBuiltinType()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3001, __PRETTY_FUNCTION__))
;
3002
3003 // Check if we've already instantiated a vector of this type.
3004 llvm::FoldingSetNodeID ID;
3005 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3006
3007 void *InsertPos = nullptr;
3008 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3009 return QualType(VTP, 0);
3010
3011 // If the element type isn't canonical, this won't be a canonical type either,
3012 // so fill in the canonical type field.
3013 QualType Canonical;
3014 if (!vecType.isCanonical()) {
3015 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
3016
3017 // Get the new insert position for the node we care about.
3018 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3019 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3019, __PRETTY_FUNCTION__))
; (void)NewIP;
3020 }
3021 VectorType *New = new (*this, TypeAlignment)
3022 VectorType(vecType, NumElts, Canonical, VecKind);
3023 VectorTypes.InsertNode(New, InsertPos);
3024 Types.push_back(New);
3025 return QualType(New, 0);
3026}
3027
3028/// getExtVectorType - Return the unique reference to an extended vector type of
3029/// the specified element type and size. VectorType must be a built-in type.
3030QualType
3031ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
3032 assert(vecType->isBuiltinType() || vecType->isDependentType())((vecType->isBuiltinType() || vecType->isDependentType(
)) ? static_cast<void> (0) : __assert_fail ("vecType->isBuiltinType() || vecType->isDependentType()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3032, __PRETTY_FUNCTION__))
;
3033
3034 // Check if we've already instantiated a vector of this type.
3035 llvm::FoldingSetNodeID ID;
3036 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
3037 VectorType::GenericVector);
3038 void *InsertPos = nullptr;
3039 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3040 return QualType(VTP, 0);
3041
3042 // If the element type isn't canonical, this won't be a canonical type either,
3043 // so fill in the canonical type field.
3044 QualType Canonical;
3045 if (!vecType.isCanonical()) {
3046 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
3047
3048 // Get the new insert position for the node we care about.
3049 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3050 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3050, __PRETTY_FUNCTION__))
; (void)NewIP;
3051 }
3052 ExtVectorType *New = new (*this, TypeAlignment)
3053 ExtVectorType(vecType, NumElts, Canonical);
3054 VectorTypes.InsertNode(New, InsertPos);
3055 Types.push_back(New);
3056 return QualType(New, 0);
3057}
3058
3059QualType
3060ASTContext::getDependentSizedExtVectorType(QualType vecType,
3061 Expr *SizeExpr,
3062 SourceLocation AttrLoc) const {
3063 llvm::FoldingSetNodeID ID;
3064 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
3065 SizeExpr);
3066
3067 void *InsertPos = nullptr;
3068 DependentSizedExtVectorType *Canon
3069 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3070 DependentSizedExtVectorType *New;
3071 if (Canon) {
3072 // We already have a canonical version of this array type; use it as
3073 // the canonical type for a newly-built type.
3074 New = new (*this, TypeAlignment)
3075 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3076 SizeExpr, AttrLoc);
3077 } else {
3078 QualType CanonVecTy = getCanonicalType(vecType);
3079 if (CanonVecTy == vecType) {
3080 New = new (*this, TypeAlignment)
3081 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3082 AttrLoc);
3083
3084 DependentSizedExtVectorType *CanonCheck
3085 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3086 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken")((!CanonCheck && "Dependent-sized ext_vector canonical type broken"
) ? static_cast<void> (0) : __assert_fail ("!CanonCheck && \"Dependent-sized ext_vector canonical type broken\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3086, __PRETTY_FUNCTION__))
;
3087 (void)CanonCheck;
3088 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3089 } else {
3090 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3091 SourceLocation());
3092 New = new (*this, TypeAlignment)
3093 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
3094 }
3095 }
3096
3097 Types.push_back(New);
3098 return QualType(New, 0);
3099}
3100
3101/// \brief Determine whether \p T is canonical as the result type of a function.
3102static bool isCanonicalResultType(QualType T) {
3103 return T.isCanonical() &&
3104 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3105 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3106}
3107
3108/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
3109///
3110QualType
3111ASTContext::getFunctionNoProtoType(QualType ResultTy,
3112 const FunctionType::ExtInfo &Info) const {
3113 // Unique functions, to guarantee there is only one function of a particular
3114 // structure.
3115 llvm::FoldingSetNodeID ID;
3116 FunctionNoProtoType::Profile(ID, ResultTy, Info);
3117
3118 void *InsertPos = nullptr;
3119 if (FunctionNoProtoType *FT =
3120 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3121 return QualType(FT, 0);
3122
3123 QualType Canonical;
3124 if (!isCanonicalResultType(ResultTy)) {
3125 Canonical =
3126 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
3127
3128 // Get the new insert position for the node we care about.
3129 FunctionNoProtoType *NewIP =
3130 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3131 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3131, __PRETTY_FUNCTION__))
; (void)NewIP;
3132 }
3133
3134 FunctionNoProtoType *New = new (*this, TypeAlignment)
3135 FunctionNoProtoType(ResultTy, Canonical, Info);
3136 Types.push_back(New);
3137 FunctionNoProtoTypes.InsertNode(New, InsertPos);
3138 return QualType(New, 0);
3139}
3140
3141CanQualType
3142ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3143 CanQualType CanResultType = getCanonicalType(ResultType);
3144
3145 // Canonical result types do not have ARC lifetime qualifiers.
3146 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3147 Qualifiers Qs = CanResultType.getQualifiers();
3148 Qs.removeObjCLifetime();
3149 return CanQualType::CreateUnsafe(
3150 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3151 }
3152
3153 return CanResultType;
3154}
3155
3156static bool isCanonicalExceptionSpecification(
3157 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3158 if (ESI.Type == EST_None)
3159 return true;
3160 if (!NoexceptInType)
3161 return false;
3162
3163 // C++17 onwards: exception specification is part of the type, as a simple
3164 // boolean "can this function type throw".
3165 if (ESI.Type == EST_BasicNoexcept)
3166 return true;
3167
3168 // A dynamic exception specification is canonical if it only contains pack
3169 // expansions (so we can't tell whether it's non-throwing) and all its
3170 // contained types are canonical.
3171 if (ESI.Type == EST_Dynamic) {
3172 bool AnyPackExpansions = false;
3173 for (QualType ET : ESI.Exceptions) {
3174 if (!ET.isCanonical())
3175 return false;
3176 if (ET->getAs<PackExpansionType>())
3177 AnyPackExpansions = true;
3178 }
3179 return AnyPackExpansions;
3180 }
3181
3182 // A noexcept(expr) specification is (possibly) canonical if expr is
3183 // value-dependent.
3184 if (ESI.Type == EST_ComputedNoexcept)
3185 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent();
3186
3187 return false;
3188}
3189
3190QualType ASTContext::getFunctionTypeInternal(
3191 QualType ResultTy, ArrayRef<QualType> ArgArray,
3192 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
3193 size_t NumArgs = ArgArray.size();
3194
3195 // Unique functions, to guarantee there is only one function of a particular
3196 // structure.
3197 llvm::FoldingSetNodeID ID;
3198 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3199 *this, true);
3200
3201 QualType Canonical;
3202 bool Unique = false;
3203
3204 void *InsertPos = nullptr;
3205 if (FunctionProtoType *FPT =
3206 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3207 QualType Existing = QualType(FPT, 0);
3208
3209 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3210 // it so long as our exception specification doesn't contain a dependent
3211 // noexcept expression, or we're just looking for a canonical type.
3212 // Otherwise, we're going to need to create a type
3213 // sugar node to hold the concrete expression.
3214 if (OnlyWantCanonical || EPI.ExceptionSpec.Type != EST_ComputedNoexcept ||
3215 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3216 return Existing;
3217
3218 // We need a new type sugar node for this one, to hold the new noexcept
3219 // expression. We do no canonicalization here, but that's OK since we don't
3220 // expect to see the same noexcept expression much more than once.
3221 Canonical = getCanonicalType(Existing);
3222 Unique = true;
3223 }
3224
3225 bool NoexceptInType = getLangOpts().CPlusPlus1z;
3226 bool IsCanonicalExceptionSpec =
3227 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3228
3229 // Determine whether the type being created is already canonical or not.
3230 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
3231 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
3232 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
3233 if (!ArgArray[i].isCanonicalAsParam())
3234 isCanonical = false;
3235
3236 if (OnlyWantCanonical)
3237 assert(isCanonical &&((isCanonical && "given non-canonical parameters constructing canonical type"
) ? static_cast<void> (0) : __assert_fail ("isCanonical && \"given non-canonical parameters constructing canonical type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3238, __PRETTY_FUNCTION__))
3238 "given non-canonical parameters constructing canonical type")((isCanonical && "given non-canonical parameters constructing canonical type"
) ? static_cast<void> (0) : __assert_fail ("isCanonical && \"given non-canonical parameters constructing canonical type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3238, __PRETTY_FUNCTION__))
;
3239
3240 // If this type isn't canonical, get the canonical version of it if we don't
3241 // already have it. The exception spec is only partially part of the
3242 // canonical type, and only in C++17 onwards.
3243 if (!isCanonical && Canonical.isNull()) {
3244 SmallVector<QualType, 16> CanonicalArgs;
3245 CanonicalArgs.reserve(NumArgs);
3246 for (unsigned i = 0; i != NumArgs; ++i)
3247 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
3248
3249 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
3250 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
3251 CanonicalEPI.HasTrailingReturn = false;
3252
3253 if (IsCanonicalExceptionSpec) {
3254 // Exception spec is already OK.
3255 } else if (NoexceptInType) {
3256 switch (EPI.ExceptionSpec.Type) {
3257 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3258 // We don't know yet. It shouldn't matter what we pick here; no-one
3259 // should ever look at this.
3260 LLVM_FALLTHROUGH[[clang::fallthrough]];
3261 case EST_None: case EST_MSAny:
3262 CanonicalEPI.ExceptionSpec.Type = EST_None;
3263 break;
3264
3265 // A dynamic exception specification is almost always "not noexcept",
3266 // with the exception that a pack expansion might expand to no types.
3267 case EST_Dynamic: {
3268 bool AnyPacks = false;
3269 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3270 if (ET->getAs<PackExpansionType>())
3271 AnyPacks = true;
3272 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3273 }
3274 if (!AnyPacks)
3275 CanonicalEPI.ExceptionSpec.Type = EST_None;
3276 else {
3277 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3278 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3279 }
3280 break;
3281 }
3282
3283 case EST_DynamicNone: case EST_BasicNoexcept:
3284 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3285 break;
3286
3287 case EST_ComputedNoexcept:
3288 llvm::APSInt Value(1);
3289 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr;
3290 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr,
3291 /*IsEvaluated*/false)) {
3292 // This noexcept specification is invalid.
3293 // FIXME: Should this be able to happen?
3294 CanonicalEPI.ExceptionSpec.Type = EST_None;
3295 break;
3296 }
3297
3298 CanonicalEPI.ExceptionSpec.Type =
3299 Value.getBoolValue() ? EST_BasicNoexcept : EST_None;
3300 break;
3301 }
3302 } else {
3303 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3304 }
3305
3306 // Adjust the canonical function result type.
3307 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
3308 Canonical =
3309 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
3310
3311 // Get the new insert position for the node we care about.
3312 FunctionProtoType *NewIP =
3313 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3314 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3314, __PRETTY_FUNCTION__))
; (void)NewIP;
3315 }
3316
3317 // FunctionProtoType objects are allocated with extra bytes after
3318 // them for three variable size arrays at the end:
3319 // - parameter types
3320 // - exception types
3321 // - extended parameter information
3322 // Instead of the exception types, there could be a noexcept
3323 // expression, or information used to resolve the exception
3324 // specification.
3325 size_t Size = sizeof(FunctionProtoType) +
3326 NumArgs * sizeof(QualType);
3327
3328 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3329 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3330 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3331 Size += sizeof(Expr*);
3332 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3333 Size += 2 * sizeof(FunctionDecl*);
3334 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3335 Size += sizeof(FunctionDecl*);
3336 }
3337
3338 // Put the ExtParameterInfos last. If all were equal, it would make
3339 // more sense to put these before the exception specification, because
3340 // it's much easier to skip past them compared to the elaborate switch
3341 // required to skip the exception specification. However, all is not
3342 // equal; ExtParameterInfos are used to model very uncommon features,
3343 // and it's better not to burden the more common paths.
3344 if (EPI.ExtParameterInfos) {
3345 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3346 }
3347
3348 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
3349 FunctionProtoType::ExtProtoInfo newEPI = EPI;
3350 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
3351 Types.push_back(FTP);
3352 if (!Unique)
3353 FunctionProtoTypes.InsertNode(FTP, InsertPos);
3354 return QualType(FTP, 0);
3355}
3356
3357QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
3358 llvm::FoldingSetNodeID ID;
3359 PipeType::Profile(ID, T, ReadOnly);
3360
3361 void *InsertPos = 0;
3362 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3363 return QualType(PT, 0);
3364
3365 // If the pipe element type isn't canonical, this won't be a canonical type
3366 // either, so fill in the canonical type field.
3367 QualType Canonical;
3368 if (!T.isCanonical()) {
3369 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
3370
3371 // Get the new insert position for the node we care about.
3372 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3373 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3373, __PRETTY_FUNCTION__))
;
3374 (void)NewIP;
3375 }
3376 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
3377 Types.push_back(New);
3378 PipeTypes.InsertNode(New, InsertPos);
3379 return QualType(New, 0);
3380}
3381
3382QualType ASTContext::getReadPipeType(QualType T) const {
3383 return getPipeType(T, true);
3384}
3385
3386QualType ASTContext::getWritePipeType(QualType T) const {
3387 return getPipeType(T, false);
3388}
3389
3390#ifndef NDEBUG
3391static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3392 if (!isa<CXXRecordDecl>(D)) return false;
3393 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3394 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3395 return true;
3396 if (RD->getDescribedClassTemplate() &&
3397 !isa<ClassTemplateSpecializationDecl>(RD))
3398 return true;
3399 return false;
3400}
3401#endif
3402
3403/// getInjectedClassNameType - Return the unique reference to the
3404/// injected class name type for the specified templated declaration.
3405QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
3406 QualType TST) const {
3407 assert(NeedsInjectedClassNameType(Decl))((NeedsInjectedClassNameType(Decl)) ? static_cast<void>
(0) : __assert_fail ("NeedsInjectedClassNameType(Decl)", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3407, __PRETTY_FUNCTION__))
;
3408 if (Decl->TypeForDecl) {
3409 assert(isa<InjectedClassNameType>(Decl->TypeForDecl))((isa<InjectedClassNameType>(Decl->TypeForDecl)) ? static_cast
<void> (0) : __assert_fail ("isa<InjectedClassNameType>(Decl->TypeForDecl)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3409, __PRETTY_FUNCTION__))
;
3410 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
3411 assert(PrevDecl->TypeForDecl && "previous declaration has no type")((PrevDecl->TypeForDecl && "previous declaration has no type"
) ? static_cast<void> (0) : __assert_fail ("PrevDecl->TypeForDecl && \"previous declaration has no type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3411, __PRETTY_FUNCTION__))
;
3412 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3413 assert(isa<InjectedClassNameType>(Decl->TypeForDecl))((isa<InjectedClassNameType>(Decl->TypeForDecl)) ? static_cast
<void> (0) : __assert_fail ("isa<InjectedClassNameType>(Decl->TypeForDecl)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3413, __PRETTY_FUNCTION__))
;
3414 } else {
3415 Type *newType =
3416 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
3417 Decl->TypeForDecl = newType;
3418 Types.push_back(newType);
3419 }
3420 return QualType(Decl->TypeForDecl, 0);
3421}
3422
3423/// getTypeDeclType - Return the unique reference to the type for the
3424/// specified type declaration.
3425QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
3426 assert(Decl && "Passed null for Decl param")((Decl && "Passed null for Decl param") ? static_cast
<void> (0) : __assert_fail ("Decl && \"Passed null for Decl param\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3426, __PRETTY_FUNCTION__))
;
3427 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case")((!Decl->TypeForDecl && "TypeForDecl present in slow case"
) ? static_cast<void> (0) : __assert_fail ("!Decl->TypeForDecl && \"TypeForDecl present in slow case\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3427, __PRETTY_FUNCTION__))
;
3428
3429 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
3430 return getTypedefType(Typedef);
3431
3432 assert(!isa<TemplateTypeParmDecl>(Decl) &&((!isa<TemplateTypeParmDecl>(Decl) && "Template type parameter types are always available."
) ? static_cast<void> (0) : __assert_fail ("!isa<TemplateTypeParmDecl>(Decl) && \"Template type parameter types are always available.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3433, __PRETTY_FUNCTION__))
3433 "Template type parameter types are always available.")((!isa<TemplateTypeParmDecl>(Decl) && "Template type parameter types are always available."
) ? static_cast<void> (0) : __assert_fail ("!isa<TemplateTypeParmDecl>(Decl) && \"Template type parameter types are always available.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3433, __PRETTY_FUNCTION__))
;
3434
3435 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
3436 assert(Record->isFirstDecl() && "struct/union has previous declaration")((Record->isFirstDecl() && "struct/union has previous declaration"
) ? static_cast<void> (0) : __assert_fail ("Record->isFirstDecl() && \"struct/union has previous declaration\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3436, __PRETTY_FUNCTION__))
;
3437 assert(!NeedsInjectedClassNameType(Record))((!NeedsInjectedClassNameType(Record)) ? static_cast<void>
(0) : __assert_fail ("!NeedsInjectedClassNameType(Record)", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3437, __PRETTY_FUNCTION__))
;
3438 return getRecordType(Record);
3439 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
3440 assert(Enum->isFirstDecl() && "enum has previous declaration")((Enum->isFirstDecl() && "enum has previous declaration"
) ? static_cast<void> (0) : __assert_fail ("Enum->isFirstDecl() && \"enum has previous declaration\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3440, __PRETTY_FUNCTION__))
;
3441 return getEnumType(Enum);
3442 } else if (const UnresolvedUsingTypenameDecl *Using =
3443 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
3444 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3445 Decl->TypeForDecl = newType;
3446 Types.push_back(newType);
3447 } else
3448 llvm_unreachable("TypeDecl without a type?")::llvm::llvm_unreachable_internal("TypeDecl without a type?",
"/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3448)
;
3449
3450 return QualType(Decl->TypeForDecl, 0);
3451}
3452
3453/// getTypedefType - Return the unique reference to the type for the
3454/// specified typedef name decl.
3455QualType
3456ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3457 QualType Canonical) const {
3458 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3459
3460 if (Canonical.isNull())
3461 Canonical = getCanonicalType(Decl->getUnderlyingType());
3462 TypedefType *newType = new(*this, TypeAlignment)
3463 TypedefType(Type::Typedef, Decl, Canonical);
3464 Decl->TypeForDecl = newType;
3465 Types.push_back(newType);
3466 return QualType(newType, 0);
3467}
3468
3469QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
3470 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3471
3472 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
3473 if (PrevDecl->TypeForDecl)
3474 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3475
3476 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3477 Decl->TypeForDecl = newType;
3478 Types.push_back(newType);
3479 return QualType(newType, 0);
3480}
3481
3482QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
3483 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3484
3485 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3486 if (PrevDecl->TypeForDecl)
3487 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3488
3489 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3490 Decl->TypeForDecl = newType;
3491 Types.push_back(newType);
3492 return QualType(newType, 0);
3493}
3494
3495QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3496 QualType modifiedType,
3497 QualType equivalentType) {
3498 llvm::FoldingSetNodeID id;
3499 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3500
3501 void *insertPos = nullptr;
3502 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3503 if (type) return QualType(type, 0);
3504
3505 QualType canon = getCanonicalType(equivalentType);
3506 type = new (*this, TypeAlignment)
3507 AttributedType(canon, attrKind, modifiedType, equivalentType);
3508
3509 Types.push_back(type);
3510 AttributedTypes.InsertNode(type, insertPos);
3511
3512 return QualType(type, 0);
3513}
3514
3515/// \brief Retrieve a substitution-result type.
3516QualType
3517ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3518 QualType Replacement) const {
3519 assert(Replacement.isCanonical()((Replacement.isCanonical() && "replacement types must always be canonical"
) ? static_cast<void> (0) : __assert_fail ("Replacement.isCanonical() && \"replacement types must always be canonical\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3520, __PRETTY_FUNCTION__))
3520 && "replacement types must always be canonical")((Replacement.isCanonical() && "replacement types must always be canonical"
) ? static_cast<void> (0) : __assert_fail ("Replacement.isCanonical() && \"replacement types must always be canonical\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3520, __PRETTY_FUNCTION__))
;
3521
3522 llvm::FoldingSetNodeID ID;
3523 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3524 void *InsertPos = nullptr;
3525 SubstTemplateTypeParmType *SubstParm
3526 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3527
3528 if (!SubstParm) {
3529 SubstParm = new (*this, TypeAlignment)
3530 SubstTemplateTypeParmType(Parm, Replacement);
3531 Types.push_back(SubstParm);
3532 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3533 }
3534
3535 return QualType(SubstParm, 0);
3536}
3537
3538/// \brief Retrieve a
3539QualType ASTContext::getSubstTemplateTypeParmPackType(
3540 const TemplateTypeParmType *Parm,
3541 const TemplateArgument &ArgPack) {
3542#ifndef NDEBUG
3543 for (const auto &P : ArgPack.pack_elements()) {
3544 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type")((P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"
) ? static_cast<void> (0) : __assert_fail ("P.getKind() == TemplateArgument::Type &&\"Pack contains a non-type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3544, __PRETTY_FUNCTION__))
;
3545 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type")((P.getAsType().isCanonical() && "Pack contains non-canonical type"
) ? static_cast<void> (0) : __assert_fail ("P.getAsType().isCanonical() && \"Pack contains non-canonical type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3545, __PRETTY_FUNCTION__))
;
3546 }
3547#endif
3548
3549 llvm::FoldingSetNodeID ID;
3550 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3551 void *InsertPos = nullptr;
3552 if (SubstTemplateTypeParmPackType *SubstParm
3553 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3554 return QualType(SubstParm, 0);
3555
3556 QualType Canon;
3557 if (!Parm->isCanonicalUnqualified()) {
3558 Canon = getCanonicalType(QualType(Parm, 0));
3559 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3560 ArgPack);
3561 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3562 }
3563
3564 SubstTemplateTypeParmPackType *SubstParm
3565 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3566 ArgPack);
3567 Types.push_back(SubstParm);
3568 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
3569 return QualType(SubstParm, 0);
3570}
3571
3572/// \brief Retrieve the template type parameter type for a template
3573/// parameter or parameter pack with the given depth, index, and (optionally)
3574/// name.
3575QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3576 bool ParameterPack,
3577 TemplateTypeParmDecl *TTPDecl) const {
3578 llvm::FoldingSetNodeID ID;
3579 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3580 void *InsertPos = nullptr;
3581 TemplateTypeParmType *TypeParm
3582 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3583
3584 if (TypeParm)
3585 return QualType(TypeParm, 0);
3586
3587 if (TTPDecl) {
3588 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3589 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3590
3591 TemplateTypeParmType *TypeCheck
3592 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3593 assert(!TypeCheck && "Template type parameter canonical type broken")((!TypeCheck && "Template type parameter canonical type broken"
) ? static_cast<void> (0) : __assert_fail ("!TypeCheck && \"Template type parameter canonical type broken\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3593, __PRETTY_FUNCTION__))
;
3594 (void)TypeCheck;
3595 } else
3596 TypeParm = new (*this, TypeAlignment)
3597 TemplateTypeParmType(Depth, Index, ParameterPack);
3598
3599 Types.push_back(TypeParm);
3600 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3601
3602 return QualType(TypeParm, 0);
3603}
3604
3605TypeSourceInfo *
3606ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3607 SourceLocation NameLoc,
3608 const TemplateArgumentListInfo &Args,
3609 QualType Underlying) const {
3610 assert(!Name.getAsDependentTemplateName() &&((!Name.getAsDependentTemplateName() && "No dependent template names here!"
) ? static_cast<void> (0) : __assert_fail ("!Name.getAsDependentTemplateName() && \"No dependent template names here!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3611, __PRETTY_FUNCTION__))
3611 "No dependent template names here!")((!Name.getAsDependentTemplateName() && "No dependent template names here!"
) ? static_cast<void> (0) : __assert_fail ("!Name.getAsDependentTemplateName() && \"No dependent template names here!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3611, __PRETTY_FUNCTION__))
;
3612 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3613
3614 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3615 TemplateSpecializationTypeLoc TL =
3616 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3617 TL.setTemplateKeywordLoc(SourceLocation());
3618 TL.setTemplateNameLoc(NameLoc);
3619 TL.setLAngleLoc(Args.getLAngleLoc());
3620 TL.setRAngleLoc(Args.getRAngleLoc());
3621 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3622 TL.setArgLocInfo(i, Args[i].getLocInfo());
3623 return DI;
3624}
3625
3626QualType
3627ASTContext::getTemplateSpecializationType(TemplateName Template,
3628 const TemplateArgumentListInfo &Args,
3629 QualType Underlying) const {
3630 assert(!Template.getAsDependentTemplateName() &&((!Template.getAsDependentTemplateName() && "No dependent template names here!"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3631, __PRETTY_FUNCTION__))
3631 "No dependent template names here!")((!Template.getAsDependentTemplateName() && "No dependent template names here!"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3631, __PRETTY_FUNCTION__))
;
3632
3633 SmallVector<TemplateArgument, 4> ArgVec;
3634 ArgVec.reserve(Args.size());
3635 for (const TemplateArgumentLoc &Arg : Args.arguments())
3636 ArgVec.push_back(Arg.getArgument());
3637
3638 return getTemplateSpecializationType(Template, ArgVec, Underlying);
3639}
3640
3641#ifndef NDEBUG
3642static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3643 for (const TemplateArgument &Arg : Args)
3644 if (Arg.isPackExpansion())
3645 return true;
3646
3647 return true;
3648}
3649#endif
3650
3651QualType
3652ASTContext::getTemplateSpecializationType(TemplateName Template,
3653 ArrayRef<TemplateArgument> Args,
3654 QualType Underlying) const {
3655 assert(!Template.getAsDependentTemplateName() &&((!Template.getAsDependentTemplateName() && "No dependent template names here!"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3656, __PRETTY_FUNCTION__))
3656 "No dependent template names here!")((!Template.getAsDependentTemplateName() && "No dependent template names here!"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3656, __PRETTY_FUNCTION__))
;
3657 // Look through qualified template names.
3658 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3659 Template = TemplateName(QTN->getTemplateDecl());
3660
3661 bool IsTypeAlias =
3662 Template.getAsTemplateDecl() &&
3663 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3664 QualType CanonType;
3665 if (!Underlying.isNull())
3666 CanonType = getCanonicalType(Underlying);
3667 else {
3668 // We can get here with an alias template when the specialization contains
3669 // a pack expansion that does not match up with a parameter pack.
3670 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&(((!IsTypeAlias || hasAnyPackExpansions(Args)) && "Caller must compute aliased type"
) ? static_cast<void> (0) : __assert_fail ("(!IsTypeAlias || hasAnyPackExpansions(Args)) && \"Caller must compute aliased type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3671, __PRETTY_FUNCTION__))
3671 "Caller must compute aliased type")(((!IsTypeAlias || hasAnyPackExpansions(Args)) && "Caller must compute aliased type"
) ? static_cast<void> (0) : __assert_fail ("(!IsTypeAlias || hasAnyPackExpansions(Args)) && \"Caller must compute aliased type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3671, __PRETTY_FUNCTION__))
;
3672 IsTypeAlias = false;
3673 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
3674 }
3675
3676 // Allocate the (non-canonical) template specialization type, but don't
3677 // try to unique it: these types typically have location information that
3678 // we don't unique and don't want to lose.
3679 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3680 sizeof(TemplateArgument) * Args.size() +
3681 (IsTypeAlias? sizeof(QualType) : 0),
3682 TypeAlignment);
3683 TemplateSpecializationType *Spec
3684 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
3685 IsTypeAlias ? Underlying : QualType());
3686
3687 Types.push_back(Spec);
3688 return QualType(Spec, 0);
3689}
3690
3691QualType ASTContext::getCanonicalTemplateSpecializationType(
3692 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
3693 assert(!Template.getAsDependentTemplateName() &&((!Template.getAsDependentTemplateName() && "No dependent template names here!"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3694, __PRETTY_FUNCTION__))
3694 "No dependent template names here!")((!Template.getAsDependentTemplateName() && "No dependent template names here!"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3694, __PRETTY_FUNCTION__))
;
3695
3696 // Look through qualified template names.
3697 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3698 Template = TemplateName(QTN->getTemplateDecl());
3699
3700 // Build the canonical template specialization type.
3701 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3702 SmallVector<TemplateArgument, 4> CanonArgs;
3703 unsigned NumArgs = Args.size();
3704 CanonArgs.reserve(NumArgs);
3705 for (const TemplateArgument &Arg : Args)
3706 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
3707
3708 // Determine whether this canonical template specialization type already
3709 // exists.
3710 llvm::FoldingSetNodeID ID;
3711 TemplateSpecializationType::Profile(ID, CanonTemplate,
3712 CanonArgs, *this);
3713
3714 void *InsertPos = nullptr;
3715 TemplateSpecializationType *Spec
3716 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3717
3718 if (!Spec) {
3719 // Allocate a new canonical template specialization type.
3720 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3721 sizeof(TemplateArgument) * NumArgs),
3722 TypeAlignment);
3723 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3724 CanonArgs,
3725 QualType(), QualType());
3726 Types.push_back(Spec);
3727 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3728 }
3729
3730 assert(Spec->isDependentType() &&((Spec->isDependentType() && "Non-dependent template-id type must have a canonical type"
) ? static_cast<void> (0) : __assert_fail ("Spec->isDependentType() && \"Non-dependent template-id type must have a canonical type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3731, __PRETTY_FUNCTION__))
3731 "Non-dependent template-id type must have a canonical type")((Spec->isDependentType() && "Non-dependent template-id type must have a canonical type"
) ? static_cast<void> (0) : __assert_fail ("Spec->isDependentType() && \"Non-dependent template-id type must have a canonical type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3731, __PRETTY_FUNCTION__))
;
3732 return QualType(Spec, 0);
3733}
3734
3735QualType
3736ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3737 NestedNameSpecifier *NNS,
3738 QualType NamedType) const {
3739 llvm::FoldingSetNodeID ID;
3740 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3741
3742 void *InsertPos = nullptr;
3743 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3744 if (T)
3745 return QualType(T, 0);
3746
3747 QualType Canon = NamedType;
3748 if (!Canon.isCanonical()) {
3749 Canon = getCanonicalType(NamedType);
3750 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3751 assert(!CheckT && "Elaborated canonical type broken")((!CheckT && "Elaborated canonical type broken") ? static_cast
<void> (0) : __assert_fail ("!CheckT && \"Elaborated canonical type broken\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3751, __PRETTY_FUNCTION__))
;
3752 (void)CheckT;
3753 }
3754
3755 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
3756 Types.push_back(T);
3757 ElaboratedTypes.InsertNode(T, InsertPos);
3758 return QualType(T, 0);
3759}
3760
3761QualType
3762ASTContext::getParenType(QualType InnerType) const {
3763 llvm::FoldingSetNodeID ID;
3764 ParenType::Profile(ID, InnerType);
3765
3766 void *InsertPos = nullptr;
3767 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3768 if (T)
3769 return QualType(T, 0);
3770
3771 QualType Canon = InnerType;
3772 if (!Canon.isCanonical()) {
3773 Canon = getCanonicalType(InnerType);
3774 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3775 assert(!CheckT && "Paren canonical type broken")((!CheckT && "Paren canonical type broken") ? static_cast
<void> (0) : __assert_fail ("!CheckT && \"Paren canonical type broken\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3775, __PRETTY_FUNCTION__))
;
3776 (void)CheckT;
3777 }
3778
3779 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
3780 Types.push_back(T);
3781 ParenTypes.InsertNode(T, InsertPos);
3782 return QualType(T, 0);
3783}
3784
3785QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3786 NestedNameSpecifier *NNS,
3787 const IdentifierInfo *Name,
3788 QualType Canon) const {
3789 if (Canon.isNull()) {
3790 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3791 if (CanonNNS != NNS)
3792 Canon = getDependentNameType(Keyword, CanonNNS, Name);
3793 }
3794
3795 llvm::FoldingSetNodeID ID;
3796 DependentNameType::Profile(ID, Keyword, NNS, Name);
3797
3798 void *InsertPos = nullptr;
3799 DependentNameType *T
3800 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3801 if (T)
3802 return QualType(T, 0);
3803
3804 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
3805 Types.push_back(T);
3806 DependentNameTypes.InsertNode(T, InsertPos);
3807 return QualType(T, 0);
3808}
3809
3810QualType
3811ASTContext::getDependentTemplateSpecializationType(
3812 ElaboratedTypeKeyword Keyword,
3813 NestedNameSpecifier *NNS,
3814 const IdentifierInfo *Name,
3815 const TemplateArgumentListInfo &Args) const {
3816 // TODO: avoid this copy
3817 SmallVector<TemplateArgument, 16> ArgCopy;
3818 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3819 ArgCopy.push_back(Args[I].getArgument());
3820 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
3821}
3822
3823QualType
3824ASTContext::getDependentTemplateSpecializationType(
3825 ElaboratedTypeKeyword Keyword,
3826 NestedNameSpecifier *NNS,
3827 const IdentifierInfo *Name,
3828 ArrayRef<TemplateArgument> Args) const {
3829 assert((!NNS || NNS->isDependent()) &&(((!NNS || NNS->isDependent()) && "nested-name-specifier must be dependent"
) ? static_cast<void> (0) : __assert_fail ("(!NNS || NNS->isDependent()) && \"nested-name-specifier must be dependent\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3830, __PRETTY_FUNCTION__))
3830 "nested-name-specifier must be dependent")(((!NNS || NNS->isDependent()) && "nested-name-specifier must be dependent"
) ? static_cast<void> (0) : __assert_fail ("(!NNS || NNS->isDependent()) && \"nested-name-specifier must be dependent\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3830, __PRETTY_FUNCTION__))
;
3831
3832 llvm::FoldingSetNodeID ID;
3833 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3834 Name, Args);
3835
3836 void *InsertPos = nullptr;
3837 DependentTemplateSpecializationType *T
3838 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3839 if (T)
3840 return QualType(T, 0);
3841
3842 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3843
3844 ElaboratedTypeKeyword CanonKeyword = Keyword;
3845 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3846
3847 bool AnyNonCanonArgs = false;
3848 unsigned NumArgs = Args.size();
3849 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3850 for (unsigned I = 0; I != NumArgs; ++I) {
3851 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3852 if (!CanonArgs[I].structurallyEquals(Args[I]))
3853 AnyNonCanonArgs = true;
3854 }
3855
3856 QualType Canon;
3857 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3858 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3859 Name,
3860 CanonArgs);
3861
3862 // Find the insert position again.
3863 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3864 }
3865
3866 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3867 sizeof(TemplateArgument) * NumArgs),
3868 TypeAlignment);
3869 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3870 Name, Args, Canon);
3871 Types.push_back(T);
3872 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3873 return QualType(T, 0);
3874}
3875
3876TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
3877 TemplateArgument Arg;
3878 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3879 QualType ArgType = getTypeDeclType(TTP);
3880 if (TTP->isParameterPack())
3881 ArgType = getPackExpansionType(ArgType, None);
3882
3883 Arg = TemplateArgument(ArgType);
3884 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3885 Expr *E = new (*this) DeclRefExpr(
3886 NTTP, /*enclosing*/false,
3887 NTTP->getType().getNonLValueExprType(*this),
3888 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
3889
3890 if (NTTP->isParameterPack())
3891 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
3892 None);
3893 Arg = TemplateArgument(E);
3894 } else {
3895 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
3896 if (TTP->isParameterPack())
3897 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
3898 else
3899 Arg = TemplateArgument(TemplateName(TTP));
3900 }
3901
3902 if (Param->isTemplateParameterPack())
3903 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
3904
3905 return Arg;
3906}
3907
3908void
3909ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
3910 SmallVectorImpl<TemplateArgument> &Args) {
3911 Args.reserve(Args.size() + Params->size());
3912
3913 for (NamedDecl *Param : *Params)
3914 Args.push_back(getInjectedTemplateArg(Param));
3915}
3916
3917QualType ASTContext::getPackExpansionType(QualType Pattern,
3918 Optional<unsigned> NumExpansions) {
3919 llvm::FoldingSetNodeID ID;
3920 PackExpansionType::Profile(ID, Pattern, NumExpansions);
3921
3922 assert(Pattern->containsUnexpandedParameterPack() &&((Pattern->containsUnexpandedParameterPack() && "Pack expansions must expand one or more parameter packs"
) ? static_cast<void> (0) : __assert_fail ("Pattern->containsUnexpandedParameterPack() && \"Pack expansions must expand one or more parameter packs\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3923, __PRETTY_FUNCTION__))
3923 "Pack expansions must expand one or more parameter packs")((Pattern->containsUnexpandedParameterPack() && "Pack expansions must expand one or more parameter packs"
) ? static_cast<void> (0) : __assert_fail ("Pattern->containsUnexpandedParameterPack() && \"Pack expansions must expand one or more parameter packs\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 3923, __PRETTY_FUNCTION__))
;
3924 void *InsertPos = nullptr;
3925 PackExpansionType *T
3926 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3927 if (T)
3928 return QualType(T, 0);
3929
3930 QualType Canon;
3931 if (!Pattern.isCanonical()) {
3932 Canon = getCanonicalType(Pattern);
3933 // The canonical type might not contain an unexpanded parameter pack, if it
3934 // contains an alias template specialization which ignores one of its
3935 // parameters.
3936 if (Canon->containsUnexpandedParameterPack()) {
3937 Canon = getPackExpansionType(Canon, NumExpansions);
3938
3939 // Find the insert position again, in case we inserted an element into
3940 // PackExpansionTypes and invalidated our insert position.
3941 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3942 }
3943 }
3944
3945 T = new (*this, TypeAlignment)
3946 PackExpansionType(Pattern, Canon, NumExpansions);
3947 Types.push_back(T);
3948 PackExpansionTypes.InsertNode(T, InsertPos);
3949 return QualType(T, 0);
3950}
3951
3952/// CmpProtocolNames - Comparison predicate for sorting protocols
3953/// alphabetically.
3954static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3955 ObjCProtocolDecl *const *RHS) {
3956 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
3957}
3958
3959static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3960 if (Protocols.empty()) return true;
3961
3962 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3963 return false;
3964
3965 for (unsigned i = 1; i != Protocols.size(); ++i)
3966 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
3967 Protocols[i]->getCanonicalDecl() != Protocols[i])
3968 return false;
3969 return true;
3970}
3971
3972static void
3973SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
3974 // Sort protocols, keyed by name.
3975 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
3976
3977 // Canonicalize.
3978 for (ObjCProtocolDecl *&P : Protocols)
3979 P = P->getCanonicalDecl();
3980
3981 // Remove duplicates.
3982 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3983 Protocols.erase(ProtocolsEnd, Protocols.end());
3984}
3985
3986QualType ASTContext::getObjCObjectType(QualType BaseType,
3987 ObjCProtocolDecl * const *Protocols,
3988 unsigned NumProtocols) const {
3989 return getObjCObjectType(BaseType, { },
3990 llvm::makeArrayRef(Protocols, NumProtocols),
3991 /*isKindOf=*/false);
3992}
3993
3994QualType ASTContext::getObjCObjectType(
3995 QualType baseType,
3996 ArrayRef<QualType> typeArgs,
3997 ArrayRef<ObjCProtocolDecl *> protocols,
3998 bool isKindOf) const {
3999 // If the base type is an interface and there aren't any protocols or
4000 // type arguments to add, then the interface type will do just fine.
4001 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4002 isa<ObjCInterfaceType>(baseType))
4003 return baseType;
4004
4005 // Look in the folding set for an existing type.
4006 llvm::FoldingSetNodeID ID;
4007 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
4008 void *InsertPos = nullptr;
4009 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4010 return QualType(QT, 0);
4011
4012 // Determine the type arguments to be used for canonicalization,
4013 // which may be explicitly specified here or written on the base
4014 // type.
4015 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4016 if (effectiveTypeArgs.empty()) {
4017 if (auto baseObject = baseType->getAs<ObjCObjectType>())
4018 effectiveTypeArgs = baseObject->getTypeArgs();
4019 }
4020
4021 // Build the canonical type, which has the canonical base type and a
4022 // sorted-and-uniqued list of protocols and the type arguments
4023 // canonicalized.
4024 QualType canonical;
4025 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4026 effectiveTypeArgs.end(),
4027 [&](QualType type) {
4028 return type.isCanonical();
4029 });
4030 bool protocolsSorted = areSortedAndUniqued(protocols);
4031 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4032 // Determine the canonical type arguments.
4033 ArrayRef<QualType> canonTypeArgs;
4034 SmallVector<QualType, 4> canonTypeArgsVec;
4035 if (!typeArgsAreCanonical) {
4036 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4037 for (auto typeArg : effectiveTypeArgs)
4038 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4039 canonTypeArgs = canonTypeArgsVec;
4040 } else {
4041 canonTypeArgs = effectiveTypeArgs;
4042 }
4043
4044 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4045 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4046 if (!protocolsSorted) {
4047 canonProtocolsVec.append(protocols.begin(), protocols.end());
4048 SortAndUniqueProtocols(canonProtocolsVec);
4049 canonProtocols = canonProtocolsVec;
4050 } else {
4051 canonProtocols = protocols;
4052 }
4053
4054 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
4055 canonProtocols, isKindOf);
4056
4057 // Regenerate InsertPos.
4058 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4059 }
4060
4061 unsigned size = sizeof(ObjCObjectTypeImpl);
4062 size += typeArgs.size() * sizeof(QualType);
4063 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4064 void *mem = Allocate(size, TypeAlignment);
4065 ObjCObjectTypeImpl *T =
4066 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4067 isKindOf);
4068
4069 Types.push_back(T);
4070 ObjCObjectTypes.InsertNode(T, InsertPos);
4071 return QualType(T, 0);
4072}
4073
4074/// Apply Objective-C protocol qualifiers to the given type.
4075/// If this is for the canonical type of a type parameter, we can apply
4076/// protocol qualifiers on the ObjCObjectPointerType.
4077QualType
4078ASTContext::applyObjCProtocolQualifiers(QualType type,
4079 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4080 bool allowOnPointerType) const {
4081 hasError = false;
4082
4083 if (const ObjCTypeParamType *objT =
4084 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4085 return getObjCTypeParamType(objT->getDecl(), protocols);
4086 }
4087
4088 // Apply protocol qualifiers to ObjCObjectPointerType.
4089 if (allowOnPointerType) {
4090 if (const ObjCObjectPointerType *objPtr =
4091 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4092 const ObjCObjectType *objT = objPtr->getObjectType();
4093 // Merge protocol lists and construct ObjCObjectType.
4094 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4095 protocolsVec.append(objT->qual_begin(),
4096 objT->qual_end());
4097 protocolsVec.append(protocols.begin(), protocols.end());
4098 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4099 type = getObjCObjectType(
4100 objT->getBaseType(),
4101 objT->getTypeArgsAsWritten(),
4102 protocols,
4103 objT->isKindOfTypeAsWritten());
4104 return getObjCObjectPointerType(type);
4105 }
4106 }
4107
4108 // Apply protocol qualifiers to ObjCObjectType.
4109 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4110 // FIXME: Check for protocols to which the class type is already
4111 // known to conform.
4112
4113 return getObjCObjectType(objT->getBaseType(),
4114 objT->getTypeArgsAsWritten(),
4115 protocols,
4116 objT->isKindOfTypeAsWritten());
4117 }
4118
4119 // If the canonical type is ObjCObjectType, ...
4120 if (type->isObjCObjectType()) {
4121 // Silently overwrite any existing protocol qualifiers.
4122 // TODO: determine whether that's the right thing to do.
4123
4124 // FIXME: Check for protocols to which the class type is already
4125 // known to conform.
4126 return getObjCObjectType(type, { }, protocols, false);
4127 }
4128
4129 // id<protocol-list>
4130 if (type->isObjCIdType()) {
4131 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4132 type = getObjCObjectType(ObjCBuiltinIdTy, { }, protocols,
4133 objPtr->isKindOfType());
4134 return getObjCObjectPointerType(type);
4135 }
4136
4137 // Class<protocol-list>
4138 if (type->isObjCClassType()) {
4139 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4140 type = getObjCObjectType(ObjCBuiltinClassTy, { }, protocols,
4141 objPtr->isKindOfType());
4142 return getObjCObjectPointerType(type);
4143 }
4144
4145 hasError = true;
4146 return type;
4147}
4148
4149QualType
4150ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4151 ArrayRef<ObjCProtocolDecl *> protocols,
4152 QualType Canonical) const {
4153 // Look in the folding set for an existing type.
4154 llvm::FoldingSetNodeID ID;
4155 ObjCTypeParamType::Profile(ID, Decl, protocols);
4156 void *InsertPos = nullptr;
4157 if (ObjCTypeParamType *TypeParam =
4158 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4159 return QualType(TypeParam, 0);
4160
4161 if (Canonical.isNull()) {
4162 // We canonicalize to the underlying type.
4163 Canonical = getCanonicalType(Decl->getUnderlyingType());
4164 if (!protocols.empty()) {
4165 // Apply the protocol qualifers.
4166 bool hasError;
4167 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4168 true/*allowOnPointerType*/);
4169 assert(!hasError && "Error when apply protocol qualifier to bound type")((!hasError && "Error when apply protocol qualifier to bound type"
) ? static_cast<void> (0) : __assert_fail ("!hasError && \"Error when apply protocol qualifier to bound type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 4169, __PRETTY_FUNCTION__))
;
4170 }
4171 }
4172
4173 unsigned size = sizeof(ObjCTypeParamType);
4174 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4175 void *mem = Allocate(size, TypeAlignment);
4176 ObjCTypeParamType *newType = new (mem)
4177 ObjCTypeParamType(Decl, Canonical, protocols);
4178
4179 Types.push_back(newType);
4180 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4181 return QualType(newType, 0);
4182}
4183
4184/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4185/// protocol list adopt all protocols in QT's qualified-id protocol
4186/// list.
4187bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4188 ObjCInterfaceDecl *IC) {
4189 if (!QT->isObjCQualifiedIdType())
4190 return false;
4191
4192 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
4193 // If both the right and left sides have qualifiers.
4194 for (auto *Proto : OPT->quals()) {
4195 if (!IC->ClassImplementsProtocol(Proto, false))
4196 return false;
4197 }
4198 return true;
4199 }
4200 return false;
4201}
4202
4203/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4204/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4205/// of protocols.
4206bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4207 ObjCInterfaceDecl *IDecl) {
4208 if (!QT->isObjCQualifiedIdType())
4209 return false;
4210 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
4211 if (!OPT)
4212 return false;
4213 if (!IDecl->hasDefinition())
4214 return false;
4215 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4216 CollectInheritedProtocols(IDecl, InheritedProtocols);
4217 if (InheritedProtocols.empty())
4218 return false;
4219 // Check that if every protocol in list of id<plist> conforms to a protcol
4220 // of IDecl's, then bridge casting is ok.
4221 bool Conforms = false;
4222 for (auto *Proto : OPT->quals()) {
4223 Conforms = false;
4224 for (auto *PI : InheritedProtocols) {
4225 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4226 Conforms = true;
4227 break;
4228 }
4229 }
4230 if (!Conforms)
4231 break;
4232 }
4233 if (Conforms)
4234 return true;
4235
4236 for (auto *PI : InheritedProtocols) {
4237 // If both the right and left sides have qualifiers.
4238 bool Adopts = false;
4239 for (auto *Proto : OPT->quals()) {
4240 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
4241 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
4242 break;
4243 }
4244 if (!Adopts)
4245 return false;
4246 }
4247 return true;
4248}
4249
4250/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4251/// the given object type.
4252QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
4253 llvm::FoldingSetNodeID ID;
4254 ObjCObjectPointerType::Profile(ID, ObjectT);
4255
4256 void *InsertPos = nullptr;
4257 if (ObjCObjectPointerType *QT =
4258 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4259 return QualType(QT, 0);
4260
4261 // Find the canonical object type.
4262 QualType Canonical;
4263 if (!ObjectT.isCanonical()) {
4264 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4265
4266 // Regenerate InsertPos.
4267 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4268 }
4269
4270 // No match.
4271 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4272 ObjCObjectPointerType *QType =
4273 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
4274
4275 Types.push_back(QType);
4276 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
4277 return QualType(QType, 0);
4278}
4279
4280/// getObjCInterfaceType - Return the unique reference to the type for the
4281/// specified ObjC interface decl. The list of protocols is optional.
4282QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4283 ObjCInterfaceDecl *PrevDecl) const {
4284 if (Decl->TypeForDecl)
4285 return QualType(Decl->TypeForDecl, 0);
4286
4287 if (PrevDecl) {
4288 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl")((PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"
) ? static_cast<void> (0) : __assert_fail ("PrevDecl->TypeForDecl && \"previous decl has no TypeForDecl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 4288, __PRETTY_FUNCTION__))
;
4289 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4290 return QualType(PrevDecl->TypeForDecl, 0);
4291 }
4292
4293 // Prefer the definition, if there is one.
4294 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4295 Decl = Def;
4296
4297 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4298 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
4299 Decl->TypeForDecl = T;
4300 Types.push_back(T);
4301 return QualType(T, 0);
4302}
4303
4304/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4305/// TypeOfExprType AST's (since expression's are never shared). For example,
4306/// multiple declarations that refer to "typeof(x)" all contain different
4307/// DeclRefExpr's. This doesn't effect the type checker, since it operates
4308/// on canonical type's (which are always unique).
4309QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
4310 TypeOfExprType *toe;
4311 if (tofExpr->isTypeDependent()) {
4312 llvm::FoldingSetNodeID ID;
4313 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
4314
4315 void *InsertPos = nullptr;
4316 DependentTypeOfExprType *Canon
4317 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4318 if (Canon) {
4319 // We already have a "canonical" version of an identical, dependent
4320 // typeof(expr) type. Use that as our canonical type.
4321 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
4322 QualType((TypeOfExprType*)Canon, 0));
4323 } else {
4324 // Build a new, canonical typeof(expr) type.
4325 Canon
4326 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
4327 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4328 toe = Canon;
4329 }
4330 } else {
4331 QualType Canonical = getCanonicalType(tofExpr->getType());
4332 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
4333 }
4334 Types.push_back(toe);
4335 return QualType(toe, 0);
4336}
4337
4338/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
4339/// TypeOfType nodes. The only motivation to unique these nodes would be
4340/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
4341/// an issue. This doesn't affect the type checker, since it operates
4342/// on canonical types (which are always unique).
4343QualType ASTContext::getTypeOfType(QualType tofType) const {
4344 QualType Canonical = getCanonicalType(tofType);
4345 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
4346 Types.push_back(tot);
4347 return QualType(tot, 0);
4348}
4349
4350/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4351/// nodes. This would never be helpful, since each such type has its own
4352/// expression, and would not give a significant memory saving, since there
4353/// is an Expr tree under each such type.
4354QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
4355 DecltypeType *dt;
4356
4357 // C++11 [temp.type]p2:
4358 // If an expression e involves a template parameter, decltype(e) denotes a
4359 // unique dependent type. Two such decltype-specifiers refer to the same
4360 // type only if their expressions are equivalent (14.5.6.1).
4361 if (e->isInstantiationDependent()) {
4362 llvm::FoldingSetNodeID ID;
4363 DependentDecltypeType::Profile(ID, *this, e);
4364
4365 void *InsertPos = nullptr;
4366 DependentDecltypeType *Canon
4367 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
4368 if (!Canon) {
4369 // Build a new, canonical decltype(expr) type.
4370 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
4371 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
4372 }
4373 dt = new (*this, TypeAlignment)
4374 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
4375 } else {
4376 dt = new (*this, TypeAlignment)
4377 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
4378 }
4379 Types.push_back(dt);
4380 return QualType(dt, 0);
4381}
4382
4383/// getUnaryTransformationType - We don't unique these, since the memory
4384/// savings are minimal and these are rare.
4385QualType ASTContext::getUnaryTransformType(QualType BaseType,
4386 QualType UnderlyingType,
4387 UnaryTransformType::UTTKind Kind)
4388 const {
4389 UnaryTransformType *ut = nullptr;
4390
4391 if (BaseType->isDependentType()) {
4392 // Look in the folding set for an existing type.
4393 llvm::FoldingSetNodeID ID;
4394 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4395
4396 void *InsertPos = nullptr;
4397 DependentUnaryTransformType *Canon
4398 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4399
4400 if (!Canon) {
4401 // Build a new, canonical __underlying_type(type) type.
4402 Canon = new (*this, TypeAlignment)
4403 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4404 Kind);
4405 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4406 }
4407 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4408 QualType(), Kind,
4409 QualType(Canon, 0));
4410 } else {
4411 QualType CanonType = getCanonicalType(UnderlyingType);
4412 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4413 UnderlyingType, Kind,
4414 CanonType);
4415 }
4416 Types.push_back(ut);
4417 return QualType(ut, 0);
4418}
4419
4420/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4421/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4422/// canonical deduced-but-dependent 'auto' type.
4423QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
4424 bool IsDependent) const {
4425 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
4426 return getAutoDeductType();
4427
4428 // Look in the folding set for an existing type.
4429 void *InsertPos = nullptr;
4430 llvm::FoldingSetNodeID ID;
4431 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
4432 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4433 return QualType(AT, 0);
4434
4435 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
4436 Keyword,
4437 IsDependent);
4438 Types.push_back(AT);
4439 if (InsertPos)
4440 AutoTypes.InsertNode(AT, InsertPos);
4441 return QualType(AT, 0);
4442}
4443
4444/// Return the uniqued reference to the deduced template specialization type
4445/// which has been deduced to the given type, or to the canonical undeduced
4446/// such type, or the canonical deduced-but-dependent such type.
4447QualType ASTContext::getDeducedTemplateSpecializationType(
4448 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4449 // Look in the folding set for an existing type.
4450 void *InsertPos = nullptr;
4451 llvm::FoldingSetNodeID ID;
4452 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4453 IsDependent);
4454 if (DeducedTemplateSpecializationType *DTST =
4455 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4456 return QualType(DTST, 0);
4457
4458 DeducedTemplateSpecializationType *DTST = new (*this, TypeAlignment)
4459 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4460 Types.push_back(DTST);
4461 if (InsertPos)
4462 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4463 return QualType(DTST, 0);
4464}
4465
4466/// getAtomicType - Return the uniqued reference to the atomic type for
4467/// the given value type.
4468QualType ASTContext::getAtomicType(QualType T) const {
4469 // Unique pointers, to guarantee there is only one pointer of a particular
4470 // structure.
4471 llvm::FoldingSetNodeID ID;
4472 AtomicType::Profile(ID, T);
4473
4474 void *InsertPos = nullptr;
4475 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4476 return QualType(AT, 0);
4477
4478 // If the atomic value type isn't canonical, this won't be a canonical type
4479 // either, so fill in the canonical type field.
4480 QualType Canonical;
4481 if (!T.isCanonical()) {
4482 Canonical = getAtomicType(getCanonicalType(T));
4483
4484 // Get the new insert position for the node we care about.
4485 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
4486 assert(!NewIP && "Shouldn't be in the map!")((!NewIP && "Shouldn't be in the map!") ? static_cast
<void> (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 4486, __PRETTY_FUNCTION__))
; (void)NewIP;
4487 }
4488 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4489 Types.push_back(New);
4490 AtomicTypes.InsertNode(New, InsertPos);
4491 return QualType(New, 0);
4492}
4493
4494/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4495QualType ASTContext::getAutoDeductType() const {
4496 if (AutoDeductTy.isNull())
4497 AutoDeductTy = QualType(
4498 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
4499 /*dependent*/false),
4500 0);
4501 return AutoDeductTy;
4502}
4503
4504/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4505QualType ASTContext::getAutoRRefDeductType() const {
4506 if (AutoRRefDeductTy.isNull())
4507 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4508 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern")((!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"
) ? static_cast<void> (0) : __assert_fail ("!AutoRRefDeductTy.isNull() && \"can't build 'auto &&' pattern\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 4508, __PRETTY_FUNCTION__))
;
4509 return AutoRRefDeductTy;
4510}
4511
4512/// getTagDeclType - Return the unique reference to the type for the
4513/// specified TagDecl (struct/union/class/enum) decl.
4514QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
4515 assert (Decl)((Decl) ? static_cast<void> (0) : __assert_fail ("Decl"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 4515, __PRETTY_FUNCTION__))
;
4516 // FIXME: What is the design on getTagDeclType when it requires casting
4517 // away const? mutable?
4518 return getTypeDeclType(const_cast<TagDecl*>(Decl));
4519}
4520
4521/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4522/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4523/// needs to agree with the definition in <stddef.h>.
4524CanQualType ASTContext::getSizeType() const {
4525 return getFromTargetType(Target->getSizeType());
4526}
4527
4528/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4529CanQualType ASTContext::getIntMaxType() const {
4530 return getFromTargetType(Target->getIntMaxType());
4531}
4532
4533/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4534CanQualType ASTContext::getUIntMaxType() const {
4535 return getFromTargetType(Target->getUIntMaxType());
4536}
4537
4538/// getSignedWCharType - Return the type of "signed wchar_t".
4539/// Used when in C++, as a GCC extension.
4540QualType ASTContext::getSignedWCharType() const {
4541 // FIXME: derive from "Target" ?
4542 return WCharTy;
4543}
4544
4545/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4546/// Used when in C++, as a GCC extension.
4547QualType ASTContext::getUnsignedWCharType() const {
4548 // FIXME: derive from "Target" ?
4549 return UnsignedIntTy;
4550}
4551
4552QualType ASTContext::getIntPtrType() const {
4553 return getFromTargetType(Target->getIntPtrType());
4554}
4555
4556QualType ASTContext::getUIntPtrType() const {
4557 return getCorrespondingUnsignedType(getIntPtrType());
4558}
4559
4560/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
4561/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4562QualType ASTContext::getPointerDiffType() const {
4563 return getFromTargetType(Target->getPtrDiffType(0));
4564}
4565
4566/// \brief Return the unique type for "pid_t" defined in
4567/// <sys/types.h>. We need this to compute the correct type for vfork().
4568QualType ASTContext::getProcessIDType() const {
4569 return getFromTargetType(Target->getProcessIDType());
4570}
4571
4572//===----------------------------------------------------------------------===//
4573// Type Operators
4574//===----------------------------------------------------------------------===//
4575
4576CanQualType ASTContext::getCanonicalParamType(QualType T) const {
4577 // Push qualifiers into arrays, and then discard any remaining
4578 // qualifiers.
4579 T = getCanonicalType(T);
4580 T = getVariableArrayDecayedType(T);
4581 const Type *Ty = T.getTypePtr();
4582 QualType Result;
4583 if (isa<ArrayType>(Ty)) {
4584 Result = getArrayDecayedType(QualType(Ty,0));
4585 } else if (isa<FunctionType>(Ty)) {
4586 Result = getPointerType(QualType(Ty, 0));
4587 } else {
4588 Result = QualType(Ty, 0);
4589 }
4590
4591 return CanQualType::CreateUnsafe(Result);
4592}
4593
4594QualType ASTContext::getUnqualifiedArrayType(QualType type,
4595 Qualifiers &quals) {
4596 SplitQualType splitType = type.getSplitUnqualifiedType();
4597
4598 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4599 // the unqualified desugared type and then drops it on the floor.
4600 // We then have to strip that sugar back off with
4601 // getUnqualifiedDesugaredType(), which is silly.
4602 const ArrayType *AT =
4603 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
4604
4605 // If we don't have an array, just use the results in splitType.
4606 if (!AT) {
4607 quals = splitType.Quals;
4608 return QualType(splitType.Ty, 0);
4609 }
4610
4611 // Otherwise, recurse on the array's element type.
4612 QualType elementType = AT->getElementType();
4613 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4614
4615 // If that didn't change the element type, AT has no qualifiers, so we
4616 // can just use the results in splitType.
4617 if (elementType == unqualElementType) {
4618 assert(quals.empty())((quals.empty()) ? static_cast<void> (0) : __assert_fail
("quals.empty()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 4618, __PRETTY_FUNCTION__))
; // from the recursive call
4619 quals = splitType.Quals;
4620 return QualType(splitType.Ty, 0);
4621 }
4622
4623 // Otherwise, add in the qualifiers from the outermost type, then
4624 // build the type back up.
4625 quals.addConsistentQualifiers(splitType.Quals);
4626
4627 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4628 return getConstantArrayType(unqualElementType, CAT->getSize(),
4629 CAT->getSizeModifier(), 0);
4630 }
4631
4632 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
4633 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
4634 }
4635
4636 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
4637 return getVariableArrayType(unqualElementType,
4638 VAT->getSizeExpr(),
4639 VAT->getSizeModifier(),
4640 VAT->getIndexTypeCVRQualifiers(),
4641 VAT->getBracketsRange());
4642 }
4643
4644 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
4645 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
4646 DSAT->getSizeModifier(), 0,
4647 SourceRange());
4648}
4649
4650/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4651/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4652/// they point to and return true. If T1 and T2 aren't pointer types
4653/// or pointer-to-member types, or if they are not similar at this
4654/// level, returns false and leaves T1 and T2 unchanged. Top-level
4655/// qualifiers on T1 and T2 are ignored. This function will typically
4656/// be called in a loop that successively "unwraps" pointer and
4657/// pointer-to-member types to compare them at each level.
4658bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4659 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4660 *T2PtrType = T2->getAs<PointerType>();
4661 if (T1PtrType && T2PtrType) {
4662 T1 = T1PtrType->getPointeeType();
4663 T2 = T2PtrType->getPointeeType();
4664 return true;
4665 }
4666
4667 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4668 *T2MPType = T2->getAs<MemberPointerType>();
4669 if (T1MPType && T2MPType &&
4670 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4671 QualType(T2MPType->getClass(), 0))) {
4672 T1 = T1MPType->getPointeeType();
4673 T2 = T2MPType->getPointeeType();
4674 return true;
4675 }
4676
4677 if (getLangOpts().ObjC1) {
4678 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4679 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4680 if (T1OPType && T2OPType) {
4681 T1 = T1OPType->getPointeeType();
4682 T2 = T2OPType->getPointeeType();
4683 return true;
4684 }
4685 }
4686
4687 // FIXME: Block pointers, too?
4688
4689 return false;
4690}
4691
4692DeclarationNameInfo
4693ASTContext::getNameForTemplate(TemplateName Name,
4694 SourceLocation NameLoc) const {
4695 switch (Name.getKind()) {
4696 case TemplateName::QualifiedTemplate:
4697 case TemplateName::Template:
4698 // DNInfo work in progress: CHECKME: what about DNLoc?
4699 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4700 NameLoc);
4701
4702 case TemplateName::OverloadedTemplate: {
4703 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4704 // DNInfo work in progress: CHECKME: what about DNLoc?
4705 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4706 }
4707
4708 case TemplateName::DependentTemplate: {
4709 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4710 DeclarationName DName;
4711 if (DTN->isIdentifier()) {
4712 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4713 return DeclarationNameInfo(DName, NameLoc);
4714 } else {
4715 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4716 // DNInfo work in progress: FIXME: source locations?
4717 DeclarationNameLoc DNLoc;
4718 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4719 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4720 return DeclarationNameInfo(DName, NameLoc, DNLoc);
4721 }
4722 }
4723
4724 case TemplateName::SubstTemplateTemplateParm: {
4725 SubstTemplateTemplateParmStorage *subst
4726 = Name.getAsSubstTemplateTemplateParm();
4727 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4728 NameLoc);
4729 }
4730
4731 case TemplateName::SubstTemplateTemplateParmPack: {
4732 SubstTemplateTemplateParmPackStorage *subst
4733 = Name.getAsSubstTemplateTemplateParmPack();
4734 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4735 NameLoc);
4736 }
4737 }
4738
4739 llvm_unreachable("bad template name kind!")::llvm::llvm_unreachable_internal("bad template name kind!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 4739)
;
4740}
4741
4742TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
4743 switch (Name.getKind()) {
4744 case TemplateName::QualifiedTemplate:
4745 case TemplateName::Template: {
4746 TemplateDecl *Template = Name.getAsTemplateDecl();
4747 if (TemplateTemplateParmDecl *TTP
4748 = dyn_cast<TemplateTemplateParmDecl>(Template))
4749 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4750
4751 // The canonical template name is the canonical template declaration.
4752 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
4753 }
4754
4755 case TemplateName::OverloadedTemplate:
4756 llvm_unreachable("cannot canonicalize overloaded template")::llvm::llvm_unreachable_internal("cannot canonicalize overloaded template"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 4756)
;
4757
4758 case TemplateName::DependentTemplate: {
4759 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4760 assert(DTN && "Non-dependent template names must refer to template decls.")((DTN && "Non-dependent template names must refer to template decls."
) ? static_cast<void> (0) : __assert_fail ("DTN && \"Non-dependent template names must refer to template decls.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 4760, __PRETTY_FUNCTION__))
;
4761 return DTN->CanonicalTemplateName;
4762 }
4763
4764 case TemplateName::SubstTemplateTemplateParm: {
4765 SubstTemplateTemplateParmStorage *subst
4766 = Name.getAsSubstTemplateTemplateParm();
4767 return getCanonicalTemplateName(subst->getReplacement());
4768 }
4769
4770 case TemplateName::SubstTemplateTemplateParmPack: {
4771 SubstTemplateTemplateParmPackStorage *subst
4772 = Name.getAsSubstTemplateTemplateParmPack();
4773 TemplateTemplateParmDecl *canonParameter
4774 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4775 TemplateArgument canonArgPack
4776 = getCanonicalTemplateArgument(subst->getArgumentPack());
4777 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4778 }
4779 }
4780
4781 llvm_unreachable("bad template name!")::llvm::llvm_unreachable_internal("bad template name!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 4781)
;
4782}
4783
4784bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4785 X = getCanonicalTemplateName(X);
4786 Y = getCanonicalTemplateName(Y);
4787 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4788}
4789
4790TemplateArgument
4791ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4792 switch (Arg.getKind()) {
4793 case TemplateArgument::Null:
4794 return Arg;
4795
4796 case TemplateArgument::Expression:
4797 return Arg;
4798
4799 case TemplateArgument::Declaration: {
4800 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4801 return TemplateArgument(D, Arg.getParamTypeForDecl());
4802 }
4803
4804 case TemplateArgument::NullPtr:
4805 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4806 /*isNullPtr*/true);
4807
4808 case TemplateArgument::Template:
4809 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4810
4811 case TemplateArgument::TemplateExpansion:
4812 return TemplateArgument(getCanonicalTemplateName(
4813 Arg.getAsTemplateOrTemplatePattern()),
4814 Arg.getNumTemplateExpansions());
4815
4816 case TemplateArgument::Integral:
4817 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4818
4819 case TemplateArgument::Type:
4820 return TemplateArgument(getCanonicalType(Arg.getAsType()));
4821
4822 case TemplateArgument::Pack: {
4823 if (Arg.pack_size() == 0)
4824 return Arg;
4825
4826 TemplateArgument *CanonArgs
4827 = new (*this) TemplateArgument[Arg.pack_size()];
4828 unsigned Idx = 0;
4829 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4830 AEnd = Arg.pack_end();
4831 A != AEnd; (void)++A, ++Idx)
4832 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4833
4834 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
4835 }
4836 }
4837
4838 // Silence GCC warning
4839 llvm_unreachable("Unhandled template argument kind")::llvm::llvm_unreachable_internal("Unhandled template argument kind"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 4839)
;
4840}
4841
4842NestedNameSpecifier *
4843ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4844 if (!NNS)
4845 return nullptr;
4846
4847 switch (NNS->getKind()) {
4848 case NestedNameSpecifier::Identifier:
4849 // Canonicalize the prefix but keep the identifier the same.
4850 return NestedNameSpecifier::Create(*this,
4851 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4852 NNS->getAsIdentifier());
4853
4854 case NestedNameSpecifier::Namespace:
4855 // A namespace is canonical; build a nested-name-specifier with
4856 // this namespace and no prefix.
4857 return NestedNameSpecifier::Create(*this, nullptr,
4858 NNS->getAsNamespace()->getOriginalNamespace());
4859
4860 case NestedNameSpecifier::NamespaceAlias:
4861 // A namespace is canonical; build a nested-name-specifier with
4862 // this namespace and no prefix.
4863 return NestedNameSpecifier::Create(*this, nullptr,
4864 NNS->getAsNamespaceAlias()->getNamespace()
4865 ->getOriginalNamespace());
4866
4867 case NestedNameSpecifier::TypeSpec:
4868 case NestedNameSpecifier::TypeSpecWithTemplate: {
4869 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4870
4871 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4872 // break it apart into its prefix and identifier, then reconsititute those
4873 // as the canonical nested-name-specifier. This is required to canonicalize
4874 // a dependent nested-name-specifier involving typedefs of dependent-name
4875 // types, e.g.,
4876 // typedef typename T::type T1;
4877 // typedef typename T1::type T2;
4878 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4879 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4880 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4881
4882 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4883 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4884 // first place?
4885 return NestedNameSpecifier::Create(*this, nullptr, false,
4886 const_cast<Type *>(T.getTypePtr()));
4887 }
4888
4889 case NestedNameSpecifier::Global:
4890 case NestedNameSpecifier::Super:
4891 // The global specifier and __super specifer are canonical and unique.
4892 return NNS;
4893 }
4894
4895 llvm_unreachable("Invalid NestedNameSpecifier::Kind!")::llvm::llvm_unreachable_internal("Invalid NestedNameSpecifier::Kind!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 4895)
;
4896}
4897
4898const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4899 // Handle the non-qualified case efficiently.
4900 if (!T.hasLocalQualifiers()) {
4901 // Handle the common positive case fast.
4902 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4903 return AT;
4904 }
4905
4906 // Handle the common negative case fast.
4907 if (!isa<ArrayType>(T.getCanonicalType()))
4908 return nullptr;
4909
4910 // Apply any qualifiers from the array type to the element type. This
4911 // implements C99 6.7.3p8: "If the specification of an array type includes
4912 // any type qualifiers, the element type is so qualified, not the array type."
4913
4914 // If we get here, we either have type qualifiers on the type, or we have
4915 // sugar such as a typedef in the way. If we have type qualifiers on the type
4916 // we must propagate them down into the element type.
4917
4918 SplitQualType split = T.getSplitDesugaredType();
4919 Qualifiers qs = split.Quals;
4920
4921 // If we have a simple case, just return now.
4922 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4923 if (!ATy || qs.empty())
4924 return ATy;
4925
4926 // Otherwise, we have an array and we have qualifiers on it. Push the
4927 // qualifiers into the array element type and return a new array type.
4928 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4929
4930 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4931 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4932 CAT->getSizeModifier(),
4933 CAT->getIndexTypeCVRQualifiers()));
4934 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4935 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4936 IAT->getSizeModifier(),
4937 IAT->getIndexTypeCVRQualifiers()));
4938
4939 if (const DependentSizedArrayType *DSAT
4940 = dyn_cast<DependentSizedArrayType>(ATy))
4941 return cast<ArrayType>(
4942 getDependentSizedArrayType(NewEltTy,
4943 DSAT->getSizeExpr(),
4944 DSAT->getSizeModifier(),
4945 DSAT->getIndexTypeCVRQualifiers(),
4946 DSAT->getBracketsRange()));
4947
4948 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4949 return cast<ArrayType>(getVariableArrayType(NewEltTy,
4950 VAT->getSizeExpr(),
4951 VAT->getSizeModifier(),
4952 VAT->getIndexTypeCVRQualifiers(),
4953 VAT->getBracketsRange()));
4954}
4955
4956QualType ASTContext::getAdjustedParameterType(QualType T) const {
4957 if (T->isArrayType() || T->isFunctionType())
4958 return getDecayedType(T);
4959 return T;
4960}
4961
4962QualType ASTContext::getSignatureParameterType(QualType T) const {
4963 T = getVariableArrayDecayedType(T);
4964 T = getAdjustedParameterType(T);
4965 return T.getUnqualifiedType();
4966}
4967
4968QualType ASTContext::getExceptionObjectType(QualType T) const {
4969 // C++ [except.throw]p3:
4970 // A throw-expression initializes a temporary object, called the exception
4971 // object, the type of which is determined by removing any top-level
4972 // cv-qualifiers from the static type of the operand of throw and adjusting
4973 // the type from "array of T" or "function returning T" to "pointer to T"
4974 // or "pointer to function returning T", [...]
4975 T = getVariableArrayDecayedType(T);
4976 if (T->isArrayType() || T->isFunctionType())
4977 T = getDecayedType(T);
4978 return T.getUnqualifiedType();
4979}
4980
4981/// getArrayDecayedType - Return the properly qualified result of decaying the
4982/// specified array type to a pointer. This operation is non-trivial when
4983/// handling typedefs etc. The canonical type of "T" must be an array type,
4984/// this returns a pointer to a properly qualified element of the array.
4985///
4986/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
4987QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4988 // Get the element type with 'getAsArrayType' so that we don't lose any
4989 // typedefs in the element type of the array. This also handles propagation
4990 // of type qualifiers from the array type into the element type if present
4991 // (C99 6.7.3p8).
4992 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4993 assert(PrettyArrayType && "Not an array type!")((PrettyArrayType && "Not an array type!") ? static_cast
<void> (0) : __assert_fail ("PrettyArrayType && \"Not an array type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 4993, __PRETTY_FUNCTION__))
;
4994
4995 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4996
4997 // int x[restrict 4] -> int *restrict
4998 QualType Result = getQualifiedType(PtrTy,
4999 PrettyArrayType->getIndexTypeQualifiers());
5000
5001 // int x[_Nullable] -> int * _Nullable
5002 if (auto Nullability = Ty->getNullability(*this)) {
5003 Result = const_cast<ASTContext *>(this)->getAttributedType(
5004 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5005 }
5006 return Result;
5007}
5008
5009QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5010 return getBaseElementType(array->getElementType());
5011}
5012
5013QualType ASTContext::getBaseElementType(QualType type) const {
5014 Qualifiers qs;
5015 while (true) {
5016 SplitQualType split = type.getSplitDesugaredType();
5017 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
5018 if (!array) break;
5019
5020 type = array->getElementType();
5021 qs.addConsistentQualifiers(split.Quals);
5022 }
5023
5024 return getQualifiedType(type, qs);
5025}
5026
5027/// getConstantArrayElementCount - Returns number of constant array elements.
5028uint64_t
5029ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5030 uint64_t ElementCount = 1;
5031 do {
5032 ElementCount *= CA->getSize().getZExtValue();
5033 CA = dyn_cast_or_null<ConstantArrayType>(
5034 CA->getElementType()->getAsArrayTypeUnsafe());
5035 } while (CA);
5036 return ElementCount;
5037}
5038
5039/// getFloatingRank - Return a relative rank for floating point types.
5040/// This routine will assert if passed a built-in type that isn't a float.
5041static FloatingRank getFloatingRank(QualType T) {
5042 if (const ComplexType *CT = T->getAs<ComplexType>())
5043 return getFloatingRank(CT->getElementType());
5044
5045 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type")((T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"
) ? static_cast<void> (0) : __assert_fail ("T->getAs<BuiltinType>() && \"getFloatingRank(): not a floating type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5045, __PRETTY_FUNCTION__))
;
5046 switch (T->getAs<BuiltinType>()->getKind()) {
5047 default: llvm_unreachable("getFloatingRank(): not a floating type")::llvm::llvm_unreachable_internal("getFloatingRank(): not a floating type"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5047)
;
5048 case BuiltinType::Half: return HalfRank;
5049 case BuiltinType::Float: return FloatRank;
5050 case BuiltinType::Double: return DoubleRank;
5051 case BuiltinType::LongDouble: return LongDoubleRank;
5052 case BuiltinType::Float128: return Float128Rank;
5053 }
5054}
5055
5056/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5057/// point or a complex type (based on typeDomain/typeSize).
5058/// 'typeDomain' is a real floating point or complex type.
5059/// 'typeSize' is a real floating point or complex type.
5060QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5061 QualType Domain) const {
5062 FloatingRank EltRank = getFloatingRank(Size);
5063 if (Domain->isComplexType()) {
5064 switch (EltRank) {
5065 case HalfRank: llvm_unreachable("Complex half is not supported")::llvm::llvm_unreachable_internal("Complex half is not supported"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5065)
;
5066 case FloatRank: return FloatComplexTy;
5067 case DoubleRank: return DoubleComplexTy;
5068 case LongDoubleRank: return LongDoubleComplexTy;
5069 case Float128Rank: return Float128ComplexTy;
5070 }
5071 }
5072
5073 assert(Domain->isRealFloatingType() && "Unknown domain!")((Domain->isRealFloatingType() && "Unknown domain!"
) ? static_cast<void> (0) : __assert_fail ("Domain->isRealFloatingType() && \"Unknown domain!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5073, __PRETTY_FUNCTION__))
;
5074 switch (EltRank) {
5075 case HalfRank: return HalfTy;
5076 case FloatRank: return FloatTy;
5077 case DoubleRank: return DoubleTy;
5078 case LongDoubleRank: return LongDoubleTy;
5079 case Float128Rank: return Float128Ty;
5080 }
5081 llvm_unreachable("getFloatingRank(): illegal value for rank")::llvm::llvm_unreachable_internal("getFloatingRank(): illegal value for rank"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5081)
;
5082}
5083
5084/// getFloatingTypeOrder - Compare the rank of the two specified floating
5085/// point types, ignoring the domain of the type (i.e. 'double' ==
5086/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
5087/// LHS < RHS, return -1.
5088int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
5089 FloatingRank LHSR = getFloatingRank(LHS);
5090 FloatingRank RHSR = getFloatingRank(RHS);
5091
5092 if (LHSR == RHSR)
5093 return 0;
5094 if (LHSR > RHSR)
5095 return 1;
5096 return -1;
5097}
5098
5099/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5100/// routine will assert if passed a built-in type that isn't an integer or enum,
5101/// or if it is not canonicalized.
5102unsigned ASTContext::getIntegerRank(const Type *T) const {
5103 assert(T->isCanonicalUnqualified() && "T should be canonicalized")((T->isCanonicalUnqualified() && "T should be canonicalized"
) ? static_cast<void> (0) : __assert_fail ("T->isCanonicalUnqualified() && \"T should be canonicalized\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5103, __PRETTY_FUNCTION__))
;
5104
5105 switch (cast<BuiltinType>(T)->getKind()) {
5106 default: llvm_unreachable("getIntegerRank(): not a built-in integer")::llvm::llvm_unreachable_internal("getIntegerRank(): not a built-in integer"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5106)
;
5107 case BuiltinType::Bool:
5108 return 1 + (getIntWidth(BoolTy) << 3);
5109 case BuiltinType::Char_S:
5110 case BuiltinType::Char_U:
5111 case BuiltinType::SChar:
5112 case BuiltinType::UChar:
5113 return 2 + (getIntWidth(CharTy) << 3);
5114 case BuiltinType::Short:
5115 case BuiltinType::UShort:
5116 return 3 + (getIntWidth(ShortTy) << 3);
5117 case BuiltinType::Int:
5118 case BuiltinType::UInt:
5119 return 4 + (getIntWidth(IntTy) << 3);
5120 case BuiltinType::Long:
5121 case BuiltinType::ULong:
5122 return 5 + (getIntWidth(LongTy) << 3);
5123 case BuiltinType::LongLong:
5124 case BuiltinType::ULongLong:
5125 return 6 + (getIntWidth(LongLongTy) << 3);
5126 case BuiltinType::Int128:
5127 case BuiltinType::UInt128:
5128 return 7 + (getIntWidth(Int128Ty) << 3);
5129 }
5130}
5131
5132/// \brief Whether this is a promotable bitfield reference according
5133/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5134///
5135/// \returns the type this bit-field will promote to, or NULL if no
5136/// promotion occurs.
5137QualType ASTContext::isPromotableBitField(Expr *E) const {
5138 if (E->isTypeDependent() || E->isValueDependent())
5139 return QualType();
5140
5141 // FIXME: We should not do this unless E->refersToBitField() is true. This
5142 // matters in C where getSourceBitField() will find bit-fields for various
5143 // cases where the source expression is not a bit-field designator.
5144
5145 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
5146 if (!Field)
5147 return QualType();
5148
5149 QualType FT = Field->getType();
5150
5151 uint64_t BitWidth = Field->getBitWidthValue(*this);
5152 uint64_t IntSize = getTypeSize(IntTy);
5153 // C++ [conv.prom]p5:
5154 // A prvalue for an integral bit-field can be converted to a prvalue of type
5155 // int if int can represent all the values of the bit-field; otherwise, it
5156 // can be converted to unsigned int if unsigned int can represent all the
5157 // values of the bit-field. If the bit-field is larger yet, no integral
5158 // promotion applies to it.
5159 // C11 6.3.1.1/2:
5160 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5161 // If an int can represent all values of the original type (as restricted by
5162 // the width, for a bit-field), the value is converted to an int; otherwise,
5163 // it is converted to an unsigned int.
5164 //
5165 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5166 // We perform that promotion here to match GCC and C++.
5167 if (BitWidth < IntSize)
5168 return IntTy;
5169
5170 if (BitWidth == IntSize)
5171 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5172
5173 // Types bigger than int are not subject to promotions, and therefore act
5174 // like the base type. GCC has some weird bugs in this area that we
5175 // deliberately do not follow (GCC follows a pre-standard resolution to
5176 // C's DR315 which treats bit-width as being part of the type, and this leaks
5177 // into their semantics in some cases).
5178 return QualType();
5179}
5180
5181/// getPromotedIntegerType - Returns the type that Promotable will
5182/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5183/// integer type.
5184QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
5185 assert(!Promotable.isNull())((!Promotable.isNull()) ? static_cast<void> (0) : __assert_fail
("!Promotable.isNull()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5185, __PRETTY_FUNCTION__))
;
5186 assert(Promotable->isPromotableIntegerType())((Promotable->isPromotableIntegerType()) ? static_cast<
void> (0) : __assert_fail ("Promotable->isPromotableIntegerType()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5186, __PRETTY_FUNCTION__))
;
5187 if (const EnumType *ET = Promotable->getAs<EnumType>())
5188 return ET->getDecl()->getPromotionType();
5189
5190 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
5191 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5192 // (3.9.1) can be converted to a prvalue of the first of the following
5193 // types that can represent all the values of its underlying type:
5194 // int, unsigned int, long int, unsigned long int, long long int, or
5195 // unsigned long long int [...]
5196 // FIXME: Is there some better way to compute this?
5197 if (BT->getKind() == BuiltinType::WChar_S ||
5198 BT->getKind() == BuiltinType::WChar_U ||
5199 BT->getKind() == BuiltinType::Char16 ||
5200 BT->getKind() == BuiltinType::Char32) {
5201 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5202 uint64_t FromSize = getTypeSize(BT);
5203 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5204 LongLongTy, UnsignedLongLongTy };
5205 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5206 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5207 if (FromSize < ToSize ||
5208 (FromSize == ToSize &&
5209 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5210 return PromoteTypes[Idx];
5211 }
5212 llvm_unreachable("char type should fit into long long")::llvm::llvm_unreachable_internal("char type should fit into long long"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5212)
;
5213 }
5214 }
5215
5216 // At this point, we should have a signed or unsigned integer type.
5217 if (Promotable->isSignedIntegerType())
5218 return IntTy;
5219 uint64_t PromotableSize = getIntWidth(Promotable);
5220 uint64_t IntSize = getIntWidth(IntTy);
5221 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize)((Promotable->isUnsignedIntegerType() && PromotableSize
<= IntSize) ? static_cast<void> (0) : __assert_fail
("Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5221, __PRETTY_FUNCTION__))
;
5222 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5223}
5224
5225/// \brief Recurses in pointer/array types until it finds an objc retainable
5226/// type and returns its ownership.
5227Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5228 while (!T.isNull()) {
5229 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5230 return T.getObjCLifetime();
5231 if (T->isArrayType())
5232 T = getBaseElementType(T);
5233 else if (const PointerType *PT = T->getAs<PointerType>())
5234 T = PT->getPointeeType();
5235 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
5236 T = RT->getPointeeType();
5237 else
5238 break;
5239 }
5240
5241 return Qualifiers::OCL_None;
5242}
5243
5244static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5245 // Incomplete enum types are not treated as integer types.
5246 // FIXME: In C++, enum types are never integer types.
5247 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5248 return ET->getDecl()->getIntegerType().getTypePtr();
5249 return nullptr;
5250}
5251
5252/// getIntegerTypeOrder - Returns the highest ranked integer type:
5253/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
5254/// LHS < RHS, return -1.
5255int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
5256 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5257 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
5258
5259 // Unwrap enums to their underlying type.
5260 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
5261 LHSC = getIntegerTypeForEnum(ET);
5262 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
5263 RHSC = getIntegerTypeForEnum(ET);
5264
5265 if (LHSC == RHSC) return 0;
5266
5267 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5268 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
5269
5270 unsigned LHSRank = getIntegerRank(LHSC);
5271 unsigned RHSRank = getIntegerRank(RHSC);
5272
5273 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5274 if (LHSRank == RHSRank) return 0;
5275 return LHSRank > RHSRank ? 1 : -1;
5276 }
5277
5278 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5279 if (LHSUnsigned) {
5280 // If the unsigned [LHS] type is larger, return it.
5281 if (LHSRank >= RHSRank)
5282 return 1;
5283
5284 // If the signed type can represent all values of the unsigned type, it
5285 // wins. Because we are dealing with 2's complement and types that are
5286 // powers of two larger than each other, this is always safe.
5287 return -1;
5288 }
5289
5290 // If the unsigned [RHS] type is larger, return it.
5291 if (RHSRank >= LHSRank)
5292 return -1;
5293
5294 // If the signed type can represent all values of the unsigned type, it
5295 // wins. Because we are dealing with 2's complement and types that are
5296 // powers of two larger than each other, this is always safe.
5297 return 1;
5298}
5299
5300TypedefDecl *ASTContext::getCFConstantStringDecl() const {
5301 if (!CFConstantStringTypeDecl) {
5302 assert(!CFConstantStringTagDecl &&((!CFConstantStringTagDecl && "tag and typedef should be initialized together"
) ? static_cast<void> (0) : __assert_fail ("!CFConstantStringTagDecl && \"tag and typedef should be initialized together\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5303, __PRETTY_FUNCTION__))
5303 "tag and typedef should be initialized together")((!CFConstantStringTagDecl && "tag and typedef should be initialized together"
) ? static_cast<void> (0) : __assert_fail ("!CFConstantStringTagDecl && \"tag and typedef should be initialized together\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5303, __PRETTY_FUNCTION__))
;
5304 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5305 CFConstantStringTagDecl->startDefinition();
5306
5307 QualType FieldTypes[4];
5308 const char *FieldNames[4];
5309
5310 // const int *isa;
5311 FieldTypes[0] = getPointerType(IntTy.withConst());
5312 FieldNames[0] = "isa";
5313 // int flags;
5314 FieldTypes[1] = IntTy;
5315 FieldNames[1] = "flags";
5316 // const char *str;
5317 FieldTypes[2] = getPointerType(CharTy.withConst());
5318 FieldNames[2] = "str";
5319 // long length;
5320 FieldTypes[3] = LongTy;
5321 FieldNames[3] = "length";
5322
5323 // Create fields
5324 for (unsigned i = 0; i < 4; ++i) {
5325 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
5326 SourceLocation(),
5327 SourceLocation(),
5328 &Idents.get(FieldNames[i]),
5329 FieldTypes[i], /*TInfo=*/nullptr,
5330 /*BitWidth=*/nullptr,
5331 /*Mutable=*/false,
5332 ICIS_NoInit);
5333 Field->setAccess(AS_public);
5334 CFConstantStringTagDecl->addDecl(Field);
5335 }
5336
5337 CFConstantStringTagDecl->completeDefinition();
5338 // This type is designed to be compatible with NSConstantString, but cannot
5339 // use the same name, since NSConstantString is an interface.
5340 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5341 CFConstantStringTypeDecl =
5342 buildImplicitTypedef(tagType, "__NSConstantString");
5343 }
5344
5345 return CFConstantStringTypeDecl;
5346}
5347
5348RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5349 if (!CFConstantStringTagDecl)
5350 getCFConstantStringDecl(); // Build the tag and the typedef.
5351 return CFConstantStringTagDecl;
5352}
5353
5354// getCFConstantStringType - Return the type used for constant CFStrings.
5355QualType ASTContext::getCFConstantStringType() const {
5356 return getTypedefType(getCFConstantStringDecl());
5357}
5358
5359QualType ASTContext::getObjCSuperType() const {
5360 if (ObjCSuperType.isNull()) {
5361 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
5362 TUDecl->addDecl(ObjCSuperTypeDecl);
5363 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5364 }
5365 return ObjCSuperType;
5366}
5367
5368void ASTContext::setCFConstantStringType(QualType T) {
5369 const TypedefType *TD = T->getAs<TypedefType>();
5370 assert(TD && "Invalid CFConstantStringType")((TD && "Invalid CFConstantStringType") ? static_cast
<void> (0) : __assert_fail ("TD && \"Invalid CFConstantStringType\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5370, __PRETTY_FUNCTION__))
;
5371 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5372 auto TagType =
5373 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5374 assert(TagType && "Invalid CFConstantStringType")((TagType && "Invalid CFConstantStringType") ? static_cast
<void> (0) : __assert_fail ("TagType && \"Invalid CFConstantStringType\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5374, __PRETTY_FUNCTION__))
;
5375 CFConstantStringTagDecl = TagType->getDecl();
5376}
5377
5378QualType ASTContext::getBlockDescriptorType() const {
5379 if (BlockDescriptorType)
5380 return getTagDeclType(BlockDescriptorType);
5381
5382 RecordDecl *RD;
5383 // FIXME: Needs the FlagAppleBlock bit.
5384 RD = buildImplicitRecord("__block_descriptor");
5385 RD->startDefinition();
5386
5387 QualType FieldTypes[] = {
5388 UnsignedLongTy,
5389 UnsignedLongTy,
5390 };
5391
5392 static const char *const FieldNames[] = {
5393 "reserved",
5394 "Size"
5395 };
5396
5397 for (size_t i = 0; i < 2; ++i) {
5398 FieldDecl *Field = FieldDecl::Create(
5399 *this, RD, SourceLocation(), SourceLocation(),
5400 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5401 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
5402 Field->setAccess(AS_public);
5403 RD->addDecl(Field);
5404 }
5405
5406 RD->completeDefinition();
5407
5408 BlockDescriptorType = RD;
5409
5410 return getTagDeclType(BlockDescriptorType);
5411}
5412
5413QualType ASTContext::getBlockDescriptorExtendedType() const {
5414 if (BlockDescriptorExtendedType)
5415 return getTagDeclType(BlockDescriptorExtendedType);
5416
5417 RecordDecl *RD;
5418 // FIXME: Needs the FlagAppleBlock bit.
5419 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5420 RD->startDefinition();
5421
5422 QualType FieldTypes[] = {
5423 UnsignedLongTy,
5424 UnsignedLongTy,
5425 getPointerType(VoidPtrTy),
5426 getPointerType(VoidPtrTy)
5427 };
5428
5429 static const char *const FieldNames[] = {
5430 "reserved",
5431 "Size",
5432 "CopyFuncPtr",
5433 "DestroyFuncPtr"
5434 };
5435
5436 for (size_t i = 0; i < 4; ++i) {
5437 FieldDecl *Field = FieldDecl::Create(
5438 *this, RD, SourceLocation(), SourceLocation(),
5439 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5440 /*BitWidth=*/nullptr,
5441 /*Mutable=*/false, ICIS_NoInit);
5442 Field->setAccess(AS_public);
5443 RD->addDecl(Field);
5444 }
5445
5446 RD->completeDefinition();
5447
5448 BlockDescriptorExtendedType = RD;
5449 return getTagDeclType(BlockDescriptorExtendedType);
5450}
5451
5452/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5453/// requires copy/dispose. Note that this must match the logic
5454/// in buildByrefHelpers.
5455bool ASTContext::BlockRequiresCopying(QualType Ty,
5456 const VarDecl *D) {
5457 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5458 const Expr *copyExpr = getBlockVarCopyInits(D);
5459 if (!copyExpr && record->hasTrivialDestructor()) return false;
5460
5461 return true;
5462 }
5463
5464 if (!Ty->isObjCRetainableType()) return false;
5465
5466 Qualifiers qs = Ty.getQualifiers();
5467
5468 // If we have lifetime, that dominates.
5469 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
5470 switch (lifetime) {
5471 case Qualifiers::OCL_None: llvm_unreachable("impossible")::llvm::llvm_unreachable_internal("impossible", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5471)
;
5472
5473 // These are just bits as far as the runtime is concerned.
5474 case Qualifiers::OCL_ExplicitNone:
5475 case Qualifiers::OCL_Autoreleasing:
5476 return false;
5477
5478 // Tell the runtime that this is ARC __weak, called by the
5479 // byref routines.
5480 case Qualifiers::OCL_Weak:
5481 // ARC __strong __block variables need to be retained.
5482 case Qualifiers::OCL_Strong:
5483 return true;
5484 }
5485 llvm_unreachable("fell out of lifetime switch!")::llvm::llvm_unreachable_internal("fell out of lifetime switch!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5485)
;
5486 }
5487 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5488 Ty->isObjCObjectPointerType());
5489}
5490
5491bool ASTContext::getByrefLifetime(QualType Ty,
5492 Qualifiers::ObjCLifetime &LifeTime,
5493 bool &HasByrefExtendedLayout) const {
5494
5495 if (!getLangOpts().ObjC1 ||
5496 getLangOpts().getGC() != LangOptions::NonGC)
5497 return false;
5498
5499 HasByrefExtendedLayout = false;
5500 if (Ty->isRecordType()) {
5501 HasByrefExtendedLayout = true;
5502 LifeTime = Qualifiers::OCL_None;
5503 } else if ((LifeTime = Ty.getObjCLifetime())) {
5504 // Honor the ARC qualifiers.
5505 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5506 // The MRR rule.
5507 LifeTime = Qualifiers::OCL_ExplicitNone;
5508 } else {
5509 LifeTime = Qualifiers::OCL_None;
5510 }
5511 return true;
5512}
5513
5514TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5515 if (!ObjCInstanceTypeDecl)
5516 ObjCInstanceTypeDecl =
5517 buildImplicitTypedef(getObjCIdType(), "instancetype");
5518 return ObjCInstanceTypeDecl;
5519}
5520
5521// This returns true if a type has been typedefed to BOOL:
5522// typedef <type> BOOL;
5523static bool isTypeTypedefedAsBOOL(QualType T) {
5524 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
5525 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5526 return II->isStr("BOOL");
5527
5528 return false;
5529}
5530
5531/// getObjCEncodingTypeSize returns size of type for objective-c encoding
5532/// purpose.
5533CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
5534 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5535 return CharUnits::Zero();
5536
5537 CharUnits sz = getTypeSizeInChars(type);
5538
5539 // Make all integer and enum types at least as large as an int
5540 if (sz.isPositive() && type->isIntegralOrEnumerationType())
5541 sz = std::max(sz, getTypeSizeInChars(IntTy));
5542 // Treat arrays as pointers, since that's how they're passed in.
5543 else if (type->isArrayType())
5544 sz = getTypeSizeInChars(VoidPtrTy);
5545 return sz;
5546}
5547
5548bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
5549 return getTargetInfo().getCXXABI().isMicrosoft() &&
5550 VD->isStaticDataMember() &&
5551 VD->getType()->isIntegralOrEnumerationType() &&
5552 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
5553}
5554
5555ASTContext::InlineVariableDefinitionKind
5556ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5557 if (!VD->isInline())
5558 return InlineVariableDefinitionKind::None;
5559
5560 // In almost all cases, it's a weak definition.
5561 auto *First = VD->getFirstDecl();
5562 if (!First->isConstexpr() || First->isInlineSpecified() ||
5563 !VD->isStaticDataMember())
5564 return InlineVariableDefinitionKind::Weak;
5565
5566 // If there's a file-context declaration in this translation unit, it's a
5567 // non-discardable definition.
5568 for (auto *D : VD->redecls())
5569 if (D->getLexicalDeclContext()->isFileContext())
5570 return InlineVariableDefinitionKind::Strong;
5571
5572 // If we've not seen one yet, we don't know.
5573 return InlineVariableDefinitionKind::WeakUnknown;
5574}
5575
5576static inline
5577std::string charUnitsToString(const CharUnits &CU) {
5578 return llvm::itostr(CU.getQuantity());
5579}
5580
5581/// getObjCEncodingForBlock - Return the encoded type for this block
5582/// declaration.
5583std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5584 std::string S;
5585
5586 const BlockDecl *Decl = Expr->getBlockDecl();
5587 QualType BlockTy =
5588 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5589 // Encode result type.
5590 if (getLangOpts().EncodeExtendedBlockSig)
5591 getObjCEncodingForMethodParameter(
5592 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5593 true /*Extended*/);
5594 else
5595 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
5596 // Compute size of all parameters.
5597 // Start with computing size of a pointer in number of bytes.
5598 // FIXME: There might(should) be a better way of doing this computation!
5599 SourceLocation Loc;
5600 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5601 CharUnits ParmOffset = PtrSize;
5602 for (auto PI : Decl->parameters()) {
5603 QualType PType = PI->getType();
5604 CharUnits sz = getObjCEncodingTypeSize(PType);
5605 if (sz.isZero())
5606 continue;
5607 assert (sz.isPositive() && "BlockExpr - Incomplete param type")((sz.isPositive() && "BlockExpr - Incomplete param type"
) ? static_cast<void> (0) : __assert_fail ("sz.isPositive() && \"BlockExpr - Incomplete param type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5607, __PRETTY_FUNCTION__))
;
5608 ParmOffset += sz;
5609 }
5610 // Size of the argument frame
5611 S += charUnitsToString(ParmOffset);
5612 // Block pointer and offset.
5613 S += "@?0";
5614
5615 // Argument types.
5616 ParmOffset = PtrSize;
5617 for (auto PVDecl : Decl->parameters()) {
5618 QualType PType = PVDecl->getOriginalType();
5619 if (const ArrayType *AT =
5620 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5621 // Use array's original type only if it has known number of
5622 // elements.
5623 if (!isa<ConstantArrayType>(AT))
5624 PType = PVDecl->getType();
5625 } else if (PType->isFunctionType())
5626 PType = PVDecl->getType();
5627 if (getLangOpts().EncodeExtendedBlockSig)
5628 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5629 S, true /*Extended*/);
5630 else
5631 getObjCEncodingForType(PType, S);
5632 S += charUnitsToString(ParmOffset);
5633 ParmOffset += getObjCEncodingTypeSize(PType);
5634 }
5635
5636 return S;
5637}
5638
5639std::string
5640ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
5641 std::string S;
5642 // Encode result type.
5643 getObjCEncodingForType(Decl->getReturnType(), S);
5644 CharUnits ParmOffset;
5645 // Compute size of all parameters.
5646 for (auto PI : Decl->parameters()) {
5647 QualType PType = PI->getType();
5648 CharUnits sz = getObjCEncodingTypeSize(PType);
5649 if (sz.isZero())
5650 continue;
5651
5652 assert(sz.isPositive() &&((sz.isPositive() && "getObjCEncodingForFunctionDecl - Incomplete param type"
) ? static_cast<void> (0) : __assert_fail ("sz.isPositive() && \"getObjCEncodingForFunctionDecl - Incomplete param type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5653, __PRETTY_FUNCTION__))
5653 "getObjCEncodingForFunctionDecl - Incomplete param type")((sz.isPositive() && "getObjCEncodingForFunctionDecl - Incomplete param type"
) ? static_cast<void> (0) : __assert_fail ("sz.isPositive() && \"getObjCEncodingForFunctionDecl - Incomplete param type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5653, __PRETTY_FUNCTION__))
;
5654 ParmOffset += sz;
5655 }
5656 S += charUnitsToString(ParmOffset);
5657 ParmOffset = CharUnits::Zero();
5658
5659 // Argument types.
5660 for (auto PVDecl : Decl->parameters()) {
5661 QualType PType = PVDecl->getOriginalType();
5662 if (const ArrayType *AT =
5663 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5664 // Use array's original type only if it has known number of
5665 // elements.
5666 if (!isa<ConstantArrayType>(AT))
5667 PType = PVDecl->getType();
5668 } else if (PType->isFunctionType())
5669 PType = PVDecl->getType();
5670 getObjCEncodingForType(PType, S);
5671 S += charUnitsToString(ParmOffset);
5672 ParmOffset += getObjCEncodingTypeSize(PType);
5673 }
5674
5675 return S;
5676}
5677
5678/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5679/// method parameter or return type. If Extended, include class names and
5680/// block object types.
5681void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5682 QualType T, std::string& S,
5683 bool Extended) const {
5684 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5685 getObjCEncodingForTypeQualifier(QT, S);
5686 // Encode parameter type.
5687 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5688 true /*OutermostType*/,
5689 false /*EncodingProperty*/,
5690 false /*StructField*/,
5691 Extended /*EncodeBlockParameters*/,
5692 Extended /*EncodeClassNames*/);
5693}
5694
5695/// getObjCEncodingForMethodDecl - Return the encoded type for this method
5696/// declaration.
5697std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5698 bool Extended) const {
5699 // FIXME: This is not very efficient.
5700 // Encode return type.
5701 std::string S;
5702 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5703 Decl->getReturnType(), S, Extended);
5704 // Compute size of all parameters.
5705 // Start with computing size of a pointer in number of bytes.
5706 // FIXME: There might(should) be a better way of doing this computation!
5707 SourceLocation Loc;
5708 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5709 // The first two arguments (self and _cmd) are pointers; account for
5710 // their size.
5711 CharUnits ParmOffset = 2 * PtrSize;
5712 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5713 E = Decl->sel_param_end(); PI != E; ++PI) {
5714 QualType PType = (*PI)->getType();
5715 CharUnits sz = getObjCEncodingTypeSize(PType);
5716 if (sz.isZero())
5717 continue;
5718
5719 assert (sz.isPositive() &&((sz.isPositive() && "getObjCEncodingForMethodDecl - Incomplete param type"
) ? static_cast<void> (0) : __assert_fail ("sz.isPositive() && \"getObjCEncodingForMethodDecl - Incomplete param type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5720, __PRETTY_FUNCTION__))
5720 "getObjCEncodingForMethodDecl - Incomplete param type")((sz.isPositive() && "getObjCEncodingForMethodDecl - Incomplete param type"
) ? static_cast<void> (0) : __assert_fail ("sz.isPositive() && \"getObjCEncodingForMethodDecl - Incomplete param type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5720, __PRETTY_FUNCTION__))
;
5721 ParmOffset += sz;
5722 }
5723 S += charUnitsToString(ParmOffset);
5724 S += "@0:";
5725 S += charUnitsToString(PtrSize);
5726
5727 // Argument types.
5728 ParmOffset = 2 * PtrSize;
5729 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5730 E = Decl->sel_param_end(); PI != E; ++PI) {
5731 const ParmVarDecl *PVDecl = *PI;
5732 QualType PType = PVDecl->getOriginalType();
5733 if (const ArrayType *AT =
5734 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5735 // Use array's original type only if it has known number of
5736 // elements.
5737 if (!isa<ConstantArrayType>(AT))
5738 PType = PVDecl->getType();
5739 } else if (PType->isFunctionType())
5740 PType = PVDecl->getType();
5741 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5742 PType, S, Extended);
5743 S += charUnitsToString(ParmOffset);
5744 ParmOffset += getObjCEncodingTypeSize(PType);
5745 }
5746
5747 return S;
5748}
5749
5750ObjCPropertyImplDecl *
5751ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5752 const ObjCPropertyDecl *PD,
5753 const Decl *Container) const {
5754 if (!Container)
5755 return nullptr;
5756 if (const ObjCCategoryImplDecl *CID =
5757 dyn_cast<ObjCCategoryImplDecl>(Container)) {
5758 for (auto *PID : CID->property_impls())
5759 if (PID->getPropertyDecl() == PD)
5760 return PID;
5761 } else {
5762 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5763 for (auto *PID : OID->property_impls())
5764 if (PID->getPropertyDecl() == PD)
5765 return PID;
5766 }
5767 return nullptr;
5768}
5769
5770/// getObjCEncodingForPropertyDecl - Return the encoded type for this
5771/// property declaration. If non-NULL, Container must be either an
5772/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5773/// NULL when getting encodings for protocol properties.
5774/// Property attributes are stored as a comma-delimited C string. The simple
5775/// attributes readonly and bycopy are encoded as single characters. The
5776/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5777/// encoded as single characters, followed by an identifier. Property types
5778/// are also encoded as a parametrized attribute. The characters used to encode
5779/// these attributes are defined by the following enumeration:
5780/// @code
5781/// enum PropertyAttributes {
5782/// kPropertyReadOnly = 'R', // property is read-only.
5783/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5784/// kPropertyByref = '&', // property is a reference to the value last assigned
5785/// kPropertyDynamic = 'D', // property is dynamic
5786/// kPropertyGetter = 'G', // followed by getter selector name
5787/// kPropertySetter = 'S', // followed by setter selector name
5788/// kPropertyInstanceVariable = 'V' // followed by instance variable name
5789/// kPropertyType = 'T' // followed by old-style type encoding.
5790/// kPropertyWeak = 'W' // 'weak' property
5791/// kPropertyStrong = 'P' // property GC'able
5792/// kPropertyNonAtomic = 'N' // property non-atomic
5793/// };
5794/// @endcode
5795std::string
5796ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5797 const Decl *Container) const {
5798 // Collect information from the property implementation decl(s).
5799 bool Dynamic = false;
5800 ObjCPropertyImplDecl *SynthesizePID = nullptr;
5801
5802 if (ObjCPropertyImplDecl *PropertyImpDecl =
5803 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5804 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5805 Dynamic = true;
5806 else
5807 SynthesizePID = PropertyImpDecl;
5808 }
5809
5810 // FIXME: This is not very efficient.
5811 std::string S = "T";
5812
5813 // Encode result type.
5814 // GCC has some special rules regarding encoding of properties which
5815 // closely resembles encoding of ivars.
5816 getObjCEncodingForPropertyType(PD->getType(), S);
5817
5818 if (PD->isReadOnly()) {
5819 S += ",R";
5820 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5821 S += ",C";
5822 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5823 S += ",&";
5824 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5825 S += ",W";
5826 } else {
5827 switch (PD->getSetterKind()) {
5828 case ObjCPropertyDecl::Assign: break;
5829 case ObjCPropertyDecl::Copy: S += ",C"; break;
5830 case ObjCPropertyDecl::Retain: S += ",&"; break;
5831 case ObjCPropertyDecl::Weak: S += ",W"; break;
5832 }
5833 }
5834
5835 // It really isn't clear at all what this means, since properties
5836 // are "dynamic by default".
5837 if (Dynamic)
5838 S += ",D";
5839
5840 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5841 S += ",N";
5842
5843 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5844 S += ",G";
5845 S += PD->getGetterName().getAsString();
5846 }
5847
5848 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5849 S += ",S";
5850 S += PD->getSetterName().getAsString();
5851 }
5852
5853 if (SynthesizePID) {
5854 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5855 S += ",V";
5856 S += OID->getNameAsString();
5857 }
5858
5859 // FIXME: OBJCGC: weak & strong
5860 return S;
5861}
5862
5863/// getLegacyIntegralTypeEncoding -
5864/// Another legacy compatibility encoding: 32-bit longs are encoded as
5865/// 'l' or 'L' , but not always. For typedefs, we need to use
5866/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5867///
5868void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5869 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5870 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5871 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5872 PointeeTy = UnsignedIntTy;
5873 else
5874 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5875 PointeeTy = IntTy;
5876 }
5877 }
5878}
5879
5880void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5881 const FieldDecl *Field,
5882 QualType *NotEncodedT) const {
5883 // We follow the behavior of gcc, expanding structures which are
5884 // directly pointed to, and expanding embedded structures. Note that
5885 // these rules are sufficient to prevent recursive encoding of the
5886 // same type.
5887 getObjCEncodingForTypeImpl(T, S, true, true, Field,
5888 true /* outermost type */, false, false,
5889 false, false, false, NotEncodedT);
5890}
5891
5892void ASTContext::getObjCEncodingForPropertyType(QualType T,
5893 std::string& S) const {
5894 // Encode result type.
5895 // GCC has some special rules regarding encoding of properties which
5896 // closely resembles encoding of ivars.
5897 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5898 true /* outermost type */,
5899 true /* encoding property */);
5900}
5901
5902static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5903 BuiltinType::Kind kind) {
5904 switch (kind) {
5905 case BuiltinType::Void: return 'v';
5906 case BuiltinType::Bool: return 'B';
5907 case BuiltinType::Char_U:
5908 case BuiltinType::UChar: return 'C';
5909 case BuiltinType::Char16:
5910 case BuiltinType::UShort: return 'S';
5911 case BuiltinType::Char32:
5912 case BuiltinType::UInt: return 'I';
5913 case BuiltinType::ULong:
5914 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5915 case BuiltinType::UInt128: return 'T';
5916 case BuiltinType::ULongLong: return 'Q';
5917 case BuiltinType::Char_S:
5918 case BuiltinType::SChar: return 'c';
5919 case BuiltinType::Short: return 's';
5920 case BuiltinType::WChar_S:
5921 case BuiltinType::WChar_U:
5922 case BuiltinType::Int: return 'i';
5923 case BuiltinType::Long:
5924 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5925 case BuiltinType::LongLong: return 'q';
5926 case BuiltinType::Int128: return 't';
5927 case BuiltinType::Float: return 'f';
5928 case BuiltinType::Double: return 'd';
5929 case BuiltinType::LongDouble: return 'D';
5930 case BuiltinType::NullPtr: return '*'; // like char*
5931
5932 case BuiltinType::Float128:
5933 case BuiltinType::Half:
5934 // FIXME: potentially need @encodes for these!
5935 return ' ';
5936
5937 case BuiltinType::ObjCId:
5938 case BuiltinType::ObjCClass:
5939 case BuiltinType::ObjCSel:
5940 llvm_unreachable("@encoding ObjC primitive type")::llvm::llvm_unreachable_internal("@encoding ObjC primitive type"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5940)
;
5941
5942 // OpenCL and placeholder types don't need @encodings.
5943#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5944 case BuiltinType::Id:
5945#include "clang/Basic/OpenCLImageTypes.def"
5946 case BuiltinType::OCLEvent:
5947 case BuiltinType::OCLClkEvent:
5948 case BuiltinType::OCLQueue:
5949 case BuiltinType::OCLReserveID:
5950 case BuiltinType::OCLSampler:
5951 case BuiltinType::Dependent:
5952#define BUILTIN_TYPE(KIND, ID)
5953#define PLACEHOLDER_TYPE(KIND, ID) \
5954 case BuiltinType::KIND:
5955#include "clang/AST/BuiltinTypes.def"
5956 llvm_unreachable("invalid builtin type for @encode")::llvm::llvm_unreachable_internal("invalid builtin type for @encode"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5956)
;
5957 }
5958 llvm_unreachable("invalid BuiltinType::Kind value")::llvm::llvm_unreachable_internal("invalid BuiltinType::Kind value"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5958)
;
5959}
5960
5961static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5962 EnumDecl *Enum = ET->getDecl();
5963
5964 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5965 if (!Enum->isFixed())
5966 return 'i';
5967
5968 // The encoding of a fixed enum type matches its fixed underlying type.
5969 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5970 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5971}
5972
5973static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5974 QualType T, const FieldDecl *FD) {
5975 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl")((FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"
) ? static_cast<void> (0) : __assert_fail ("FD->isBitField() && \"not a bitfield - getObjCEncodingForTypeImpl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 5975, __PRETTY_FUNCTION__))
;
5976 S += 'b';
5977 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5978 // The GNU runtime requires more information; bitfields are encoded as b,
5979 // then the offset (in bits) of the first element, then the type of the
5980 // bitfield, then the size in bits. For example, in this structure:
5981 //
5982 // struct
5983 // {
5984 // int integer;
5985 // int flags:2;
5986 // };
5987 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5988 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5989 // information is not especially sensible, but we're stuck with it for
5990 // compatibility with GCC, although providing it breaks anything that
5991 // actually uses runtime introspection and wants to work on both runtimes...
5992 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5993 uint64_t Offset;
5994
5995 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
5996 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
5997 IVD);
5998 } else {
5999 const RecordDecl *RD = FD->getParent();
6000 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6001 Offset = RL.getFieldOffset(FD->getFieldIndex());
6002 }
6003
6004 S += llvm::utostr(Offset);
6005
6006 if (const EnumType *ET = T->getAs<EnumType>())
6007 S += ObjCEncodingForEnumType(Ctx, ET);
6008 else {
6009 const BuiltinType *BT = T->castAs<BuiltinType>();
6010 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6011 }
6012 }
6013 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
6014}
6015
6016// FIXME: Use SmallString for accumulating string.
6017void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6018 bool ExpandPointedToStructures,
6019 bool ExpandStructures,
6020 const FieldDecl *FD,
6021 bool OutermostType,
6022 bool EncodingProperty,
6023 bool StructField,
6024 bool EncodeBlockParameters,
6025 bool EncodeClassNames,
6026 bool EncodePointerToObjCTypedef,
6027 QualType *NotEncodedT) const {
6028 CanQualType CT = getCanonicalType(T);
6029 switch (CT->getTypeClass()) {
6030 case Type::Builtin:
6031 case Type::Enum:
6032 if (FD && FD->isBitField())
6033 return EncodeBitField(this, S, T, FD);
6034 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
6035 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6036 else
6037 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
6038 return;
6039
6040 case Type::Complex: {
6041 const ComplexType *CT = T->castAs<ComplexType>();
6042 S += 'j';
6043 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
6044 return;
6045 }
6046
6047 case Type::Atomic: {
6048 const AtomicType *AT = T->castAs<AtomicType>();
6049 S += 'A';
6050 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
6051 return;
6052 }
6053
6054 // encoding for pointer or reference types.
6055 case Type::Pointer:
6056 case Type::LValueReference:
6057 case Type::RValueReference: {
6058 QualType PointeeTy;
6059 if (isa<PointerType>(CT)) {
6060 const PointerType *PT = T->castAs<PointerType>();
6061 if (PT->isObjCSelType()) {
6062 S += ':';
6063 return;
6064 }
6065 PointeeTy = PT->getPointeeType();
6066 } else {
6067 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6068 }
6069
6070 bool isReadOnly = false;
6071 // For historical/compatibility reasons, the read-only qualifier of the
6072 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6073 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
6074 // Also, do not emit the 'r' for anything but the outermost type!
6075 if (isa<TypedefType>(T.getTypePtr())) {
6076 if (OutermostType && T.isConstQualified()) {
6077 isReadOnly = true;
6078 S += 'r';
6079 }
6080 } else if (OutermostType) {
6081 QualType P = PointeeTy;
6082 while (P->getAs<PointerType>())
6083 P = P->getAs<PointerType>()->getPointeeType();
6084 if (P.isConstQualified()) {
6085 isReadOnly = true;
6086 S += 'r';
6087 }
6088 }
6089 if (isReadOnly) {
6090 // Another legacy compatibility encoding. Some ObjC qualifier and type
6091 // combinations need to be rearranged.
6092 // Rewrite "in const" from "nr" to "rn"
6093 if (StringRef(S).endswith("nr"))
6094 S.replace(S.end()-2, S.end(), "rn");
6095 }
6096
6097 if (PointeeTy->isCharType()) {
6098 // char pointer types should be encoded as '*' unless it is a
6099 // type that has been typedef'd to 'BOOL'.
6100 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
6101 S += '*';
6102 return;
6103 }
6104 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
6105 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6106 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6107 S += '#';
6108 return;
6109 }
6110 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6111 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6112 S += '@';
6113 return;
6114 }
6115 // fall through...
6116 }
6117 S += '^';
6118 getLegacyIntegralTypeEncoding(PointeeTy);
6119
6120 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
6121 nullptr, false, false, false, false, false, false,
6122 NotEncodedT);
6123 return;
6124 }
6125
6126 case Type::ConstantArray:
6127 case Type::IncompleteArray:
6128 case Type::VariableArray: {
6129 const ArrayType *AT = cast<ArrayType>(CT);
6130
6131 if (isa<IncompleteArrayType>(AT) && !StructField) {
6132 // Incomplete arrays are encoded as a pointer to the array element.
6133 S += '^';
6134
6135 getObjCEncodingForTypeImpl(AT->getElementType(), S,
6136 false, ExpandStructures, FD);
6137 } else {
6138 S += '[';
6139
6140 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6141 S += llvm::utostr(CAT->getSize().getZExtValue());
6142 else {
6143 //Variable length arrays are encoded as a regular array with 0 elements.
6144 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&(((isa<VariableArrayType>(AT) || isa<IncompleteArrayType
>(AT)) && "Unknown array type!") ? static_cast<
void> (0) : __assert_fail ("(isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && \"Unknown array type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 6145, __PRETTY_FUNCTION__))
6145 "Unknown array type!")(((isa<VariableArrayType>(AT) || isa<IncompleteArrayType
>(AT)) && "Unknown array type!") ? static_cast<
void> (0) : __assert_fail ("(isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && \"Unknown array type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 6145, __PRETTY_FUNCTION__))
;
6146 S += '0';
6147 }
6148
6149 getObjCEncodingForTypeImpl(AT->getElementType(), S,
6150 false, ExpandStructures, FD,
6151 false, false, false, false, false, false,
6152 NotEncodedT);
6153 S += ']';
6154 }
6155 return;
6156 }
6157
6158 case Type::FunctionNoProto:
6159 case Type::FunctionProto:
6160 S += '?';
6161 return;
6162
6163 case Type::Record: {
6164 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
6165 S += RDecl->isUnion() ? '(' : '{';
6166 // Anonymous structures print as '?'
6167 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6168 S += II->getName();
6169 if (ClassTemplateSpecializationDecl *Spec
6170 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6171 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
6172 llvm::raw_string_ostream OS(S);
6173 TemplateSpecializationType::PrintTemplateArgumentList(OS,
6174 TemplateArgs.asArray(),
6175 (*this).getPrintingPolicy());
6176 }
6177 } else {
6178 S += '?';
6179 }
6180 if (ExpandStructures) {
6181 S += '=';
6182 if (!RDecl->isUnion()) {
6183 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
6184 } else {
6185 for (const auto *Field : RDecl->fields()) {
6186 if (FD) {
6187 S += '"';
6188 S += Field->getNameAsString();
6189 S += '"';
6190 }
6191
6192 // Special case bit-fields.
6193 if (Field->isBitField()) {
6194 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
6195 Field);
6196 } else {
6197 QualType qt = Field->getType();
6198 getLegacyIntegralTypeEncoding(qt);
6199 getObjCEncodingForTypeImpl(qt, S, false, true,
6200 FD, /*OutermostType*/false,
6201 /*EncodingProperty*/false,
6202 /*StructField*/true,
6203 false, false, false, NotEncodedT);
6204 }
6205 }
6206 }
6207 }
6208 S += RDecl->isUnion() ? ')' : '}';
6209 return;
6210 }
6211
6212 case Type::BlockPointer: {
6213 const BlockPointerType *BT = T->castAs<BlockPointerType>();
6214 S += "@?"; // Unlike a pointer-to-function, which is "^?".
6215 if (EncodeBlockParameters) {
6216 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
6217
6218 S += '<';
6219 // Block return type
6220 getObjCEncodingForTypeImpl(
6221 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6222 FD, false /* OutermostType */, EncodingProperty,
6223 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6224 NotEncodedT);
6225 // Block self
6226 S += "@?";
6227 // Block parameters
6228 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
6229 for (const auto &I : FPT->param_types())
6230 getObjCEncodingForTypeImpl(
6231 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6232 false /* OutermostType */, EncodingProperty,
6233 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6234 false, NotEncodedT);
6235 }
6236 S += '>';
6237 }
6238 return;
6239 }
6240
6241 case Type::ObjCObject: {
6242 // hack to match legacy encoding of *id and *Class
6243 QualType Ty = getObjCObjectPointerType(CT);
6244 if (Ty->isObjCIdType()) {
6245 S += "{objc_object=}";
6246 return;
6247 }
6248 else if (Ty->isObjCClassType()) {
6249 S += "{objc_class=}";
6250 return;
6251 }
6252 // TODO: Double check to make sure this intentially falls through.
6253 LLVM_FALLTHROUGH[[clang::fallthrough]];
6254 }
6255
6256 case Type::ObjCInterface: {
6257 // Ignore protocol qualifiers when mangling at this level.
6258 // @encode(class_name)
6259 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
6260 S += '{';
6261 S += OI->getObjCRuntimeNameAsString();
6262 if (ExpandStructures) {
6263 S += '=';
6264 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6265 DeepCollectObjCIvars(OI, true, Ivars);
6266 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6267 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
6268 if (Field->isBitField())
6269 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6270 else
6271 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6272 false, false, false, false, false,
6273 EncodePointerToObjCTypedef,
6274 NotEncodedT);
6275 }
6276 }
6277 S += '}';
6278 return;
6279 }
6280
6281 case Type::ObjCObjectPointer: {
6282 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
6283 if (OPT->isObjCIdType()) {
6284 S += '@';
6285 return;
6286 }
6287
6288 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6289 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6290 // Since this is a binary compatibility issue, need to consult with runtime
6291 // folks. Fortunately, this is a *very* obsure construct.
6292 S += '#';
6293 return;
6294 }
6295
6296 if (OPT->isObjCQualifiedIdType()) {
6297 getObjCEncodingForTypeImpl(getObjCIdType(), S,
6298 ExpandPointedToStructures,
6299 ExpandStructures, FD);
6300 if (FD || EncodingProperty || EncodeClassNames) {
6301 // Note that we do extended encoding of protocol qualifer list
6302 // Only when doing ivar or property encoding.
6303 S += '"';
6304 for (const auto *I : OPT->quals()) {
6305 S += '<';
6306 S += I->getObjCRuntimeNameAsString();
6307 S += '>';
6308 }
6309 S += '"';
6310 }
6311 return;
6312 }
6313
6314 QualType PointeeTy = OPT->getPointeeType();
6315 if (!EncodingProperty &&
6316 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6317 !EncodePointerToObjCTypedef) {
6318 // Another historical/compatibility reason.
6319 // We encode the underlying type which comes out as
6320 // {...};
6321 S += '^';
6322 if (FD && OPT->getInterfaceDecl()) {
6323 // Prevent recursive encoding of fields in some rare cases.
6324 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6325 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6326 DeepCollectObjCIvars(OI, true, Ivars);
6327 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6328 if (cast<FieldDecl>(Ivars[i]) == FD) {
6329 S += '{';
6330 S += OI->getObjCRuntimeNameAsString();
6331 S += '}';
6332 return;
6333 }
6334 }
6335 }
6336 getObjCEncodingForTypeImpl(PointeeTy, S,
6337 false, ExpandPointedToStructures,
6338 nullptr,
6339 false, false, false, false, false,
6340 /*EncodePointerToObjCTypedef*/true);
6341 return;
6342 }
6343
6344 S += '@';
6345 if (OPT->getInterfaceDecl() &&
6346 (FD || EncodingProperty || EncodeClassNames)) {
6347 S += '"';
6348 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
6349 for (const auto *I : OPT->quals()) {
6350 S += '<';
6351 S += I->getObjCRuntimeNameAsString();
6352 S += '>';
6353 }
6354 S += '"';
6355 }
6356 return;
6357 }
6358
6359 // gcc just blithely ignores member pointers.
6360 // FIXME: we shoul do better than that. 'M' is available.
6361 case Type::MemberPointer:
6362 // This matches gcc's encoding, even though technically it is insufficient.
6363 //FIXME. We should do a better job than gcc.
6364 case Type::Vector:
6365 case Type::ExtVector:
6366 // Until we have a coherent encoding of these three types, issue warning.
6367 { if (NotEncodedT)
6368 *NotEncodedT = T;
6369 return;
6370 }
6371
6372 // We could see an undeduced auto type here during error recovery.
6373 // Just ignore it.
6374 case Type::Auto:
6375 case Type::DeducedTemplateSpecialization:
6376 return;
6377
6378 case Type::Pipe:
6379#define ABSTRACT_TYPE(KIND, BASE)
6380#define TYPE(KIND, BASE)
6381#define DEPENDENT_TYPE(KIND, BASE) \
6382 case Type::KIND:
6383#define NON_CANONICAL_TYPE(KIND, BASE) \
6384 case Type::KIND:
6385#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6386 case Type::KIND:
6387#include "clang/AST/TypeNodes.def"
6388 llvm_unreachable("@encode for dependent type!")::llvm::llvm_unreachable_internal("@encode for dependent type!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 6388)
;
6389 }
6390 llvm_unreachable("bad type kind!")::llvm::llvm_unreachable_internal("bad type kind!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 6390)
;
6391}
6392
6393void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6394 std::string &S,
6395 const FieldDecl *FD,
6396 bool includeVBases,
6397 QualType *NotEncodedT) const {
6398 assert(RDecl && "Expected non-null RecordDecl")((RDecl && "Expected non-null RecordDecl") ? static_cast
<void> (0) : __assert_fail ("RDecl && \"Expected non-null RecordDecl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 6398, __PRETTY_FUNCTION__))
;
6399 assert(!RDecl->isUnion() && "Should not be called for unions")((!RDecl->isUnion() && "Should not be called for unions"
) ? static_cast<void> (0) : __assert_fail ("!RDecl->isUnion() && \"Should not be called for unions\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 6399, __PRETTY_FUNCTION__))
;
6400 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
6401 return;
6402
6403 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6404 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6405 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6406
6407 if (CXXRec) {
6408 for (const auto &BI : CXXRec->bases()) {
6409 if (!BI.isVirtual()) {
6410 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
6411 if (base->isEmpty())
6412 continue;
6413 uint64_t offs = toBits(layout.getBaseClassOffset(base));
6414 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6415 std::make_pair(offs, base));
6416 }
6417 }
6418 }
6419
6420 unsigned i = 0;
6421 for (auto *Field : RDecl->fields()) {
6422 uint64_t offs = layout.getFieldOffset(i);
6423 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6424 std::make_pair(offs, Field));
6425 ++i;
6426 }
6427
6428 if (CXXRec && includeVBases) {
6429 for (const auto &BI : CXXRec->vbases()) {
6430 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
6431 if (base->isEmpty())
6432 continue;
6433 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
6434 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6435 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
6436 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6437 std::make_pair(offs, base));
6438 }
6439 }
6440
6441 CharUnits size;
6442 if (CXXRec) {
6443 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6444 } else {
6445 size = layout.getSize();
6446 }
6447
6448#ifndef NDEBUG
6449 uint64_t CurOffs = 0;
6450#endif
6451 std::multimap<uint64_t, NamedDecl *>::iterator
6452 CurLayObj = FieldOrBaseOffsets.begin();
6453
6454 if (CXXRec && CXXRec->isDynamicClass() &&
6455 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
6456 if (FD) {
6457 S += "\"_vptr$";
6458 std::string recname = CXXRec->getNameAsString();
6459 if (recname.empty()) recname = "?";
6460 S += recname;
6461 S += '"';
6462 }
6463 S += "^^?";
6464#ifndef NDEBUG
6465 CurOffs += getTypeSize(VoidPtrTy);
6466#endif
6467 }
6468
6469 if (!RDecl->hasFlexibleArrayMember()) {
6470 // Mark the end of the structure.
6471 uint64_t offs = toBits(size);
6472 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6473 std::make_pair(offs, nullptr));
6474 }
6475
6476 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
6477#ifndef NDEBUG
6478 assert(CurOffs <= CurLayObj->first)((CurOffs <= CurLayObj->first) ? static_cast<void>
(0) : __assert_fail ("CurOffs <= CurLayObj->first", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 6478, __PRETTY_FUNCTION__))
;
6479 if (CurOffs < CurLayObj->first) {
6480 uint64_t padding = CurLayObj->first - CurOffs;
6481 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6482 // packing/alignment of members is different that normal, in which case
6483 // the encoding will be out-of-sync with the real layout.
6484 // If the runtime switches to just consider the size of types without
6485 // taking into account alignment, we could make padding explicit in the
6486 // encoding (e.g. using arrays of chars). The encoding strings would be
6487 // longer then though.
6488 CurOffs += padding;
6489 }
6490#endif
6491
6492 NamedDecl *dcl = CurLayObj->second;
6493 if (!dcl)
6494 break; // reached end of structure.
6495
6496 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6497 // We expand the bases without their virtual bases since those are going
6498 // in the initial structure. Note that this differs from gcc which
6499 // expands virtual bases each time one is encountered in the hierarchy,
6500 // making the encoding type bigger than it really is.
6501 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6502 NotEncodedT);
6503 assert(!base->isEmpty())((!base->isEmpty()) ? static_cast<void> (0) : __assert_fail
("!base->isEmpty()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 6503, __PRETTY_FUNCTION__))
;
6504#ifndef NDEBUG
6505 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
6506#endif
6507 } else {
6508 FieldDecl *field = cast<FieldDecl>(dcl);
6509 if (FD) {
6510 S += '"';
6511 S += field->getNameAsString();
6512 S += '"';
6513 }
6514
6515 if (field->isBitField()) {
6516 EncodeBitField(this, S, field->getType(), field);
6517#ifndef NDEBUG
6518 CurOffs += field->getBitWidthValue(*this);
6519#endif
6520 } else {
6521 QualType qt = field->getType();
6522 getLegacyIntegralTypeEncoding(qt);
6523 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6524 /*OutermostType*/false,
6525 /*EncodingProperty*/false,
6526 /*StructField*/true,
6527 false, false, false, NotEncodedT);
6528#ifndef NDEBUG
6529 CurOffs += getTypeSize(field->getType());
6530#endif
6531 }
6532 }
6533 }
6534}
6535
6536void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
6537 std::string& S) const {
6538 if (QT & Decl::OBJC_TQ_In)
6539 S += 'n';
6540 if (QT & Decl::OBJC_TQ_Inout)
6541 S += 'N';
6542 if (QT & Decl::OBJC_TQ_Out)
6543 S += 'o';
6544 if (QT & Decl::OBJC_TQ_Bycopy)
6545 S += 'O';
6546 if (QT & Decl::OBJC_TQ_Byref)
6547 S += 'R';
6548 if (QT & Decl::OBJC_TQ_Oneway)
6549 S += 'V';
6550}
6551
6552TypedefDecl *ASTContext::getObjCIdDecl() const {
6553 if (!ObjCIdDecl) {
6554 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
6555 T = getObjCObjectPointerType(T);
6556 ObjCIdDecl = buildImplicitTypedef(T, "id");
6557 }
6558 return ObjCIdDecl;
6559}
6560
6561TypedefDecl *ASTContext::getObjCSelDecl() const {
6562 if (!ObjCSelDecl) {
6563 QualType T = getPointerType(ObjCBuiltinSelTy);
6564 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
6565 }
6566 return ObjCSelDecl;
6567}
6568
6569TypedefDecl *ASTContext::getObjCClassDecl() const {
6570 if (!ObjCClassDecl) {
6571 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
6572 T = getObjCObjectPointerType(T);
6573 ObjCClassDecl = buildImplicitTypedef(T, "Class");
6574 }
6575 return ObjCClassDecl;
6576}
6577
6578ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6579 if (!ObjCProtocolClassDecl) {
6580 ObjCProtocolClassDecl
6581 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6582 SourceLocation(),
6583 &Idents.get("Protocol"),
6584 /*typeParamList=*/nullptr,
6585 /*PrevDecl=*/nullptr,
6586 SourceLocation(), true);
6587 }
6588
6589 return ObjCProtocolClassDecl;
6590}
6591
6592//===----------------------------------------------------------------------===//
6593// __builtin_va_list Construction Functions
6594//===----------------------------------------------------------------------===//
6595
6596static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6597 StringRef Name) {
6598 // typedef char* __builtin[_ms]_va_list;
6599 QualType T = Context->getPointerType(Context->CharTy);
6600 return Context->buildImplicitTypedef(T, Name);
6601}
6602
6603static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6604 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6605}
6606
6607static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6608 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
6609}
6610
6611static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6612 // typedef void* __builtin_va_list;
6613 QualType T = Context->getPointerType(Context->VoidTy);
6614 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6615}
6616
6617static TypedefDecl *
6618CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
6619 // struct __va_list
6620 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
6621 if (Context->getLangOpts().CPlusPlus) {
6622 // namespace std { struct __va_list {
6623 NamespaceDecl *NS;
6624 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6625 Context->getTranslationUnitDecl(),
6626 /*Inline*/ false, SourceLocation(),
6627 SourceLocation(), &Context->Idents.get("std"),
6628 /*PrevDecl*/ nullptr);
6629 NS->setImplicit();
6630 VaListTagDecl->setDeclContext(NS);
6631 }
6632
6633 VaListTagDecl->startDefinition();
6634
6635 const size_t NumFields = 5;
6636 QualType FieldTypes[NumFields];
6637 const char *FieldNames[NumFields];
6638
6639 // void *__stack;
6640 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6641 FieldNames[0] = "__stack";
6642
6643 // void *__gr_top;
6644 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6645 FieldNames[1] = "__gr_top";
6646
6647 // void *__vr_top;
6648 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6649 FieldNames[2] = "__vr_top";
6650
6651 // int __gr_offs;
6652 FieldTypes[3] = Context->IntTy;
6653 FieldNames[3] = "__gr_offs";
6654
6655 // int __vr_offs;
6656 FieldTypes[4] = Context->IntTy;
6657 FieldNames[4] = "__vr_offs";
6658
6659 // Create fields
6660 for (unsigned i = 0; i < NumFields; ++i) {
6661 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6662 VaListTagDecl,
6663 SourceLocation(),
6664 SourceLocation(),
6665 &Context->Idents.get(FieldNames[i]),
6666 FieldTypes[i], /*TInfo=*/nullptr,
6667 /*BitWidth=*/nullptr,
6668 /*Mutable=*/false,
6669 ICIS_NoInit);
6670 Field->setAccess(AS_public);
6671 VaListTagDecl->addDecl(Field);
6672 }
6673 VaListTagDecl->completeDefinition();
6674 Context->VaListTagDecl = VaListTagDecl;
6675 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6676
6677 // } __builtin_va_list;
6678 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
6679}
6680
6681static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6682 // typedef struct __va_list_tag {
6683 RecordDecl *VaListTagDecl;
6684
6685 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6686 VaListTagDecl->startDefinition();
6687
6688 const size_t NumFields = 5;
6689 QualType FieldTypes[NumFields];
6690 const char *FieldNames[NumFields];
6691
6692 // unsigned char gpr;
6693 FieldTypes[0] = Context->UnsignedCharTy;
6694 FieldNames[0] = "gpr";
6695
6696 // unsigned char fpr;
6697 FieldTypes[1] = Context->UnsignedCharTy;
6698 FieldNames[1] = "fpr";
6699
6700 // unsigned short reserved;
6701 FieldTypes[2] = Context->UnsignedShortTy;
6702 FieldNames[2] = "reserved";
6703
6704 // void* overflow_arg_area;
6705 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6706 FieldNames[3] = "overflow_arg_area";
6707
6708 // void* reg_save_area;
6709 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6710 FieldNames[4] = "reg_save_area";
6711
6712 // Create fields
6713 for (unsigned i = 0; i < NumFields; ++i) {
6714 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6715 SourceLocation(),
6716 SourceLocation(),
6717 &Context->Idents.get(FieldNames[i]),
6718 FieldTypes[i], /*TInfo=*/nullptr,
6719 /*BitWidth=*/nullptr,
6720 /*Mutable=*/false,
6721 ICIS_NoInit);
6722 Field->setAccess(AS_public);
6723 VaListTagDecl->addDecl(Field);
6724 }
6725 VaListTagDecl->completeDefinition();
6726 Context->VaListTagDecl = VaListTagDecl;
6727 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6728
6729 // } __va_list_tag;
6730 TypedefDecl *VaListTagTypedefDecl =
6731 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6732
6733 QualType VaListTagTypedefType =
6734 Context->getTypedefType(VaListTagTypedefDecl);
6735
6736 // typedef __va_list_tag __builtin_va_list[1];
6737 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6738 QualType VaListTagArrayType
6739 = Context->getConstantArrayType(VaListTagTypedefType,
6740 Size, ArrayType::Normal, 0);
6741 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6742}
6743
6744static TypedefDecl *
6745CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6746 // struct __va_list_tag {
6747 RecordDecl *VaListTagDecl;
6748 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6749 VaListTagDecl->startDefinition();
6750
6751 const size_t NumFields = 4;
6752 QualType FieldTypes[NumFields];
6753 const char *FieldNames[NumFields];
6754
6755 // unsigned gp_offset;
6756 FieldTypes[0] = Context->UnsignedIntTy;
6757 FieldNames[0] = "gp_offset";
6758
6759 // unsigned fp_offset;
6760 FieldTypes[1] = Context->UnsignedIntTy;
6761 FieldNames[1] = "fp_offset";
6762
6763 // void* overflow_arg_area;
6764 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6765 FieldNames[2] = "overflow_arg_area";
6766
6767 // void* reg_save_area;
6768 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6769 FieldNames[3] = "reg_save_area";
6770
6771 // Create fields
6772 for (unsigned i = 0; i < NumFields; ++i) {
6773 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6774 VaListTagDecl,
6775 SourceLocation(),
6776 SourceLocation(),
6777 &Context->Idents.get(FieldNames[i]),
6778 FieldTypes[i], /*TInfo=*/nullptr,
6779 /*BitWidth=*/nullptr,
6780 /*Mutable=*/false,
6781 ICIS_NoInit);
6782 Field->setAccess(AS_public);
6783 VaListTagDecl->addDecl(Field);
6784 }
6785 VaListTagDecl->completeDefinition();
6786 Context->VaListTagDecl = VaListTagDecl;
6787 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6788
6789 // };
6790
6791 // typedef struct __va_list_tag __builtin_va_list[1];
6792 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6793 QualType VaListTagArrayType =
6794 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6795 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6796}
6797
6798static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6799 // typedef int __builtin_va_list[4];
6800 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6801 QualType IntArrayType =
6802 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
6803 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
6804}
6805
6806static TypedefDecl *
6807CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6808 // struct __va_list
6809 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
6810 if (Context->getLangOpts().CPlusPlus) {
6811 // namespace std { struct __va_list {
6812 NamespaceDecl *NS;
6813 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6814 Context->getTranslationUnitDecl(),
6815 /*Inline*/false, SourceLocation(),
6816 SourceLocation(), &Context->Idents.get("std"),
6817 /*PrevDecl*/ nullptr);
6818 NS->setImplicit();
6819 VaListDecl->setDeclContext(NS);
6820 }
6821
6822 VaListDecl->startDefinition();
6823
6824 // void * __ap;
6825 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6826 VaListDecl,
6827 SourceLocation(),
6828 SourceLocation(),
6829 &Context->Idents.get("__ap"),
6830 Context->getPointerType(Context->VoidTy),
6831 /*TInfo=*/nullptr,
6832 /*BitWidth=*/nullptr,
6833 /*Mutable=*/false,
6834 ICIS_NoInit);
6835 Field->setAccess(AS_public);
6836 VaListDecl->addDecl(Field);
6837
6838 // };
6839 VaListDecl->completeDefinition();
6840 Context->VaListTagDecl = VaListDecl;
6841
6842 // typedef struct __va_list __builtin_va_list;
6843 QualType T = Context->getRecordType(VaListDecl);
6844 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6845}
6846
6847static TypedefDecl *
6848CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6849 // struct __va_list_tag {
6850 RecordDecl *VaListTagDecl;
6851 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6852 VaListTagDecl->startDefinition();
6853
6854 const size_t NumFields = 4;
6855 QualType FieldTypes[NumFields];
6856 const char *FieldNames[NumFields];
6857
6858 // long __gpr;
6859 FieldTypes[0] = Context->LongTy;
6860 FieldNames[0] = "__gpr";
6861
6862 // long __fpr;
6863 FieldTypes[1] = Context->LongTy;
6864 FieldNames[1] = "__fpr";
6865
6866 // void *__overflow_arg_area;
6867 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6868 FieldNames[2] = "__overflow_arg_area";
6869
6870 // void *__reg_save_area;
6871 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6872 FieldNames[3] = "__reg_save_area";
6873
6874 // Create fields
6875 for (unsigned i = 0; i < NumFields; ++i) {
6876 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6877 VaListTagDecl,
6878 SourceLocation(),
6879 SourceLocation(),
6880 &Context->Idents.get(FieldNames[i]),
6881 FieldTypes[i], /*TInfo=*/nullptr,
6882 /*BitWidth=*/nullptr,
6883 /*Mutable=*/false,
6884 ICIS_NoInit);
6885 Field->setAccess(AS_public);
6886 VaListTagDecl->addDecl(Field);
6887 }
6888 VaListTagDecl->completeDefinition();
6889 Context->VaListTagDecl = VaListTagDecl;
6890 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6891
6892 // };
6893
6894 // typedef __va_list_tag __builtin_va_list[1];
6895 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6896 QualType VaListTagArrayType =
6897 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6898
6899 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6900}
6901
6902static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6903 TargetInfo::BuiltinVaListKind Kind) {
6904 switch (Kind) {
6905 case TargetInfo::CharPtrBuiltinVaList:
6906 return CreateCharPtrBuiltinVaListDecl(Context);
6907 case TargetInfo::VoidPtrBuiltinVaList:
6908 return CreateVoidPtrBuiltinVaListDecl(Context);
6909 case TargetInfo::AArch64ABIBuiltinVaList:
6910 return CreateAArch64ABIBuiltinVaListDecl(Context);
6911 case TargetInfo::PowerABIBuiltinVaList:
6912 return CreatePowerABIBuiltinVaListDecl(Context);
6913 case TargetInfo::X86_64ABIBuiltinVaList:
6914 return CreateX86_64ABIBuiltinVaListDecl(Context);
6915 case TargetInfo::PNaClABIBuiltinVaList:
6916 return CreatePNaClABIBuiltinVaListDecl(Context);
6917 case TargetInfo::AAPCSABIBuiltinVaList:
6918 return CreateAAPCSABIBuiltinVaListDecl(Context);
6919 case TargetInfo::SystemZBuiltinVaList:
6920 return CreateSystemZBuiltinVaListDecl(Context);
6921 }
6922
6923 llvm_unreachable("Unhandled __builtin_va_list type kind")::llvm::llvm_unreachable_internal("Unhandled __builtin_va_list type kind"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 6923)
;
6924}
6925
6926TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6927 if (!BuiltinVaListDecl) {
6928 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6929 assert(BuiltinVaListDecl->isImplicit())((BuiltinVaListDecl->isImplicit()) ? static_cast<void>
(0) : __assert_fail ("BuiltinVaListDecl->isImplicit()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 6929, __PRETTY_FUNCTION__))
;
6930 }
6931
6932 return BuiltinVaListDecl;
6933}
6934
6935Decl *ASTContext::getVaListTagDecl() const {
6936 // Force the creation of VaListTagDecl by building the __builtin_va_list
6937 // declaration.
6938 if (!VaListTagDecl)
6939 (void)getBuiltinVaListDecl();
6940
6941 return VaListTagDecl;
6942}
6943
6944TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6945 if (!BuiltinMSVaListDecl)
6946 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6947
6948 return BuiltinMSVaListDecl;
6949}
6950
6951void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6952 assert(ObjCConstantStringType.isNull() &&((ObjCConstantStringType.isNull() && "'NSConstantString' type already set!"
) ? static_cast<void> (0) : __assert_fail ("ObjCConstantStringType.isNull() && \"'NSConstantString' type already set!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 6953, __PRETTY_FUNCTION__))
6953 "'NSConstantString' type already set!")((ObjCConstantStringType.isNull() && "'NSConstantString' type already set!"
) ? static_cast<void> (0) : __assert_fail ("ObjCConstantStringType.isNull() && \"'NSConstantString' type already set!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 6953, __PRETTY_FUNCTION__))
;
6954
6955 ObjCConstantStringType = getObjCInterfaceType(Decl);
6956}
6957
6958/// \brief Retrieve the template name that corresponds to a non-empty
6959/// lookup.
6960TemplateName
6961ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6962 UnresolvedSetIterator End) const {
6963 unsigned size = End - Begin;
6964 assert(size > 1 && "set is not overloaded!")((size > 1 && "set is not overloaded!") ? static_cast
<void> (0) : __assert_fail ("size > 1 && \"set is not overloaded!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 6964, __PRETTY_FUNCTION__))
;
6965
6966 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6967 size * sizeof(FunctionTemplateDecl*));
6968 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6969
6970 NamedDecl **Storage = OT->getStorage();
6971 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6972 NamedDecl *D = *I;
6973 assert(isa<FunctionTemplateDecl>(D) ||((isa<FunctionTemplateDecl>(D) || (isa<UsingShadowDecl
>(D) && isa<FunctionTemplateDecl>(D->getUnderlyingDecl
()))) ? static_cast<void> (0) : __assert_fail ("isa<FunctionTemplateDecl>(D) || (isa<UsingShadowDecl>(D) && isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 6975, __PRETTY_FUNCTION__))
6974 (isa<UsingShadowDecl>(D) &&((isa<FunctionTemplateDecl>(D) || (isa<UsingShadowDecl
>(D) && isa<FunctionTemplateDecl>(D->getUnderlyingDecl
()))) ? static_cast<void> (0) : __assert_fail ("isa<FunctionTemplateDecl>(D) || (isa<UsingShadowDecl>(D) && isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 6975, __PRETTY_FUNCTION__))
6975 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())))((isa<FunctionTemplateDecl>(D) || (isa<UsingShadowDecl
>(D) && isa<FunctionTemplateDecl>(D->getUnderlyingDecl
()))) ? static_cast<void> (0) : __assert_fail ("isa<FunctionTemplateDecl>(D) || (isa<UsingShadowDecl>(D) && isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 6975, __PRETTY_FUNCTION__))
;
6976 *Storage++ = D;
6977 }
6978
6979 return TemplateName(OT);
6980}
6981
6982/// \brief Retrieve the template name that represents a qualified
6983/// template name such as \c std::vector.
6984TemplateName
6985ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6986 bool TemplateKeyword,
6987 TemplateDecl *Template) const {
6988 assert(NNS && "Missing nested-name-specifier in qualified template name")((NNS && "Missing nested-name-specifier in qualified template name"
) ? static_cast<void> (0) : __assert_fail ("NNS && \"Missing nested-name-specifier in qualified template name\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 6988, __PRETTY_FUNCTION__))
;
6989
6990 // FIXME: Canonicalization?
6991 llvm::FoldingSetNodeID ID;
6992 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6993
6994 void *InsertPos = nullptr;
6995 QualifiedTemplateName *QTN =
6996 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6997 if (!QTN) {
6998 QTN = new (*this, alignof(QualifiedTemplateName))
6999 QualifiedTemplateName(NNS, TemplateKeyword, Template);
7000 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7001 }
7002
7003 return TemplateName(QTN);
7004}
7005
7006/// \brief Retrieve the template name that represents a dependent
7007/// template name such as \c MetaFun::template apply.
7008TemplateName
7009ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7010 const IdentifierInfo *Name) const {
7011 assert((!NNS || NNS->isDependent()) &&(((!NNS || NNS->isDependent()) && "Nested name specifier must be dependent"
) ? static_cast<void> (0) : __assert_fail ("(!NNS || NNS->isDependent()) && \"Nested name specifier must be dependent\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 7012, __PRETTY_FUNCTION__))
7012 "Nested name specifier must be dependent")(((!NNS || NNS->isDependent()) && "Nested name specifier must be dependent"
) ? static_cast<void> (0) : __assert_fail ("(!NNS || NNS->isDependent()) && \"Nested name specifier must be dependent\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 7012, __PRETTY_FUNCTION__))
;
7013
7014 llvm::FoldingSetNodeID ID;
7015 DependentTemplateName::Profile(ID, NNS, Name);
7016
7017 void *InsertPos = nullptr;
7018 DependentTemplateName *QTN =
7019 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7020
7021 if (QTN)
7022 return TemplateName(QTN);
7023
7024 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7025 if (CanonNNS == NNS) {
7026 QTN = new (*this, alignof(DependentTemplateName))
7027 DependentTemplateName(NNS, Name);
7028 } else {
7029 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
7030 QTN = new (*this, alignof(DependentTemplateName))
7031 DependentTemplateName(NNS, Name, Canon);
7032 DependentTemplateName *CheckQTN =
7033 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7034 assert(!CheckQTN && "Dependent type name canonicalization broken")((!CheckQTN && "Dependent type name canonicalization broken"
) ? static_cast<void> (0) : __assert_fail ("!CheckQTN && \"Dependent type name canonicalization broken\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 7034, __PRETTY_FUNCTION__))
;
7035 (void)CheckQTN;
7036 }
7037
7038 DependentTemplateNames.InsertNode(QTN, InsertPos);
7039 return TemplateName(QTN);
7040}
7041
7042/// \brief Retrieve the template name that represents a dependent
7043/// template name such as \c MetaFun::template operator+.
7044TemplateName
7045ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7046 OverloadedOperatorKind Operator) const {
7047 assert((!NNS || NNS->isDependent()) &&(((!NNS || NNS->isDependent()) && "Nested name specifier must be dependent"
) ? static_cast<void> (0) : __assert_fail ("(!NNS || NNS->isDependent()) && \"Nested name specifier must be dependent\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 7048, __PRETTY_FUNCTION__))
7048 "Nested name specifier must be dependent")(((!NNS || NNS->isDependent()) && "Nested name specifier must be dependent"
) ? static_cast<void> (0) : __assert_fail ("(!NNS || NNS->isDependent()) && \"Nested name specifier must be dependent\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 7048, __PRETTY_FUNCTION__))
;
7049
7050 llvm::FoldingSetNodeID ID;
7051 DependentTemplateName::Profile(ID, NNS, Operator);
7052
7053 void *InsertPos = nullptr;
7054 DependentTemplateName *QTN
7055 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7056
7057 if (QTN)
7058 return TemplateName(QTN);
7059
7060 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7061 if (CanonNNS == NNS) {
7062 QTN = new (*this, alignof(DependentTemplateName))
7063 DependentTemplateName(NNS, Operator);
7064 } else {
7065 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
7066 QTN = new (*this, alignof(DependentTemplateName))
7067 DependentTemplateName(NNS, Operator, Canon);
7068
7069 DependentTemplateName *CheckQTN
7070 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7071 assert(!CheckQTN && "Dependent template name canonicalization broken")((!CheckQTN && "Dependent template name canonicalization broken"
) ? static_cast<void> (0) : __assert_fail ("!CheckQTN && \"Dependent template name canonicalization broken\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 7071, __PRETTY_FUNCTION__))
;
7072 (void)CheckQTN;
7073 }
7074
7075 DependentTemplateNames.InsertNode(QTN, InsertPos);
7076 return TemplateName(QTN);
7077}
7078
7079TemplateName
7080ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7081 TemplateName replacement) const {
7082 llvm::FoldingSetNodeID ID;
7083 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
7084
7085 void *insertPos = nullptr;
7086 SubstTemplateTemplateParmStorage *subst
7087 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7088
7089 if (!subst) {
7090 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7091 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7092 }
7093
7094 return TemplateName(subst);
7095}
7096
7097TemplateName
7098ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7099 const TemplateArgument &ArgPack) const {
7100 ASTContext &Self = const_cast<ASTContext &>(*this);
7101 llvm::FoldingSetNodeID ID;
7102 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
7103
7104 void *InsertPos = nullptr;
7105 SubstTemplateTemplateParmPackStorage *Subst
7106 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7107
7108 if (!Subst) {
7109 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
7110 ArgPack.pack_size(),
7111 ArgPack.pack_begin());
7112 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7113 }
7114
7115 return TemplateName(Subst);
7116}
7117
7118/// getFromTargetType - Given one of the integer types provided by
7119/// TargetInfo, produce the corresponding type. The unsigned @p Type
7120/// is actually a value of type @c TargetInfo::IntType.
7121CanQualType ASTContext::getFromTargetType(unsigned Type) const {
7122 switch (Type) {
7123 case TargetInfo::NoInt: return CanQualType();
7124 case TargetInfo::SignedChar: return SignedCharTy;
7125 case TargetInfo::UnsignedChar: return UnsignedCharTy;
7126 case TargetInfo::SignedShort: return ShortTy;
7127 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7128 case TargetInfo::SignedInt: return IntTy;
7129 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7130 case TargetInfo::SignedLong: return LongTy;
7131 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7132 case TargetInfo::SignedLongLong: return LongLongTy;
7133 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7134 }
7135
7136 llvm_unreachable("Unhandled TargetInfo::IntType value")::llvm::llvm_unreachable_internal("Unhandled TargetInfo::IntType value"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 7136)
;
7137}
7138
7139//===----------------------------------------------------------------------===//
7140// Type Predicates.
7141//===----------------------------------------------------------------------===//
7142
7143/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7144/// garbage collection attribute.
7145///
7146Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
7147 if (getLangOpts().getGC() == LangOptions::NonGC)
7148 return Qualifiers::GCNone;
7149
7150 assert(getLangOpts().ObjC1)((getLangOpts().ObjC1) ? static_cast<void> (0) : __assert_fail
("getLangOpts().ObjC1", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 7150, __PRETTY_FUNCTION__))
;
7151 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7152
7153 // Default behaviour under objective-C's gc is for ObjC pointers
7154 // (or pointers to them) be treated as though they were declared
7155 // as __strong.
7156 if (GCAttrs == Qualifiers::GCNone) {
7157 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7158 return Qualifiers::Strong;
7159 else if (Ty->isPointerType())
7160 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7161 } else {
7162 // It's not valid to set GC attributes on anything that isn't a
7163 // pointer.
7164#ifndef NDEBUG
7165 QualType CT = Ty->getCanonicalTypeInternal();
7166 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7167 CT = AT->getElementType();
7168 assert(CT->isAnyPointerType() || CT->isBlockPointerType())((CT->isAnyPointerType() || CT->isBlockPointerType()) ?
static_cast<void> (0) : __assert_fail ("CT->isAnyPointerType() || CT->isBlockPointerType()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 7168, __PRETTY_FUNCTION__))
;
7169#endif
7170 }
7171 return GCAttrs;
7172}
7173
7174//===----------------------------------------------------------------------===//
7175// Type Compatibility Testing
7176//===----------------------------------------------------------------------===//
7177
7178/// areCompatVectorTypes - Return true if the two specified vector types are
7179/// compatible.
7180static bool areCompatVectorTypes(const VectorType *LHS,
7181 const VectorType *RHS) {
7182 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified())((LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified
()) ? static_cast<void> (0) : __assert_fail ("LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 7182, __PRETTY_FUNCTION__))
;
7183 return LHS->getElementType() == RHS->getElementType() &&
7184 LHS->getNumElements() == RHS->getNumElements();
7185}
7186
7187bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7188 QualType SecondVec) {
7189 assert(FirstVec->isVectorType() && "FirstVec should be a vector type")((FirstVec->isVectorType() && "FirstVec should be a vector type"
) ? static_cast<void> (0) : __assert_fail ("FirstVec->isVectorType() && \"FirstVec should be a vector type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 7189, __PRETTY_FUNCTION__))
;
7190 assert(SecondVec->isVectorType() && "SecondVec should be a vector type")((SecondVec->isVectorType() && "SecondVec should be a vector type"
) ? static_cast<void> (0) : __assert_fail ("SecondVec->isVectorType() && \"SecondVec should be a vector type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 7190, __PRETTY_FUNCTION__))
;
7191
7192 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7193 return true;
7194
7195 // Treat Neon vector types and most AltiVec vector types as if they are the
7196 // equivalent GCC vector types.
7197 const VectorType *First = FirstVec->getAs<VectorType>();
7198 const VectorType *Second = SecondVec->getAs<VectorType>();
7199 if (First->getNumElements() == Second->getNumElements() &&
7200 hasSameType(First->getElementType(), Second->getElementType()) &&
7201 First->getVectorKind() != VectorType::AltiVecPixel &&
7202 First->getVectorKind() != VectorType::AltiVecBool &&
7203 Second->getVectorKind() != VectorType::AltiVecPixel &&
7204 Second->getVectorKind() != VectorType::AltiVecBool)
7205 return true;
7206
7207 return false;
7208}
7209
7210//===----------------------------------------------------------------------===//
7211// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7212//===----------------------------------------------------------------------===//
7213
7214/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7215/// inheritance hierarchy of 'rProto'.
7216bool
7217ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7218 ObjCProtocolDecl *rProto) const {
7219 if (declaresSameEntity(lProto, rProto))
7220 return true;
7221 for (auto *PI : rProto->protocols())
7222 if (ProtocolCompatibleWithProtocol(lProto, PI))
7223 return true;
7224 return false;
7225}
7226
7227/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7228/// Class<pr1, ...>.
7229bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7230 QualType rhs) {
7231 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7232 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7233 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible")(((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible"
) ? static_cast<void> (0) : __assert_fail ("(lhsQID && rhsOPT) && \"ObjCQualifiedClassTypesAreCompatible\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 7233, __PRETTY_FUNCTION__))
;
7234
7235 for (auto *lhsProto : lhsQID->quals()) {
7236 bool match = false;
7237 for (auto *rhsProto : rhsOPT->quals()) {
7238 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7239 match = true;
7240 break;
7241 }
7242 }
7243 if (!match)
7244 return false;
7245 }
7246 return true;
7247}
7248
7249/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7250/// ObjCQualifiedIDType.
7251bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7252 bool compare) {
7253 // Allow id<P..> and an 'id' or void* type in all cases.
7254 if (lhs->isVoidPointerType() ||
7255 lhs->isObjCIdType() || lhs->isObjCClassType())
7256 return true;
7257 else if (rhs->isVoidPointerType() ||
7258 rhs->isObjCIdType() || rhs->isObjCClassType())
7259 return true;
7260
7261 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
7262 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7263
7264 if (!rhsOPT) return false;
7265
7266 if (rhsOPT->qual_empty()) {
7267 // If the RHS is a unqualified interface pointer "NSString*",
7268 // make sure we check the class hierarchy.
7269 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
7270 for (auto *I : lhsQID->quals()) {
7271 // when comparing an id<P> on lhs with a static type on rhs,
7272 // see if static class implements all of id's protocols, directly or
7273 // through its super class and categories.
7274 if (!rhsID->ClassImplementsProtocol(I, true))
7275 return false;
7276 }
7277 }
7278 // If there are no qualifiers and no interface, we have an 'id'.
7279 return true;
7280 }
7281 // Both the right and left sides have qualifiers.
7282 for (auto *lhsProto : lhsQID->quals()) {
7283 bool match = false;
7284
7285 // when comparing an id<P> on lhs with a static type on rhs,
7286 // see if static class implements all of id's protocols, directly or
7287 // through its super class and categories.
7288 for (auto *rhsProto : rhsOPT->quals()) {
7289 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7290 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7291 match = true;
7292 break;
7293 }
7294 }
7295 // If the RHS is a qualified interface pointer "NSString<P>*",
7296 // make sure we check the class hierarchy.
7297 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
7298 for (auto *I : lhsQID->quals()) {
7299 // when comparing an id<P> on lhs with a static type on rhs,
7300 // see if static class implements all of id's protocols, directly or
7301 // through its super class and categories.
7302 if (rhsID->ClassImplementsProtocol(I, true)) {
7303 match = true;
7304 break;
7305 }
7306 }
7307 }
7308 if (!match)
7309 return false;
7310 }
7311
7312 return true;
7313 }
7314
7315 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7316 assert(rhsQID && "One of the LHS/RHS should be id<x>")((rhsQID && "One of the LHS/RHS should be id<x>"
) ? static_cast<void> (0) : __assert_fail ("rhsQID && \"One of the LHS/RHS should be id<x>\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 7316, __PRETTY_FUNCTION__))
;
7317
7318 if (const ObjCObjectPointerType *lhsOPT =
7319 lhs->getAsObjCInterfacePointerType()) {
7320 // If both the right and left sides have qualifiers.
7321 for (auto *lhsProto : lhsOPT->quals()) {
7322 bool match = false;
7323
7324 // when comparing an id<P> on rhs with a static type on lhs,
7325 // see if static class implements all of id's protocols, directly or
7326 // through its super class and categories.
7327 // First, lhs protocols in the qualifier list must be found, direct
7328 // or indirect in rhs's qualifier list or it is a mismatch.
7329 for (auto *rhsProto : rhsQID->quals()) {
7330 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7331 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7332 match = true;
7333 break;
7334 }
7335 }
7336 if (!match)
7337 return false;
7338 }
7339
7340 // Static class's protocols, or its super class or category protocols
7341 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7342 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7343 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7344 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7345 // This is rather dubious but matches gcc's behavior. If lhs has
7346 // no type qualifier and its class has no static protocol(s)
7347 // assume that it is mismatch.
7348 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7349 return false;
7350 for (auto *lhsProto : LHSInheritedProtocols) {
7351 bool match = false;
7352 for (auto *rhsProto : rhsQID->quals()) {
7353 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7354 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7355 match = true;
7356 break;
7357 }
7358 }
7359 if (!match)
7360 return false;
7361 }
7362 }
7363 return true;
7364 }
7365 return false;
7366}
7367
7368/// canAssignObjCInterfaces - Return true if the two interface types are
7369/// compatible for assignment from RHS to LHS. This handles validation of any
7370/// protocol qualifiers on the LHS or RHS.
7371///
7372bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7373 const ObjCObjectPointerType *RHSOPT) {
7374 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7375 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7376
7377 // If either type represents the built-in 'id' or 'Class' types, return true.
7378 if (LHS->isObjCUnqualifiedIdOrClass() ||
7379 RHS->isObjCUnqualifiedIdOrClass())
7380 return true;
7381
7382 // Function object that propagates a successful result or handles
7383 // __kindof types.
7384 auto finish = [&](bool succeeded) -> bool {
7385 if (succeeded)
7386 return true;
7387
7388 if (!RHS->isKindOfType())
7389 return false;
7390
7391 // Strip off __kindof and protocol qualifiers, then check whether
7392 // we can assign the other way.
7393 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7394 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7395 };
7396
7397 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7398 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7399 QualType(RHSOPT,0),
7400 false));
7401 }
7402
7403 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7404 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7405 QualType(RHSOPT,0)));
7406 }
7407
7408 // If we have 2 user-defined types, fall into that path.
7409 if (LHS->getInterface() && RHS->getInterface()) {
7410 return finish(canAssignObjCInterfaces(LHS, RHS));
7411 }
7412
7413 return false;
7414}
7415
7416/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
7417/// for providing type-safety for objective-c pointers used to pass/return
7418/// arguments in block literals. When passed as arguments, passing 'A*' where
7419/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7420/// not OK. For the return type, the opposite is not OK.
7421bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7422 const ObjCObjectPointerType *LHSOPT,
7423 const ObjCObjectPointerType *RHSOPT,
7424 bool BlockReturnType) {
7425
7426 // Function object that propagates a successful result or handles
7427 // __kindof types.
7428 auto finish = [&](bool succeeded) -> bool {
7429 if (succeeded)
7430 return true;
7431
7432 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7433 if (!Expected->isKindOfType())
7434 return false;
7435
7436 // Strip off __kindof and protocol qualifiers, then check whether
7437 // we can assign the other way.
7438 return canAssignObjCInterfacesInBlockPointer(
7439 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7440 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7441 BlockReturnType);
7442 };
7443
7444 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
7445 return true;
7446
7447 if (LHSOPT->isObjCBuiltinType()) {
7448 return finish(RHSOPT->isObjCBuiltinType() ||
7449 RHSOPT->isObjCQualifiedIdType());
7450 }
7451
7452 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
7453 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7454 QualType(RHSOPT,0),
7455 false));
7456
7457 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7458 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7459 if (LHS && RHS) { // We have 2 user-defined types.
7460 if (LHS != RHS) {
7461 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
7462 return finish(BlockReturnType);
7463 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
7464 return finish(!BlockReturnType);
7465 }
7466 else
7467 return true;
7468 }
7469 return false;
7470}
7471
7472/// Comparison routine for Objective-C protocols to be used with
7473/// llvm::array_pod_sort.
7474static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7475 ObjCProtocolDecl * const *rhs) {
7476 return (*lhs)->getName().compare((*rhs)->getName());
7477
7478}
7479
7480/// getIntersectionOfProtocols - This routine finds the intersection of set
7481/// of protocols inherited from two distinct objective-c pointer objects with
7482/// the given common base.
7483/// It is used to build composite qualifier list of the composite type of
7484/// the conditional expression involving two objective-c pointer objects.
7485static
7486void getIntersectionOfProtocols(ASTContext &Context,
7487 const ObjCInterfaceDecl *CommonBase,
7488 const ObjCObjectPointerType *LHSOPT,
7489 const ObjCObjectPointerType *RHSOPT,
7490 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
7491
7492 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7493 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7494 assert(LHS->getInterface() && "LHS must have an interface base")((LHS->getInterface() && "LHS must have an interface base"
) ? static_cast<void> (0) : __assert_fail ("LHS->getInterface() && \"LHS must have an interface base\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 7494, __PRETTY_FUNCTION__))
;
7495 assert(RHS->getInterface() && "RHS must have an interface base")((RHS->getInterface() && "RHS must have an interface base"
) ? static_cast<void> (0) : __assert_fail ("RHS->getInterface() && \"RHS must have an interface base\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/AST/ASTContext.cpp"
, 7495, __PRETTY_FUNCTION__))
;
7496
7497 // Add all of the protocols for the LHS.
7498 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7499
7500 // Start with the protocol qualifiers.
7501 for (auto proto : LHS->quals()) {
7502 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
7503 }
7504
7505 // Also add the protocols associated with the LHS interface.
7506 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7507
7508 // Add all of the protocls for the RHS.
7509 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7510
7511 // Start with the protocol qualifiers.
7512 for (auto proto : RHS->quals()) {
7513 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
7514 }
7515
7516 // Also add the protocols associated with the RHS interface.
7517 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7518
7519 // Compute the intersection of the collected protocol sets.
7520 for (auto proto : LHSProtocolSet) {
7521 if (RHSProtocolSet.count(proto))
7522 IntersectionSet.push_back(proto);
7523 }
7524
7525 // Compute the set of protocols that is implied by either the common type or
7526 // the protocols within the intersection.
7527 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7528 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7529
7530 // Remove any implied protocols from the list of inherited protocols.
7531 if (!ImpliedProtocols.empty()) {
7532 IntersectionSet.erase(
7533 std::remove_if(IntersectionSet.begin(),
7534 IntersectionSet.end(),
7535 [&](ObjCProtocolDecl *proto) -> bool {
7536 return ImpliedProtocols.count(proto) > 0;
7537 }),
7538 IntersectionSet.end());
7539 }
7540
7541 // Sort the remaining protocols by name.
7542 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7543 compareObjCProtocolsByName);
7544}
7545
7546/// Determine whether the first type is a subtype of the second.
7547static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7548 QualType rhs) {
7549 // Common case: two object pointers.
7550 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7551 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7552 if (lhsOPT && rhsOPT)
7553 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7554
7555 // Two block pointers.
7556 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7557 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7558 if (lhsBlock && rhsBlock)
7559 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7560
7561 // If either is an unqualified 'id' and the other is a block, it's
7562 // acceptable.
7563 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7564 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7565 return true;
7566
7567 return false;
7568}
7569
7570// Check that the given Objective-C type argument lists are equivalent.
7571static bool sameObjCTypeArgs(ASTContext &ctx,
7572 const ObjCInterfaceDecl *iface,
7573 ArrayRef<QualType> lhsArgs,
7574 ArrayRef<QualType> rhsArgs,
7575 bool stripKindOf) {
7576 if (lhsArgs.size() != rhsArgs.size())
7577 return false;
7578
7579 ObjCTypeParamList *typeParams = iface->getTypeParamList();
7580 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
7581 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7582 continue;
7583
7584 switch (typeParams->begin()[i]->getVariance()) {
7585 case ObjCTypeParamVariance::Invariant:
7586 if (!stripKindOf ||
7587 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7588 rhsArgs[i].stripObjCKindOfType(ctx))) {
7589 return false;
7590 }
7591 break;
7592
7593 case ObjCTypeParamVariance::Covariant:
7594 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7595 return false;
7596 break;
7597
7598 case ObjCTypeParamVariance::Contravariant:
7599 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7600 return false;
7601 break;
7602 }
7603 }
7604
7605 return true;
7606}
7607
7608QualType ASTContext::areCommonBaseCompatible(
7609 const ObjCObjectPointerType *Lptr,
7610 const ObjCObjectPointerType *Rptr) {
7611 const ObjCObjectType *LHS = Lptr->getObjectType();
7612 const ObjCObjectType *RHS = Rptr->getObjectType();
7613 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7614 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
7615
7616 if (!LDecl || !RDecl)
7617 return QualType();
7618
7619 // When either LHS or RHS is a kindof type, we should return a kindof type.
7620 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7621 // kindof(A).
7622 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7623
7624 // Follow the left-hand side up the class hierarchy until we either hit a
7625 // root or find the RHS. Record the ancestors in case we don't find it.
7626 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7627 LHSAncestors;
7628 while (true) {
7629 // Record this ancestor. We'll need this if the common type isn't in the
7630 // path from the LHS to the root.
7631 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
7632
7633 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7634 // Get the type arguments.
7635 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7636 bool anyChanges = false;
7637 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7638 // Both have type arguments, compare them.
7639 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7640 LHS->getTypeArgs(), RHS->getTypeArgs(),
7641 /*stripKindOf=*/true))
7642 return QualType();
7643 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7644 // If only one has type arguments, the result will not have type
7645 // arguments.
7646 LHSTypeArgs = { };
7647 anyChanges = true;
7648 }
7649
7650 // Compute the intersection of protocols.
7651 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7652 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7653 Protocols);
7654 if (!Protocols.empty())
7655 anyChanges = true;
7656