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