blob: 1d103f11296103cce26ce25966867b56134acc5e [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000028#include "clang/AST/RecordLayout.h"
29#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000031#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000032#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000033#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000034#include "llvm/ADT/StringExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000035#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000036#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000037#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000038#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000039
Chris Lattnerddc135e2006-11-10 06:34:16 +000040using namespace clang;
41
Douglas Gregor9672f922010-07-03 00:47:00 +000042unsigned ASTContext::NumImplicitDefaultConstructors;
43unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000044unsigned ASTContext::NumImplicitCopyConstructors;
45unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveConstructors;
47unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000048unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000052unsigned ASTContext::NumImplicitDestructors;
53unsigned ASTContext::NumImplicitDestructorsDeclared;
54
Steve Naroff0af91202007-04-27 21:51:21 +000055enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000056 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000057};
58
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000059RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000060 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
63 }
64
65 assert(D);
66
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000067 // User can not attach documentation to implicit declarations.
68 if (D->isImplicit())
69 return NULL;
70
Dmitri Gribenkob2610882012-08-14 17:17:18 +000071 // 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
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000077 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 EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
89 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
90 return NULL;
91 }
92
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000093 // TODO: handle comments for function parameters properly.
94 if (isa<ParmVarDecl>(D))
95 return NULL;
96
Dmitri Gribenko34df2202012-07-31 22:37:06 +000097 // TODO: we could look up template parameter documentation in the template
98 // documentation.
99 if (isa<TemplateTypeParmDecl>(D) ||
100 isa<NonTypeTemplateParmDecl>(D) ||
101 isa<TemplateTemplateParmDecl>(D))
102 return NULL;
103
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000104 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000105
106 // If there are no comments anywhere, we won't find anything.
107 if (RawComments.empty())
108 return NULL;
109
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000110 // Find declaration location.
111 // For Objective-C declarations we generally don't expect to have multiple
112 // declarators, thus use declaration starting location as the "declaration
113 // location".
114 // For all other declarations multiple declarators are used quite frequently,
115 // so we use the location of the identifier as the "declaration location".
116 SourceLocation DeclLoc;
117 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000118 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000119 isa<RedeclarableTemplateDecl>(D) ||
120 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000121 DeclLoc = D->getLocStart();
122 else
123 DeclLoc = D->getLocation();
124
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000125 // If the declaration doesn't map directly to a location in a file, we
126 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000127 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
128 return NULL;
129
130 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000131 ArrayRef<RawComment *>::iterator Comment;
132 {
133 // When searching for comments during parsing, the comment we are looking
134 // for is usually among the last two comments we parsed -- check them
135 // first.
136 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
137 BeforeThanCompare<RawComment> Compare(SourceMgr);
138 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
139 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
140 if (!Found && RawComments.size() >= 2) {
141 MaybeBeforeDecl--;
142 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
143 }
144
145 if (Found) {
146 Comment = MaybeBeforeDecl + 1;
147 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
148 &CommentAtDeclLoc, Compare));
149 } else {
150 // Slow path.
151 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
152 &CommentAtDeclLoc, Compare);
153 }
154 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000155
156 // Decompose the location for the declaration and find the beginning of the
157 // file buffer.
158 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
159
160 // First check whether we have a trailing comment.
161 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000162 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000163 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000164 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000165 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000166 // Check that Doxygen trailing comment comes after the declaration, starts
167 // on the same line and in the same file as the declaration.
168 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
169 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
170 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
171 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000172 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000173 }
174 }
175
176 // The comment just after the declaration was not a trailing comment.
177 // Let's look at the previous comment.
178 if (Comment == RawComments.begin())
179 return NULL;
180 --Comment;
181
182 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000183 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000184 return NULL;
185
186 // Decompose the end of the comment.
187 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000188 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000189
190 // If the comment and the declaration aren't in the same file, then they
191 // aren't related.
192 if (DeclLocDecomp.first != CommentEndDecomp.first)
193 return NULL;
194
195 // Get the corresponding buffer.
196 bool Invalid = false;
197 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
198 &Invalid).data();
199 if (Invalid)
200 return NULL;
201
202 // Extract text between the comment and declaration.
203 StringRef Text(Buffer + CommentEndDecomp.second,
204 DeclLocDecomp.second - CommentEndDecomp.second);
205
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000206 // There should be no other declarations or preprocessor directives between
207 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000208 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 return NULL;
210
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000211 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000212}
213
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000214namespace {
215/// If we have a 'templated' declaration for a template, adjust 'D' to
216/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000217/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000218const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000219 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000220 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000221 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000222 return FTD;
223
224 // Nothing to do if function is not an implicit instantiation.
225 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
226 return D;
227
228 // Function is an implicit instantiation of a function template?
229 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
230 return FTD;
231
232 // Function is instantiated from a member definition of a class template?
233 if (const FunctionDecl *MemberDecl =
234 FD->getInstantiatedFromMemberFunction())
235 return MemberDecl;
236
237 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000238 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000239 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
240 // Static data member is instantiated from a member definition of a class
241 // template?
242 if (VD->isStaticDataMember())
243 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
244 return MemberDecl;
245
246 return D;
247 }
248 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
249 // Is this class declaration part of a class template?
250 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
251 return CTD;
252
253 // Class is an implicit instantiation of a class template or partial
254 // specialization?
255 if (const ClassTemplateSpecializationDecl *CTSD =
256 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
257 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
258 return D;
259 llvm::PointerUnion<ClassTemplateDecl *,
260 ClassTemplatePartialSpecializationDecl *>
261 PU = CTSD->getSpecializedTemplateOrPartial();
262 return PU.is<ClassTemplateDecl*>() ?
263 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
264 static_cast<const Decl*>(
265 PU.get<ClassTemplatePartialSpecializationDecl *>());
266 }
267
268 // Class is instantiated from a member definition of a class template?
269 if (const MemberSpecializationInfo *Info =
270 CRD->getMemberSpecializationInfo())
271 return Info->getInstantiatedFrom();
272
273 return D;
274 }
275 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
276 // Enum is instantiated from a member definition of a class template?
277 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
278 return MemberDecl;
279
280 return D;
281 }
282 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000283 return D;
284}
285} // unnamed namespace
286
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000287const RawComment *ASTContext::getRawCommentForAnyRedecl(
288 const Decl *D,
289 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000290 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000291
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000292 // Check whether we have cached a comment for this declaration already.
293 {
294 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
295 RedeclComments.find(D);
296 if (Pos != RedeclComments.end()) {
297 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000298 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
299 if (OriginalDecl)
300 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000301 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000302 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000303 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000304 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000305
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000306 // Search for comments attached to declarations in the redeclaration chain.
307 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000308 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000309 for (Decl::redecl_iterator I = D->redecls_begin(),
310 E = D->redecls_end();
311 I != E; ++I) {
312 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
313 RedeclComments.find(*I);
314 if (Pos != RedeclComments.end()) {
315 const RawCommentAndCacheFlags &Raw = Pos->second;
316 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
317 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000318 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000319 break;
320 }
321 } else {
322 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000323 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000324 RawCommentAndCacheFlags Raw;
325 if (RC) {
326 Raw.setRaw(RC);
327 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
328 } else
329 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000330 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000331 RedeclComments[*I] = Raw;
332 if (RC)
333 break;
334 }
335 }
336
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000337 // If we found a comment, it should be a documentation comment.
338 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000339
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000340 if (OriginalDecl)
341 *OriginalDecl = OriginalDeclForRC;
342
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000343 // Update cache for every declaration in the redeclaration chain.
344 RawCommentAndCacheFlags Raw;
345 Raw.setRaw(RC);
346 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348
349 for (Decl::redecl_iterator I = D->redecls_begin(),
350 E = D->redecls_end();
351 I != E; ++I) {
352 RawCommentAndCacheFlags &R = RedeclComments[*I];
353 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
354 R = Raw;
355 }
356
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000357 return RC;
358}
359
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000360static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
361 SmallVectorImpl<const NamedDecl *> &Redeclared) {
362 const DeclContext *DC = ObjCMethod->getDeclContext();
363 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
364 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
365 if (!ID)
366 return;
367 // Add redeclared method here.
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000368 for (ObjCInterfaceDecl::known_extensions_iterator
369 Ext = ID->known_extensions_begin(),
370 ExtEnd = ID->known_extensions_end();
371 Ext != ExtEnd; ++Ext) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000372 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000373 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000374 ObjCMethod->isInstanceMethod()))
375 Redeclared.push_back(RedeclaredMethod);
376 }
377 }
378}
379
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000380comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
381 const Decl *D) const {
382 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
383 ThisDeclInfo->CommentDecl = D;
384 ThisDeclInfo->IsFilled = false;
385 ThisDeclInfo->fill();
386 ThisDeclInfo->CommentDecl = FC->getDecl();
387 comments::FullComment *CFC =
388 new (*this) comments::FullComment(FC->getBlocks(),
389 ThisDeclInfo);
390 return CFC;
391
392}
393
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000394comments::FullComment *ASTContext::getCommentForDecl(
395 const Decl *D,
396 const Preprocessor *PP) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000397 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000398
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000399 const Decl *Canonical = D->getCanonicalDecl();
400 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
401 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000402
403 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000404 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000405 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000406 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000407 return CFC;
408 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000409 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000410 }
411
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000412 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000413
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000414 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000415 if (!RC) {
416 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000417 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000418 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000419 if (OMD && OMD->isPropertyAccessor())
420 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
421 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
422 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000423 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000424 addRedeclaredMethods(OMD, Overridden);
425 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000426 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
427 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
428 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000429 }
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000430 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000431 // Attach enum's documentation to its typedef if latter
432 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000433 QualType QT = TD->getUnderlyingType();
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000434 if (const EnumType *ET = QT->getAs<EnumType>())
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000435 if (const EnumDecl *ED = ET->getDecl())
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000436 if (comments::FullComment *FC = getCommentForDecl(ED, PP))
437 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000438 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000439 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000440 }
441
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000442 // If the RawComment was attached to other redeclaration of this Decl, we
443 // should parse the comment in context of that other Decl. This is important
444 // because comments can contain references to parameter names which can be
445 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000446 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000447 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000448
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000449 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000450 ParsedComments[Canonical] = FC;
451 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000452}
453
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000454void
455ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
456 TemplateTemplateParmDecl *Parm) {
457 ID.AddInteger(Parm->getDepth());
458 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000459 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000460
461 TemplateParameterList *Params = Parm->getTemplateParameters();
462 ID.AddInteger(Params->size());
463 for (TemplateParameterList::const_iterator P = Params->begin(),
464 PEnd = Params->end();
465 P != PEnd; ++P) {
466 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
467 ID.AddInteger(0);
468 ID.AddBoolean(TTP->isParameterPack());
469 continue;
470 }
471
472 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
473 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000474 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000475 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000476 if (NTTP->isExpandedParameterPack()) {
477 ID.AddBoolean(true);
478 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000479 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
480 QualType T = NTTP->getExpansionType(I);
481 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
482 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000483 } else
484 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000485 continue;
486 }
487
488 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
489 ID.AddInteger(2);
490 Profile(ID, TTP);
491 }
492}
493
494TemplateTemplateParmDecl *
495ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000496 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000497 // Check if we already have a canonical template template parameter.
498 llvm::FoldingSetNodeID ID;
499 CanonicalTemplateTemplateParm::Profile(ID, TTP);
500 void *InsertPos = 0;
501 CanonicalTemplateTemplateParm *Canonical
502 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
503 if (Canonical)
504 return Canonical->getParam();
505
506 // Build a canonical template parameter list.
507 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000508 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000509 CanonParams.reserve(Params->size());
510 for (TemplateParameterList::const_iterator P = Params->begin(),
511 PEnd = Params->end();
512 P != PEnd; ++P) {
513 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
514 CanonParams.push_back(
515 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000516 SourceLocation(),
517 SourceLocation(),
518 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000519 TTP->getIndex(), 0, false,
520 TTP->isParameterPack()));
521 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000522 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
523 QualType T = getCanonicalType(NTTP->getType());
524 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
525 NonTypeTemplateParmDecl *Param;
526 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000527 SmallVector<QualType, 2> ExpandedTypes;
528 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000529 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
530 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
531 ExpandedTInfos.push_back(
532 getTrivialTypeSourceInfo(ExpandedTypes.back()));
533 }
534
535 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000536 SourceLocation(),
537 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000538 NTTP->getDepth(),
539 NTTP->getPosition(), 0,
540 T,
541 TInfo,
542 ExpandedTypes.data(),
543 ExpandedTypes.size(),
544 ExpandedTInfos.data());
545 } else {
546 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000547 SourceLocation(),
548 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000549 NTTP->getDepth(),
550 NTTP->getPosition(), 0,
551 T,
552 NTTP->isParameterPack(),
553 TInfo);
554 }
555 CanonParams.push_back(Param);
556
557 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000558 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
559 cast<TemplateTemplateParmDecl>(*P)));
560 }
561
562 TemplateTemplateParmDecl *CanonTTP
563 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
564 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000565 TTP->getPosition(),
566 TTP->isParameterPack(),
567 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000568 TemplateParameterList::Create(*this, SourceLocation(),
569 SourceLocation(),
570 CanonParams.data(),
571 CanonParams.size(),
572 SourceLocation()));
573
574 // Get the new insert position for the node we care about.
575 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
576 assert(Canonical == 0 && "Shouldn't be in the map!");
577 (void)Canonical;
578
579 // Create the canonical template template parameter entry.
580 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
581 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
582 return CanonTTP;
583}
584
Charles Davis53c59df2010-08-16 03:33:14 +0000585CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000586 if (!LangOpts.CPlusPlus) return 0;
587
John McCall359b8852013-01-25 22:30:49 +0000588 switch (T.getCXXABI().getKind()) {
589 case TargetCXXABI::GenericARM:
590 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000591 return CreateARMCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000592 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000593 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000594 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000595 return CreateMicrosoftCXXABI(*this);
596 }
David Blaikie8a40f702012-01-17 06:56:22 +0000597 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000598}
599
Douglas Gregore8bbc122011-09-02 00:18:52 +0000600static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000601 const LangOptions &LOpts) {
602 if (LOpts.FakeAddressSpaceMap) {
603 // The fake address space map must have a distinct entry for each
604 // language-specific address space.
605 static const unsigned FakeAddrSpaceMap[] = {
606 1, // opencl_global
607 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000608 3, // opencl_constant
609 4, // cuda_device
610 5, // cuda_constant
611 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000612 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000613 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000614 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000615 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000616 }
617}
618
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000619ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000620 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000621 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000622 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000623 unsigned size_reserve,
624 bool DelayInitialization)
625 : FunctionProtoTypes(this_()),
626 TemplateSpecializationTypes(this_()),
627 DependentTemplateSpecializationTypes(this_()),
628 SubstTemplateTemplateParmPacks(this_()),
629 GlobalNestedNameSpecifier(0),
630 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000631 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000632 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000633 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000634 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000635 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000636 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
637 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
638 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000639 NullTypeSourceInfo(QualType()),
640 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000641 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000642 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000643 Idents(idents), Selectors(sels),
644 BuiltinInfo(builtins),
645 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000646 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000647 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000648 CommentCommandTraits(BumpAlloc),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000649 LastSDM(0, 0),
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000650 UniqueBlockByRefTypeID(0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000651{
Mike Stump11289f42009-09-09 15:08:12 +0000652 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000653 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000654
655 if (!DelayInitialization) {
656 assert(t && "No target supplied for ASTContext initialization");
657 InitBuiltinTypes(*t);
658 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000659}
660
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000661ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000662 // Release the DenseMaps associated with DeclContext objects.
663 // FIXME: Is this the ideal solution?
664 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000665
Douglas Gregor5b11d492010-07-25 17:53:33 +0000666 // Call all of the deallocation functions.
667 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
668 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000669
Ted Kremenek076baeb2010-06-08 23:00:58 +0000670 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000671 // because they can contain DenseMaps.
672 for (llvm::DenseMap<const ObjCContainerDecl*,
673 const ASTRecordLayout*>::iterator
674 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
675 // Increment in loop to prevent using deallocated memory.
676 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
677 R->Destroy(*this);
678
Ted Kremenek076baeb2010-06-08 23:00:58 +0000679 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
680 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
681 // Increment in loop to prevent using deallocated memory.
682 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
683 R->Destroy(*this);
684 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000685
686 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
687 AEnd = DeclAttrs.end();
688 A != AEnd; ++A)
689 A->second->~AttrVec();
690}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000691
Douglas Gregor1a809332010-05-23 18:26:36 +0000692void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
693 Deallocations.push_back(std::make_pair(Callback, Data));
694}
695
Mike Stump11289f42009-09-09 15:08:12 +0000696void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000697ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000698 ExternalSource.reset(Source.take());
699}
700
Chris Lattner4eb445d2007-01-26 01:27:23 +0000701void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000702 llvm::errs() << "\n*** AST Context Stats:\n";
703 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000704
Douglas Gregora30d0462009-05-26 14:40:08 +0000705 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000706#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000707#define ABSTRACT_TYPE(Name, Parent)
708#include "clang/AST/TypeNodes.def"
709 0 // Extra
710 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000711
Chris Lattner4eb445d2007-01-26 01:27:23 +0000712 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
713 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000714 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000715 }
716
Douglas Gregora30d0462009-05-26 14:40:08 +0000717 unsigned Idx = 0;
718 unsigned TotalBytes = 0;
719#define TYPE(Name, Parent) \
720 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000721 llvm::errs() << " " << counts[Idx] << " " << #Name \
722 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000723 TotalBytes += counts[Idx] * sizeof(Name##Type); \
724 ++Idx;
725#define ABSTRACT_TYPE(Name, Parent)
726#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000727
Chandler Carruth3c147a72011-07-04 05:32:14 +0000728 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
729
Douglas Gregor7454c562010-07-02 20:37:36 +0000730 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000731 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
732 << NumImplicitDefaultConstructors
733 << " implicit default constructors created\n";
734 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
735 << NumImplicitCopyConstructors
736 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000737 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000738 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
739 << NumImplicitMoveConstructors
740 << " implicit move constructors created\n";
741 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
742 << NumImplicitCopyAssignmentOperators
743 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000744 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000745 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
746 << NumImplicitMoveAssignmentOperators
747 << " implicit move assignment operators created\n";
748 llvm::errs() << NumImplicitDestructorsDeclared << "/"
749 << NumImplicitDestructors
750 << " implicit destructors created\n";
751
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000752 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000753 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000754 ExternalSource->PrintStats();
755 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000756
Douglas Gregor5b11d492010-07-25 17:53:33 +0000757 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000758}
759
Douglas Gregor801c99d2011-08-12 06:49:56 +0000760TypedefDecl *ASTContext::getInt128Decl() const {
761 if (!Int128Decl) {
762 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
763 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
764 getTranslationUnitDecl(),
765 SourceLocation(),
766 SourceLocation(),
767 &Idents.get("__int128_t"),
768 TInfo);
769 }
770
771 return Int128Decl;
772}
773
774TypedefDecl *ASTContext::getUInt128Decl() const {
775 if (!UInt128Decl) {
776 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
777 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
778 getTranslationUnitDecl(),
779 SourceLocation(),
780 SourceLocation(),
781 &Idents.get("__uint128_t"),
782 TInfo);
783 }
784
785 return UInt128Decl;
786}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000787
John McCall48f2d582009-10-23 23:03:21 +0000788void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000789 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000790 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000791 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000792}
793
Douglas Gregore8bbc122011-09-02 00:18:52 +0000794void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
795 assert((!this->Target || this->Target == &Target) &&
796 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000797 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000798
Douglas Gregore8bbc122011-09-02 00:18:52 +0000799 this->Target = &Target;
800
801 ABI.reset(createCXXABI(Target));
802 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
803
Chris Lattner970e54e2006-11-12 00:37:36 +0000804 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000805 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000806
Chris Lattner970e54e2006-11-12 00:37:36 +0000807 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000808 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000809 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000810 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000811 InitBuiltinType(CharTy, BuiltinType::Char_S);
812 else
813 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000814 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000815 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
816 InitBuiltinType(ShortTy, BuiltinType::Short);
817 InitBuiltinType(IntTy, BuiltinType::Int);
818 InitBuiltinType(LongTy, BuiltinType::Long);
819 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000820
Chris Lattner970e54e2006-11-12 00:37:36 +0000821 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000822 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
823 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
824 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
825 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
826 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000827
Chris Lattner970e54e2006-11-12 00:37:36 +0000828 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000829 InitBuiltinType(FloatTy, BuiltinType::Float);
830 InitBuiltinType(DoubleTy, BuiltinType::Double);
831 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000832
Chris Lattnerf122cef2009-04-30 02:43:43 +0000833 // GNU extension, 128-bit integers.
834 InitBuiltinType(Int128Ty, BuiltinType::Int128);
835 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
836
Abramo Bagnara06782942012-09-09 10:13:32 +0000837 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000838 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000839 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
840 else // -fshort-wchar makes wchar_t be unsigned.
841 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnara06782942012-09-09 10:13:32 +0000842 } else // C99 (or C++ using -fno-wchar)
Chris Lattner007cb022009-02-26 23:43:47 +0000843 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000844
James Molloy36365542012-05-04 10:55:22 +0000845 WIntTy = getFromTargetType(Target.getWIntType());
846
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000847 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
848 InitBuiltinType(Char16Ty, BuiltinType::Char16);
849 else // C99
850 Char16Ty = getFromTargetType(Target.getChar16Type());
851
852 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
853 InitBuiltinType(Char32Ty, BuiltinType::Char32);
854 else // C99
855 Char32Ty = getFromTargetType(Target.getChar32Type());
856
Douglas Gregor4619e432008-12-05 23:32:09 +0000857 // Placeholder type for type-dependent expressions whose type is
858 // completely unknown. No code should ever check a type against
859 // DependentTy and users should never see it; however, it is here to
860 // help diagnose failures to properly check for type-dependent
861 // expressions.
862 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000863
John McCall36e7fe32010-10-12 00:20:44 +0000864 // Placeholder type for functions.
865 InitBuiltinType(OverloadTy, BuiltinType::Overload);
866
John McCall0009fcc2011-04-26 20:42:42 +0000867 // Placeholder type for bound members.
868 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
869
John McCall526ab472011-10-25 17:37:35 +0000870 // Placeholder type for pseudo-objects.
871 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
872
John McCall31996342011-04-07 08:22:57 +0000873 // "any" type; useful for debugger-like clients.
874 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
875
John McCall8a6b59a2011-10-17 18:09:15 +0000876 // Placeholder type for unbridged ARC casts.
877 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
878
Eli Friedman34866c72012-08-31 00:14:07 +0000879 // Placeholder type for builtin functions.
880 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
881
Chris Lattner970e54e2006-11-12 00:37:36 +0000882 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000883 FloatComplexTy = getComplexType(FloatTy);
884 DoubleComplexTy = getComplexType(DoubleTy);
885 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000886
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000887 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000888 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
889 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000890 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000891
892 if (LangOpts.OpenCL) {
893 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
894 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
895 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
896 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
897 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
898 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000899
900 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000901 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000902
903 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000904 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
905 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000906
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000907 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000908
909 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000910
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000911 // void * type
912 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000913
914 // nullptr type (C++0x 2.14.7)
915 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000916
917 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
918 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000919
920 // Builtin type used to help define __builtin_va_list.
921 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000922}
923
David Blaikie9c902b52011-09-25 23:23:43 +0000924DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000925 return SourceMgr.getDiagnostics();
926}
927
Douglas Gregor561eceb2010-08-30 16:49:28 +0000928AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
929 AttrVec *&Result = DeclAttrs[D];
930 if (!Result) {
931 void *Mem = Allocate(sizeof(AttrVec));
932 Result = new (Mem) AttrVec;
933 }
934
935 return *Result;
936}
937
938/// \brief Erase the attributes corresponding to the given declaration.
939void ASTContext::eraseDeclAttrs(const Decl *D) {
940 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
941 if (Pos != DeclAttrs.end()) {
942 Pos->second->~AttrVec();
943 DeclAttrs.erase(Pos);
944 }
945}
946
Douglas Gregor86d142a2009-10-08 07:24:58 +0000947MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000948ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000949 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000950 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000951 = InstantiatedFromStaticDataMember.find(Var);
952 if (Pos == InstantiatedFromStaticDataMember.end())
953 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000954
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000955 return Pos->second;
956}
957
Mike Stump11289f42009-09-09 15:08:12 +0000958void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000959ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000960 TemplateSpecializationKind TSK,
961 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000962 assert(Inst->isStaticDataMember() && "Not a static data member");
963 assert(Tmpl->isStaticDataMember() && "Not a static data member");
964 assert(!InstantiatedFromStaticDataMember[Inst] &&
965 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000966 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000967 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000968}
969
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000970FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
971 const FunctionDecl *FD){
972 assert(FD && "Specialization is 0");
973 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000974 = ClassScopeSpecializationPattern.find(FD);
975 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000976 return 0;
977
978 return Pos->second;
979}
980
981void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
982 FunctionDecl *Pattern) {
983 assert(FD && "Specialization is 0");
984 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000985 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000986}
987
John McCalle61f2ba2009-11-18 02:36:19 +0000988NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000989ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000990 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000991 = InstantiatedFromUsingDecl.find(UUD);
992 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000993 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000994
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000995 return Pos->second;
996}
997
998void
John McCallb96ec562009-12-04 22:46:56 +0000999ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1000 assert((isa<UsingDecl>(Pattern) ||
1001 isa<UnresolvedUsingValueDecl>(Pattern) ||
1002 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1003 "pattern decl is not a using decl");
1004 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1005 InstantiatedFromUsingDecl[Inst] = Pattern;
1006}
1007
1008UsingShadowDecl *
1009ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1010 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1011 = InstantiatedFromUsingShadowDecl.find(Inst);
1012 if (Pos == InstantiatedFromUsingShadowDecl.end())
1013 return 0;
1014
1015 return Pos->second;
1016}
1017
1018void
1019ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1020 UsingShadowDecl *Pattern) {
1021 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1022 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001023}
1024
Anders Carlsson5da84842009-09-01 04:26:58 +00001025FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1026 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1027 = InstantiatedFromUnnamedFieldDecl.find(Field);
1028 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1029 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001030
Anders Carlsson5da84842009-09-01 04:26:58 +00001031 return Pos->second;
1032}
1033
1034void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1035 FieldDecl *Tmpl) {
1036 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1037 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1038 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1039 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001040
Anders Carlsson5da84842009-09-01 04:26:58 +00001041 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1042}
1043
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001044bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1045 const FieldDecl *LastFD) const {
1046 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001047 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001048}
1049
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001050bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1051 const FieldDecl *LastFD) const {
1052 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001053 FD->getBitWidthValue(*this) == 0 &&
1054 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001055}
1056
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001057bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1058 const FieldDecl *LastFD) const {
1059 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001060 FD->getBitWidthValue(*this) &&
1061 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001062}
1063
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001064bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001065 const FieldDecl *LastFD) const {
1066 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001067 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001068}
1069
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001070bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001071 const FieldDecl *LastFD) const {
1072 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001073 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001074}
1075
Douglas Gregor832940b2010-03-02 23:58:15 +00001076ASTContext::overridden_cxx_method_iterator
1077ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1078 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001079 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001080 if (Pos == OverriddenMethods.end())
1081 return 0;
1082
1083 return Pos->second.begin();
1084}
1085
1086ASTContext::overridden_cxx_method_iterator
1087ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1088 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001089 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001090 if (Pos == OverriddenMethods.end())
1091 return 0;
1092
1093 return Pos->second.end();
1094}
1095
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001096unsigned
1097ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1098 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001099 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001100 if (Pos == OverriddenMethods.end())
1101 return 0;
1102
1103 return Pos->second.size();
1104}
1105
Douglas Gregor832940b2010-03-02 23:58:15 +00001106void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1107 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001108 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001109 OverriddenMethods[Method].push_back(Overridden);
1110}
1111
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001112void ASTContext::getOverriddenMethods(
1113 const NamedDecl *D,
1114 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001115 assert(D);
1116
1117 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001118 Overridden.append(CXXMethod->begin_overridden_methods(),
1119 CXXMethod->end_overridden_methods());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001120 return;
1121 }
1122
1123 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1124 if (!Method)
1125 return;
1126
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001127 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1128 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001129 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001130}
1131
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001132void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1133 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1134 assert(!Import->isFromASTFile() && "Non-local import declaration");
1135 if (!FirstLocalImport) {
1136 FirstLocalImport = Import;
1137 LastLocalImport = Import;
1138 return;
1139 }
1140
1141 LastLocalImport->NextLocalImport = Import;
1142 LastLocalImport = Import;
1143}
1144
Chris Lattner53cfe802007-07-18 17:52:12 +00001145//===----------------------------------------------------------------------===//
1146// Type Sizing and Analysis
1147//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001148
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001149/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1150/// scalar floating point type.
1151const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001152 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001153 assert(BT && "Not a floating point type!");
1154 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001155 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001156 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001157 case BuiltinType::Float: return Target->getFloatFormat();
1158 case BuiltinType::Double: return Target->getDoubleFormat();
1159 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001160 }
1161}
1162
Ken Dyck160146e2010-01-27 17:10:57 +00001163/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001164/// specified decl. Note that bitfields do not have a valid alignment, so
1165/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001166/// If @p RefAsPointee, references are treated like their underlying type
1167/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001168CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001169 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001170
John McCall94268702010-10-08 18:24:19 +00001171 bool UseAlignAttrOnly = false;
1172 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1173 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001174
John McCall94268702010-10-08 18:24:19 +00001175 // __attribute__((aligned)) can increase or decrease alignment
1176 // *except* on a struct or struct member, where it only increases
1177 // alignment unless 'packed' is also specified.
1178 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001179 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001180 // ignore that possibility; Sema should diagnose it.
1181 if (isa<FieldDecl>(D)) {
1182 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1183 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1184 } else {
1185 UseAlignAttrOnly = true;
1186 }
1187 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001188 else if (isa<FieldDecl>(D))
1189 UseAlignAttrOnly =
1190 D->hasAttr<PackedAttr>() ||
1191 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001192
John McCall4e819612011-01-20 07:57:12 +00001193 // If we're using the align attribute only, just ignore everything
1194 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001195 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001196 // do nothing
1197
John McCall94268702010-10-08 18:24:19 +00001198 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001199 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001200 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001201 if (RefAsPointee)
1202 T = RT->getPointeeType();
1203 else
1204 T = getPointerType(RT->getPointeeType());
1205 }
1206 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001207 // Adjust alignments of declarations with array type by the
1208 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001209 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001210 const ArrayType *arrayType;
1211 if (MinWidth && (arrayType = getAsArrayType(T))) {
1212 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001213 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001214 else if (isa<ConstantArrayType>(arrayType) &&
1215 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001216 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001217
John McCall33ddac02011-01-19 10:06:00 +00001218 // Walk through any array types while we're at it.
1219 T = getBaseElementType(arrayType);
1220 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001221 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001222 }
John McCall4e819612011-01-20 07:57:12 +00001223
1224 // Fields can be subject to extra alignment constraints, like if
1225 // the field is packed, the struct is packed, or the struct has a
1226 // a max-field-alignment constraint (#pragma pack). So calculate
1227 // the actual alignment of the field within the struct, and then
1228 // (as we're expected to) constrain that by the alignment of the type.
1229 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1230 // So calculate the alignment of the field.
1231 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1232
1233 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001234 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001235
1236 // Use the GCD of that and the offset within the record.
1237 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1238 if (offset > 0) {
1239 // Alignment is always a power of 2, so the GCD will be a power of 2,
1240 // which means we get to do this crazy thing instead of Euclid's.
1241 uint64_t lowBitOfOffset = offset & (~offset + 1);
1242 if (lowBitOfOffset < fieldAlign)
1243 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1244 }
1245
1246 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001247 }
Chris Lattner68061312009-01-24 21:53:27 +00001248 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001249
Ken Dyckcc56c542011-01-15 18:38:59 +00001250 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001251}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001252
John McCallf1249922012-08-21 04:10:00 +00001253// getTypeInfoDataSizeInChars - Return the size of a type, in
1254// chars. If the type is a record, its data size is returned. This is
1255// the size of the memcpy that's performed when assigning this type
1256// using a trivial copy/move assignment operator.
1257std::pair<CharUnits, CharUnits>
1258ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1259 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1260
1261 // In C++, objects can sometimes be allocated into the tail padding
1262 // of a base-class subobject. We decide whether that's possible
1263 // during class layout, so here we can just trust the layout results.
1264 if (getLangOpts().CPlusPlus) {
1265 if (const RecordType *RT = T->getAs<RecordType>()) {
1266 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1267 sizeAndAlign.first = layout.getDataSize();
1268 }
1269 }
1270
1271 return sizeAndAlign;
1272}
1273
John McCall87fe5d52010-05-20 01:18:31 +00001274std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001275ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001276 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001277 return std::make_pair(toCharUnitsFromBits(Info.first),
1278 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001279}
1280
1281std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001282ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001283 return getTypeInfoInChars(T.getTypePtr());
1284}
1285
Daniel Dunbarc6475872012-03-09 04:12:54 +00001286std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1287 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1288 if (it != MemoizedTypeInfo.end())
1289 return it->second;
1290
1291 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1292 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1293 return Info;
1294}
1295
1296/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1297/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001298///
1299/// FIXME: Pointers into different addr spaces could have different sizes and
1300/// alignment requirements: getPointerInfo should take an AddrSpace, this
1301/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001302std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001303ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001304 uint64_t Width=0;
1305 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001306 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001307#define TYPE(Class, Base)
1308#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001309#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001310#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1311#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001312 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001313
Chris Lattner355332d2007-07-13 22:27:08 +00001314 case Type::FunctionNoProto:
1315 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001316 // GCC extension: alignof(function) = 32 bits
1317 Width = 0;
1318 Align = 32;
1319 break;
1320
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001321 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001322 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001323 Width = 0;
1324 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1325 break;
1326
Steve Naroff5c131802007-08-30 01:06:46 +00001327 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001328 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001329
Chris Lattner37e05872008-03-05 18:54:05 +00001330 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001331 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001332 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1333 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001334 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001335 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001336 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001337 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001338 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001339 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001340 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001341 const VectorType *VT = cast<VectorType>(T);
1342 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1343 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001344 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001345 // If the alignment is not a power of 2, round up to the next power of 2.
1346 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001347 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001348 Align = llvm::NextPowerOf2(Align);
1349 Width = llvm::RoundUpToAlignment(Width, Align);
1350 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001351 // Adjust the alignment based on the target max.
1352 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1353 if (TargetVectorAlign && TargetVectorAlign < Align)
1354 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001355 break;
1356 }
Chris Lattner647fb222007-07-18 18:26:58 +00001357
Chris Lattner7570e9c2008-03-08 08:52:55 +00001358 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001359 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001360 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001361 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001362 // GCC extension: alignof(void) = 8 bits.
1363 Width = 0;
1364 Align = 8;
1365 break;
1366
Chris Lattner6a4f7452007-12-19 19:23:28 +00001367 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001368 Width = Target->getBoolWidth();
1369 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001370 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001371 case BuiltinType::Char_S:
1372 case BuiltinType::Char_U:
1373 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001374 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001375 Width = Target->getCharWidth();
1376 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001377 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001378 case BuiltinType::WChar_S:
1379 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001380 Width = Target->getWCharWidth();
1381 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001382 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001383 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001384 Width = Target->getChar16Width();
1385 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001386 break;
1387 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001388 Width = Target->getChar32Width();
1389 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001390 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001391 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001392 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001393 Width = Target->getShortWidth();
1394 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001395 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001396 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001397 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001398 Width = Target->getIntWidth();
1399 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001400 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001401 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001402 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001403 Width = Target->getLongWidth();
1404 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001405 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001406 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001407 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001408 Width = Target->getLongLongWidth();
1409 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001410 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001411 case BuiltinType::Int128:
1412 case BuiltinType::UInt128:
1413 Width = 128;
1414 Align = 128; // int128_t is 128-bit aligned on all targets.
1415 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001416 case BuiltinType::Half:
1417 Width = Target->getHalfWidth();
1418 Align = Target->getHalfAlign();
1419 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001420 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001421 Width = Target->getFloatWidth();
1422 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001423 break;
1424 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001425 Width = Target->getDoubleWidth();
1426 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001427 break;
1428 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001429 Width = Target->getLongDoubleWidth();
1430 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001431 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001432 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001433 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1434 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001435 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001436 case BuiltinType::ObjCId:
1437 case BuiltinType::ObjCClass:
1438 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001439 Width = Target->getPointerWidth(0);
1440 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001441 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001442 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001443 case BuiltinType::OCLImage1d:
1444 case BuiltinType::OCLImage1dArray:
1445 case BuiltinType::OCLImage1dBuffer:
1446 case BuiltinType::OCLImage2d:
1447 case BuiltinType::OCLImage2dArray:
1448 case BuiltinType::OCLImage3d:
1449 // Currently these types are pointers to opaque types.
1450 Width = Target->getPointerWidth(0);
1451 Align = Target->getPointerAlign(0);
1452 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001453 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001454 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001455 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001456 Width = Target->getPointerWidth(0);
1457 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001458 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001459 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001460 unsigned AS = getTargetAddressSpace(
1461 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001462 Width = Target->getPointerWidth(AS);
1463 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001464 break;
1465 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001466 case Type::LValueReference:
1467 case Type::RValueReference: {
1468 // alignof and sizeof should never enter this code path here, so we go
1469 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001470 unsigned AS = getTargetAddressSpace(
1471 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001472 Width = Target->getPointerWidth(AS);
1473 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001474 break;
1475 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001476 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001477 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001478 Width = Target->getPointerWidth(AS);
1479 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001480 break;
1481 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001482 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001483 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001484 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001485 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001486 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001487 Align = PtrDiffInfo.second;
1488 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001489 }
Chris Lattner647fb222007-07-18 18:26:58 +00001490 case Type::Complex: {
1491 // Complex types have the same alignment as their elements, but twice the
1492 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001493 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001494 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001495 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001496 Align = EltInfo.second;
1497 break;
1498 }
John McCall8b07ec22010-05-15 11:32:37 +00001499 case Type::ObjCObject:
1500 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001501 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001502 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001503 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001504 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001505 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001506 break;
1507 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001508 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001509 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001510 const TagType *TT = cast<TagType>(T);
1511
1512 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001513 Width = 8;
1514 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001515 break;
1516 }
Mike Stump11289f42009-09-09 15:08:12 +00001517
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001518 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001519 return getTypeInfo(ET->getDecl()->getIntegerType());
1520
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001521 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001522 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001523 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001524 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001525 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001526 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001527
Chris Lattner63d2b362009-10-22 05:17:15 +00001528 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001529 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1530 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001531
Richard Smith30482bc2011-02-20 03:19:35 +00001532 case Type::Auto: {
1533 const AutoType *A = cast<AutoType>(T);
1534 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001535 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001536 }
1537
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001538 case Type::Paren:
1539 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1540
Douglas Gregoref462e62009-04-30 17:32:17 +00001541 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001542 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001543 std::pair<uint64_t, unsigned> Info
1544 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001545 // If the typedef has an aligned attribute on it, it overrides any computed
1546 // alignment we have. This violates the GCC documentation (which says that
1547 // attribute(aligned) can only round up) but matches its implementation.
1548 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1549 Align = AttrAlign;
1550 else
1551 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001552 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001553 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001554 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001555
1556 case Type::TypeOfExpr:
1557 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1558 .getTypePtr());
1559
1560 case Type::TypeOf:
1561 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1562
Anders Carlsson81df7b82009-06-24 19:06:50 +00001563 case Type::Decltype:
1564 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1565 .getTypePtr());
1566
Alexis Hunte852b102011-05-24 22:41:36 +00001567 case Type::UnaryTransform:
1568 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1569
Abramo Bagnara6150c882010-05-11 21:36:43 +00001570 case Type::Elaborated:
1571 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001572
John McCall81904512011-01-06 01:58:22 +00001573 case Type::Attributed:
1574 return getTypeInfo(
1575 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1576
Richard Smith3f1b5d02011-05-05 21:57:07 +00001577 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001578 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001579 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001580 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1581 // A type alias template specialization may refer to a typedef with the
1582 // aligned attribute on it.
1583 if (TST->isTypeAlias())
1584 return getTypeInfo(TST->getAliasedType().getTypePtr());
1585 else
1586 return getTypeInfo(getCanonicalType(T));
1587 }
1588
Eli Friedman0dfb8892011-10-06 23:00:33 +00001589 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001590 std::pair<uint64_t, unsigned> Info
1591 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1592 Width = Info.first;
1593 Align = Info.second;
1594 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1595 llvm::isPowerOf2_64(Width)) {
1596 // We can potentially perform lock-free atomic operations for this
1597 // type; promote the alignment appropriately.
1598 // FIXME: We could potentially promote the width here as well...
1599 // is that worthwhile? (Non-struct atomic types generally have
1600 // power-of-two size anyway, but structs might not. Requires a bit
1601 // of implementation work to make sure we zero out the extra bits.)
1602 Align = static_cast<unsigned>(Width);
1603 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001604 }
1605
Douglas Gregoref462e62009-04-30 17:32:17 +00001606 }
Mike Stump11289f42009-09-09 15:08:12 +00001607
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001608 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001609 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001610}
1611
Ken Dyckcc56c542011-01-15 18:38:59 +00001612/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1613CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1614 return CharUnits::fromQuantity(BitSize / getCharWidth());
1615}
1616
Ken Dyckb0fcc592011-02-11 01:54:29 +00001617/// toBits - Convert a size in characters to a size in characters.
1618int64_t ASTContext::toBits(CharUnits CharSize) const {
1619 return CharSize.getQuantity() * getCharWidth();
1620}
1621
Ken Dyck8c89d592009-12-22 14:23:30 +00001622/// getTypeSizeInChars - Return the size of the specified type, in characters.
1623/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001624CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001625 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001626}
Jay Foad39c79802011-01-12 09:06:06 +00001627CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001628 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001629}
1630
Ken Dycka6046ab2010-01-26 17:25:18 +00001631/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001632/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001633CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001634 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001635}
Jay Foad39c79802011-01-12 09:06:06 +00001636CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001637 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001638}
1639
Chris Lattnera3402cd2009-01-27 18:08:34 +00001640/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1641/// type for the current target in bits. This can be different than the ABI
1642/// alignment in cases where it is beneficial for performance to overalign
1643/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001644unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001645 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001646
1647 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001648 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001649 T = CT->getElementType().getTypePtr();
1650 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001651 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1652 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001653 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1654
Chris Lattnera3402cd2009-01-27 18:08:34 +00001655 return ABIAlign;
1656}
1657
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001658/// DeepCollectObjCIvars -
1659/// This routine first collects all declared, but not synthesized, ivars in
1660/// super class and then collects all ivars, including those synthesized for
1661/// current class. This routine is used for implementation of current class
1662/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001663///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001664void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1665 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001666 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001667 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1668 DeepCollectObjCIvars(SuperClass, false, Ivars);
1669 if (!leafClass) {
1670 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1671 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001672 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001673 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001674 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001675 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001676 Iv= Iv->getNextIvar())
1677 Ivars.push_back(Iv);
1678 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001679}
1680
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001681/// CollectInheritedProtocols - Collect all protocols in current class and
1682/// those inherited by it.
1683void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001684 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001685 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001686 // We can use protocol_iterator here instead of
1687 // all_referenced_protocol_iterator since we are walking all categories.
1688 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1689 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001690 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001691 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001692 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001693 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001694 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001695 CollectInheritedProtocols(*P, Protocols);
1696 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001697 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001698
1699 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001700 for (ObjCInterfaceDecl::visible_categories_iterator
1701 Cat = OI->visible_categories_begin(),
1702 CatEnd = OI->visible_categories_end();
1703 Cat != CatEnd; ++Cat) {
1704 CollectInheritedProtocols(*Cat, Protocols);
1705 }
1706
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001707 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1708 while (SD) {
1709 CollectInheritedProtocols(SD, Protocols);
1710 SD = SD->getSuperClass();
1711 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001712 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001713 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001714 PE = OC->protocol_end(); P != PE; ++P) {
1715 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001716 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001717 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1718 PE = Proto->protocol_end(); P != PE; ++P)
1719 CollectInheritedProtocols(*P, Protocols);
1720 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001721 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001722 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1723 PE = OP->protocol_end(); P != PE; ++P) {
1724 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001725 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001726 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1727 PE = Proto->protocol_end(); P != PE; ++P)
1728 CollectInheritedProtocols(*P, Protocols);
1729 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001730 }
1731}
1732
Jay Foad39c79802011-01-12 09:06:06 +00001733unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001734 unsigned count = 0;
1735 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001736 for (ObjCInterfaceDecl::known_extensions_iterator
1737 Ext = OI->known_extensions_begin(),
1738 ExtEnd = OI->known_extensions_end();
1739 Ext != ExtEnd; ++Ext) {
1740 count += Ext->ivar_size();
1741 }
1742
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001743 // Count ivar defined in this class's implementation. This
1744 // includes synthesized ivars.
1745 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001746 count += ImplDecl->ivar_size();
1747
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001748 return count;
1749}
1750
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001751bool ASTContext::isSentinelNullExpr(const Expr *E) {
1752 if (!E)
1753 return false;
1754
1755 // nullptr_t is always treated as null.
1756 if (E->getType()->isNullPtrType()) return true;
1757
1758 if (E->getType()->isAnyPointerType() &&
1759 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1760 Expr::NPC_ValueDependentIsNull))
1761 return true;
1762
1763 // Unfortunately, __null has type 'int'.
1764 if (isa<GNUNullExpr>(E)) return true;
1765
1766 return false;
1767}
1768
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001769/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1770ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1771 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1772 I = ObjCImpls.find(D);
1773 if (I != ObjCImpls.end())
1774 return cast<ObjCImplementationDecl>(I->second);
1775 return 0;
1776}
1777/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1778ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1779 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1780 I = ObjCImpls.find(D);
1781 if (I != ObjCImpls.end())
1782 return cast<ObjCCategoryImplDecl>(I->second);
1783 return 0;
1784}
1785
1786/// \brief Set the implementation of ObjCInterfaceDecl.
1787void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1788 ObjCImplementationDecl *ImplD) {
1789 assert(IFaceD && ImplD && "Passed null params");
1790 ObjCImpls[IFaceD] = ImplD;
1791}
1792/// \brief Set the implementation of ObjCCategoryDecl.
1793void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1794 ObjCCategoryImplDecl *ImplD) {
1795 assert(CatD && ImplD && "Passed null params");
1796 ObjCImpls[CatD] = ImplD;
1797}
1798
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001799ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1800 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1801 return ID;
1802 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1803 return CD->getClassInterface();
1804 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1805 return IMD->getClassInterface();
1806
1807 return 0;
1808}
1809
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001810/// \brief Get the copy initialization expression of VarDecl,or NULL if
1811/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001812Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001813 assert(VD && "Passed null params");
1814 assert(VD->hasAttr<BlocksAttr>() &&
1815 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001816 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001817 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001818 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1819}
1820
1821/// \brief Set the copy inialization expression of a block var decl.
1822void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1823 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001824 assert(VD->hasAttr<BlocksAttr>() &&
1825 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001826 BlockVarCopyInits[VD] = Init;
1827}
1828
John McCallbcd03502009-12-07 02:54:59 +00001829TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001830 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001831 if (!DataSize)
1832 DataSize = TypeLoc::getFullDataSizeForType(T);
1833 else
1834 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001835 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001836
John McCallbcd03502009-12-07 02:54:59 +00001837 TypeSourceInfo *TInfo =
1838 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1839 new (TInfo) TypeSourceInfo(T);
1840 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001841}
1842
John McCallbcd03502009-12-07 02:54:59 +00001843TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001844 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001845 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001846 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001847 return DI;
1848}
1849
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001850const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001851ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001852 return getObjCLayout(D, 0);
1853}
1854
1855const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001856ASTContext::getASTObjCImplementationLayout(
1857 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001858 return getObjCLayout(D->getClassInterface(), D);
1859}
1860
Chris Lattner983a8bb2007-07-13 22:13:22 +00001861//===----------------------------------------------------------------------===//
1862// Type creation/memoization methods
1863//===----------------------------------------------------------------------===//
1864
Jay Foad39c79802011-01-12 09:06:06 +00001865QualType
John McCall33ddac02011-01-19 10:06:00 +00001866ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1867 unsigned fastQuals = quals.getFastQualifiers();
1868 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001869
1870 // Check if we've already instantiated this type.
1871 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001872 ExtQuals::Profile(ID, baseType, quals);
1873 void *insertPos = 0;
1874 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1875 assert(eq->getQualifiers() == quals);
1876 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001877 }
1878
John McCall33ddac02011-01-19 10:06:00 +00001879 // If the base type is not canonical, make the appropriate canonical type.
1880 QualType canon;
1881 if (!baseType->isCanonicalUnqualified()) {
1882 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001883 canonSplit.Quals.addConsistentQualifiers(quals);
1884 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001885
1886 // Re-find the insert position.
1887 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1888 }
1889
1890 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1891 ExtQualNodes.InsertNode(eq, insertPos);
1892 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001893}
1894
Jay Foad39c79802011-01-12 09:06:06 +00001895QualType
1896ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001897 QualType CanT = getCanonicalType(T);
1898 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001899 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001900
John McCall8ccfcb52009-09-24 19:53:00 +00001901 // If we are composing extended qualifiers together, merge together
1902 // into one ExtQuals node.
1903 QualifierCollector Quals;
1904 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001905
John McCall8ccfcb52009-09-24 19:53:00 +00001906 // If this type already has an address space specified, it cannot get
1907 // another one.
1908 assert(!Quals.hasAddressSpace() &&
1909 "Type cannot be in multiple addr spaces!");
1910 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001911
John McCall8ccfcb52009-09-24 19:53:00 +00001912 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001913}
1914
Chris Lattnerd60183d2009-02-18 22:53:11 +00001915QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001916 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001917 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001918 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001919 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001920
John McCall53fa7142010-12-24 02:08:15 +00001921 if (const PointerType *ptr = T->getAs<PointerType>()) {
1922 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001923 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001924 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1925 return getPointerType(ResultType);
1926 }
1927 }
Mike Stump11289f42009-09-09 15:08:12 +00001928
John McCall8ccfcb52009-09-24 19:53:00 +00001929 // If we are composing extended qualifiers together, merge together
1930 // into one ExtQuals node.
1931 QualifierCollector Quals;
1932 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001933
John McCall8ccfcb52009-09-24 19:53:00 +00001934 // If this type already has an ObjCGC specified, it cannot get
1935 // another one.
1936 assert(!Quals.hasObjCGCAttr() &&
1937 "Type cannot have multiple ObjCGCs!");
1938 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001939
John McCall8ccfcb52009-09-24 19:53:00 +00001940 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001941}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001942
John McCall4f5019e2010-12-19 02:44:49 +00001943const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1944 FunctionType::ExtInfo Info) {
1945 if (T->getExtInfo() == Info)
1946 return T;
1947
1948 QualType Result;
1949 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1950 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1951 } else {
1952 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1953 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1954 EPI.ExtInfo = Info;
1955 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1956 FPT->getNumArgs(), EPI);
1957 }
1958
1959 return cast<FunctionType>(Result.getTypePtr());
1960}
1961
Chris Lattnerc6395932007-06-22 20:56:16 +00001962/// getComplexType - Return the uniqued reference to the type for a complex
1963/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001964QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001965 // Unique pointers, to guarantee there is only one pointer of a particular
1966 // structure.
1967 llvm::FoldingSetNodeID ID;
1968 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001969
Chris Lattnerc6395932007-06-22 20:56:16 +00001970 void *InsertPos = 0;
1971 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1972 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001973
Chris Lattnerc6395932007-06-22 20:56:16 +00001974 // If the pointee type isn't canonical, this won't be a canonical type either,
1975 // so fill in the canonical type field.
1976 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001977 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001978 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001979
Chris Lattnerc6395932007-06-22 20:56:16 +00001980 // Get the new insert position for the node we care about.
1981 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001982 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001983 }
John McCall90d1c2d2009-09-24 23:30:46 +00001984 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001985 Types.push_back(New);
1986 ComplexTypes.InsertNode(New, InsertPos);
1987 return QualType(New, 0);
1988}
1989
Chris Lattner970e54e2006-11-12 00:37:36 +00001990/// getPointerType - Return the uniqued reference to the type for a pointer to
1991/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001992QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001993 // Unique pointers, to guarantee there is only one pointer of a particular
1994 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001995 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001996 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001997
Chris Lattner67521df2007-01-27 01:29:36 +00001998 void *InsertPos = 0;
1999 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002000 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002001
Chris Lattner7ccecb92006-11-12 08:50:50 +00002002 // If the pointee type isn't canonical, this won't be a canonical type either,
2003 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002004 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002005 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002006 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002007
Chris Lattner67521df2007-01-27 01:29:36 +00002008 // Get the new insert position for the node we care about.
2009 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002010 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00002011 }
John McCall90d1c2d2009-09-24 23:30:46 +00002012 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002013 Types.push_back(New);
2014 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002015 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002016}
2017
Mike Stump11289f42009-09-09 15:08:12 +00002018/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002019/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002020QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002021 assert(T->isFunctionType() && "block of function types only");
2022 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002023 // structure.
2024 llvm::FoldingSetNodeID ID;
2025 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002026
Steve Naroffec33ed92008-08-27 16:04:49 +00002027 void *InsertPos = 0;
2028 if (BlockPointerType *PT =
2029 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2030 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002031
2032 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002033 // type either so fill in the canonical type field.
2034 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002035 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002036 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002037
Steve Naroffec33ed92008-08-27 16:04:49 +00002038 // Get the new insert position for the node we care about.
2039 BlockPointerType *NewIP =
2040 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002041 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002042 }
John McCall90d1c2d2009-09-24 23:30:46 +00002043 BlockPointerType *New
2044 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002045 Types.push_back(New);
2046 BlockPointerTypes.InsertNode(New, InsertPos);
2047 return QualType(New, 0);
2048}
2049
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002050/// getLValueReferenceType - Return the uniqued reference to the type for an
2051/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002052QualType
2053ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002054 assert(getCanonicalType(T) != OverloadTy &&
2055 "Unresolved overloaded function type");
2056
Bill Wendling3708c182007-05-27 10:15:43 +00002057 // Unique pointers, to guarantee there is only one pointer of a particular
2058 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002059 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002060 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002061
2062 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002063 if (LValueReferenceType *RT =
2064 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002065 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002066
John McCallfc93cf92009-10-22 22:37:11 +00002067 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2068
Bill Wendling3708c182007-05-27 10:15:43 +00002069 // If the referencee type isn't canonical, this won't be a canonical type
2070 // either, so fill in the canonical type field.
2071 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002072 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2073 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2074 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002075
Bill Wendling3708c182007-05-27 10:15:43 +00002076 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002077 LValueReferenceType *NewIP =
2078 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002079 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002080 }
2081
John McCall90d1c2d2009-09-24 23:30:46 +00002082 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002083 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2084 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002085 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002086 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002087
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002088 return QualType(New, 0);
2089}
2090
2091/// getRValueReferenceType - Return the uniqued reference to the type for an
2092/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002093QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002094 // Unique pointers, to guarantee there is only one pointer of a particular
2095 // structure.
2096 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002097 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002098
2099 void *InsertPos = 0;
2100 if (RValueReferenceType *RT =
2101 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2102 return QualType(RT, 0);
2103
John McCallfc93cf92009-10-22 22:37:11 +00002104 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2105
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002106 // If the referencee type isn't canonical, this won't be a canonical type
2107 // either, so fill in the canonical type field.
2108 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002109 if (InnerRef || !T.isCanonical()) {
2110 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2111 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002112
2113 // Get the new insert position for the node we care about.
2114 RValueReferenceType *NewIP =
2115 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002116 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002117 }
2118
John McCall90d1c2d2009-09-24 23:30:46 +00002119 RValueReferenceType *New
2120 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002121 Types.push_back(New);
2122 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002123 return QualType(New, 0);
2124}
2125
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002126/// getMemberPointerType - Return the uniqued reference to the type for a
2127/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002128QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002129 // Unique pointers, to guarantee there is only one pointer of a particular
2130 // structure.
2131 llvm::FoldingSetNodeID ID;
2132 MemberPointerType::Profile(ID, T, Cls);
2133
2134 void *InsertPos = 0;
2135 if (MemberPointerType *PT =
2136 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2137 return QualType(PT, 0);
2138
2139 // If the pointee or class type isn't canonical, this won't be a canonical
2140 // type either, so fill in the canonical type field.
2141 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002142 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002143 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2144
2145 // Get the new insert position for the node we care about.
2146 MemberPointerType *NewIP =
2147 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002148 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002149 }
John McCall90d1c2d2009-09-24 23:30:46 +00002150 MemberPointerType *New
2151 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002152 Types.push_back(New);
2153 MemberPointerTypes.InsertNode(New, InsertPos);
2154 return QualType(New, 0);
2155}
2156
Mike Stump11289f42009-09-09 15:08:12 +00002157/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002158/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002159QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002160 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002161 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002162 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002163 assert((EltTy->isDependentType() ||
2164 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002165 "Constant array of VLAs is illegal!");
2166
Chris Lattnere2df3f92009-05-13 04:12:56 +00002167 // Convert the array size into a canonical width matching the pointer size for
2168 // the target.
2169 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002170 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002171 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002172
Chris Lattner23b7eb62007-06-15 23:05:46 +00002173 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002174 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002175
Chris Lattner36f8e652007-01-27 08:31:04 +00002176 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002177 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002178 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002179 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002180
John McCall33ddac02011-01-19 10:06:00 +00002181 // If the element type isn't canonical or has qualifiers, this won't
2182 // be a canonical type either, so fill in the canonical type field.
2183 QualType Canon;
2184 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2185 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002186 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002187 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002188 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002189
Chris Lattner36f8e652007-01-27 08:31:04 +00002190 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002191 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002192 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002193 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002194 }
Mike Stump11289f42009-09-09 15:08:12 +00002195
John McCall90d1c2d2009-09-24 23:30:46 +00002196 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002197 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002198 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002199 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002200 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002201}
2202
John McCall06549462011-01-18 08:40:38 +00002203/// getVariableArrayDecayedType - Turns the given type, which may be
2204/// variably-modified, into the corresponding type with all the known
2205/// sizes replaced with [*].
2206QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2207 // Vastly most common case.
2208 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002209
John McCall06549462011-01-18 08:40:38 +00002210 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002211
John McCall06549462011-01-18 08:40:38 +00002212 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002213 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002214 switch (ty->getTypeClass()) {
2215#define TYPE(Class, Base)
2216#define ABSTRACT_TYPE(Class, Base)
2217#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2218#include "clang/AST/TypeNodes.def"
2219 llvm_unreachable("didn't desugar past all non-canonical types?");
2220
2221 // These types should never be variably-modified.
2222 case Type::Builtin:
2223 case Type::Complex:
2224 case Type::Vector:
2225 case Type::ExtVector:
2226 case Type::DependentSizedExtVector:
2227 case Type::ObjCObject:
2228 case Type::ObjCInterface:
2229 case Type::ObjCObjectPointer:
2230 case Type::Record:
2231 case Type::Enum:
2232 case Type::UnresolvedUsing:
2233 case Type::TypeOfExpr:
2234 case Type::TypeOf:
2235 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002236 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002237 case Type::DependentName:
2238 case Type::InjectedClassName:
2239 case Type::TemplateSpecialization:
2240 case Type::DependentTemplateSpecialization:
2241 case Type::TemplateTypeParm:
2242 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002243 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002244 case Type::PackExpansion:
2245 llvm_unreachable("type should never be variably-modified");
2246
2247 // These types can be variably-modified but should never need to
2248 // further decay.
2249 case Type::FunctionNoProto:
2250 case Type::FunctionProto:
2251 case Type::BlockPointer:
2252 case Type::MemberPointer:
2253 return type;
2254
2255 // These types can be variably-modified. All these modifications
2256 // preserve structure except as noted by comments.
2257 // TODO: if we ever care about optimizing VLAs, there are no-op
2258 // optimizations available here.
2259 case Type::Pointer:
2260 result = getPointerType(getVariableArrayDecayedType(
2261 cast<PointerType>(ty)->getPointeeType()));
2262 break;
2263
2264 case Type::LValueReference: {
2265 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2266 result = getLValueReferenceType(
2267 getVariableArrayDecayedType(lv->getPointeeType()),
2268 lv->isSpelledAsLValue());
2269 break;
2270 }
2271
2272 case Type::RValueReference: {
2273 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2274 result = getRValueReferenceType(
2275 getVariableArrayDecayedType(lv->getPointeeType()));
2276 break;
2277 }
2278
Eli Friedman0dfb8892011-10-06 23:00:33 +00002279 case Type::Atomic: {
2280 const AtomicType *at = cast<AtomicType>(ty);
2281 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2282 break;
2283 }
2284
John McCall06549462011-01-18 08:40:38 +00002285 case Type::ConstantArray: {
2286 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2287 result = getConstantArrayType(
2288 getVariableArrayDecayedType(cat->getElementType()),
2289 cat->getSize(),
2290 cat->getSizeModifier(),
2291 cat->getIndexTypeCVRQualifiers());
2292 break;
2293 }
2294
2295 case Type::DependentSizedArray: {
2296 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2297 result = getDependentSizedArrayType(
2298 getVariableArrayDecayedType(dat->getElementType()),
2299 dat->getSizeExpr(),
2300 dat->getSizeModifier(),
2301 dat->getIndexTypeCVRQualifiers(),
2302 dat->getBracketsRange());
2303 break;
2304 }
2305
2306 // Turn incomplete types into [*] types.
2307 case Type::IncompleteArray: {
2308 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2309 result = getVariableArrayType(
2310 getVariableArrayDecayedType(iat->getElementType()),
2311 /*size*/ 0,
2312 ArrayType::Normal,
2313 iat->getIndexTypeCVRQualifiers(),
2314 SourceRange());
2315 break;
2316 }
2317
2318 // Turn VLA types into [*] types.
2319 case Type::VariableArray: {
2320 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2321 result = getVariableArrayType(
2322 getVariableArrayDecayedType(vat->getElementType()),
2323 /*size*/ 0,
2324 ArrayType::Star,
2325 vat->getIndexTypeCVRQualifiers(),
2326 vat->getBracketsRange());
2327 break;
2328 }
2329 }
2330
2331 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002332 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002333}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002334
Steve Naroffcadebd02007-08-30 18:14:25 +00002335/// getVariableArrayType - Returns a non-unique reference to the type for a
2336/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002337QualType ASTContext::getVariableArrayType(QualType EltTy,
2338 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002339 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002340 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002341 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002342 // Since we don't unique expressions, it isn't possible to unique VLA's
2343 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002344 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002345
John McCall33ddac02011-01-19 10:06:00 +00002346 // Be sure to pull qualifiers off the element type.
2347 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2348 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002349 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002350 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002351 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002352 }
2353
John McCall90d1c2d2009-09-24 23:30:46 +00002354 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002355 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002356
2357 VariableArrayTypes.push_back(New);
2358 Types.push_back(New);
2359 return QualType(New, 0);
2360}
2361
Douglas Gregor4619e432008-12-05 23:32:09 +00002362/// getDependentSizedArrayType - Returns a non-unique reference to
2363/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002364/// type.
John McCall33ddac02011-01-19 10:06:00 +00002365QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2366 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002367 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002368 unsigned elementTypeQuals,
2369 SourceRange brackets) const {
2370 assert((!numElements || numElements->isTypeDependent() ||
2371 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002372 "Size must be type- or value-dependent!");
2373
John McCall33ddac02011-01-19 10:06:00 +00002374 // Dependently-sized array types that do not have a specified number
2375 // of elements will have their sizes deduced from a dependent
2376 // initializer. We do no canonicalization here at all, which is okay
2377 // because they can't be used in most locations.
2378 if (!numElements) {
2379 DependentSizedArrayType *newType
2380 = new (*this, TypeAlignment)
2381 DependentSizedArrayType(*this, elementType, QualType(),
2382 numElements, ASM, elementTypeQuals,
2383 brackets);
2384 Types.push_back(newType);
2385 return QualType(newType, 0);
2386 }
2387
2388 // Otherwise, we actually build a new type every time, but we
2389 // also build a canonical type.
2390
2391 SplitQualType canonElementType = getCanonicalType(elementType).split();
2392
2393 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002394 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002395 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002396 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002397 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002398
John McCall33ddac02011-01-19 10:06:00 +00002399 // Look for an existing type with these properties.
2400 DependentSizedArrayType *canonTy =
2401 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002402
John McCall33ddac02011-01-19 10:06:00 +00002403 // If we don't have one, build one.
2404 if (!canonTy) {
2405 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002406 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002407 QualType(), numElements, ASM, elementTypeQuals,
2408 brackets);
2409 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2410 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002411 }
2412
John McCall33ddac02011-01-19 10:06:00 +00002413 // Apply qualifiers from the element type to the array.
2414 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002415 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002416
John McCall33ddac02011-01-19 10:06:00 +00002417 // If we didn't need extra canonicalization for the element type,
2418 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002419 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002420 return canon;
2421
2422 // Otherwise, we need to build a type which follows the spelling
2423 // of the element type.
2424 DependentSizedArrayType *sugaredType
2425 = new (*this, TypeAlignment)
2426 DependentSizedArrayType(*this, elementType, canon, numElements,
2427 ASM, elementTypeQuals, brackets);
2428 Types.push_back(sugaredType);
2429 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002430}
2431
John McCall33ddac02011-01-19 10:06:00 +00002432QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002433 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002434 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002435 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002436 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002437
John McCall33ddac02011-01-19 10:06:00 +00002438 void *insertPos = 0;
2439 if (IncompleteArrayType *iat =
2440 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2441 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002442
2443 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002444 // either, so fill in the canonical type field. We also have to pull
2445 // qualifiers off the element type.
2446 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002447
John McCall33ddac02011-01-19 10:06:00 +00002448 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2449 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002450 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002451 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002452 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002453
2454 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002455 IncompleteArrayType *existing =
2456 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2457 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002458 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002459
John McCall33ddac02011-01-19 10:06:00 +00002460 IncompleteArrayType *newType = new (*this, TypeAlignment)
2461 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002462
John McCall33ddac02011-01-19 10:06:00 +00002463 IncompleteArrayTypes.InsertNode(newType, insertPos);
2464 Types.push_back(newType);
2465 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002466}
2467
Steve Naroff91fcddb2007-07-18 18:00:27 +00002468/// getVectorType - Return the unique reference to a vector type of
2469/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002470QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002471 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002472 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002473
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002474 // Check if we've already instantiated a vector of this type.
2475 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002476 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002477
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002478 void *InsertPos = 0;
2479 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2480 return QualType(VTP, 0);
2481
2482 // If the element type isn't canonical, this won't be a canonical type either,
2483 // so fill in the canonical type field.
2484 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002485 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002486 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002487
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002488 // Get the new insert position for the node we care about.
2489 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002490 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002491 }
John McCall90d1c2d2009-09-24 23:30:46 +00002492 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002493 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002494 VectorTypes.InsertNode(New, InsertPos);
2495 Types.push_back(New);
2496 return QualType(New, 0);
2497}
2498
Nate Begemance4d7fc2008-04-18 23:10:10 +00002499/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002500/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002501QualType
2502ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002503 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002504
Steve Naroff91fcddb2007-07-18 18:00:27 +00002505 // Check if we've already instantiated a vector of this type.
2506 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002507 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002508 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002509 void *InsertPos = 0;
2510 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2511 return QualType(VTP, 0);
2512
2513 // If the element type isn't canonical, this won't be a canonical type either,
2514 // so fill in the canonical type field.
2515 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002516 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002517 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002518
Steve Naroff91fcddb2007-07-18 18:00:27 +00002519 // Get the new insert position for the node we care about.
2520 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002521 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002522 }
John McCall90d1c2d2009-09-24 23:30:46 +00002523 ExtVectorType *New = new (*this, TypeAlignment)
2524 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002525 VectorTypes.InsertNode(New, InsertPos);
2526 Types.push_back(New);
2527 return QualType(New, 0);
2528}
2529
Jay Foad39c79802011-01-12 09:06:06 +00002530QualType
2531ASTContext::getDependentSizedExtVectorType(QualType vecType,
2532 Expr *SizeExpr,
2533 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002534 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002535 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002536 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002537
Douglas Gregor352169a2009-07-31 03:54:25 +00002538 void *InsertPos = 0;
2539 DependentSizedExtVectorType *Canon
2540 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2541 DependentSizedExtVectorType *New;
2542 if (Canon) {
2543 // We already have a canonical version of this array type; use it as
2544 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002545 New = new (*this, TypeAlignment)
2546 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2547 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002548 } else {
2549 QualType CanonVecTy = getCanonicalType(vecType);
2550 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002551 New = new (*this, TypeAlignment)
2552 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2553 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002554
2555 DependentSizedExtVectorType *CanonCheck
2556 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2557 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2558 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002559 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2560 } else {
2561 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2562 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002563 New = new (*this, TypeAlignment)
2564 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002565 }
2566 }
Mike Stump11289f42009-09-09 15:08:12 +00002567
Douglas Gregor758a8692009-06-17 21:51:59 +00002568 Types.push_back(New);
2569 return QualType(New, 0);
2570}
2571
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002572/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002573///
Jay Foad39c79802011-01-12 09:06:06 +00002574QualType
2575ASTContext::getFunctionNoProtoType(QualType ResultTy,
2576 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002577 const CallingConv DefaultCC = Info.getCC();
2578 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2579 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002580 // Unique functions, to guarantee there is only one function of a particular
2581 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002582 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002583 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002584
Chris Lattner47955de2007-01-27 08:37:20 +00002585 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002586 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002587 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002588 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002589
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002590 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002591 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002592 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002593 Canonical =
2594 getFunctionNoProtoType(getCanonicalType(ResultTy),
2595 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002596
Chris Lattner47955de2007-01-27 08:37:20 +00002597 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002598 FunctionNoProtoType *NewIP =
2599 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002600 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002601 }
Mike Stump11289f42009-09-09 15:08:12 +00002602
Roman Divacky65b88cd2011-03-01 17:40:53 +00002603 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002604 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002605 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002606 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002607 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002608 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002609}
2610
Douglas Gregorcd780372013-01-17 23:36:45 +00002611/// \brief Determine whether \p T is canonical as the result type of a function.
2612static bool isCanonicalResultType(QualType T) {
2613 return T.isCanonical() &&
2614 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2615 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2616}
2617
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002618/// getFunctionType - Return a normal function type with a typed argument
2619/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002620QualType
2621ASTContext::getFunctionType(QualType ResultTy,
2622 const QualType *ArgArray, unsigned NumArgs,
2623 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002624 // Unique functions, to guarantee there is only one function of a particular
2625 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002626 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002627 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002628
2629 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002630 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002631 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002632 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002633
2634 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002635 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002636 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002637 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002638 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002639 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002640 isCanonical = false;
2641
Roman Divacky65b88cd2011-03-01 17:40:53 +00002642 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2643 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2644 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002645
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002646 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002647 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002648 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002649 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002650 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002651 CanonicalArgs.reserve(NumArgs);
2652 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002653 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002654
John McCalldb40c7f2010-12-14 08:05:40 +00002655 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002656 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002657 CanonicalEPI.ExceptionSpecType = EST_None;
2658 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002659 CanonicalEPI.ExtInfo
2660 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2661
Douglas Gregorcd780372013-01-17 23:36:45 +00002662 // Result types do not have ARC lifetime qualifiers.
2663 QualType CanResultTy = getCanonicalType(ResultTy);
2664 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2665 Qualifiers Qs = CanResultTy.getQualifiers();
2666 Qs.removeObjCLifetime();
2667 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2668 }
2669
2670 Canonical = getFunctionType(CanResultTy,
Jay Foad7d0479f2009-05-21 09:52:38 +00002671 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002672 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002673
Chris Lattnerfd4de792007-01-27 01:15:32 +00002674 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002675 FunctionProtoType *NewIP =
2676 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002677 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002678 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002679
John McCall31168b02011-06-15 23:02:42 +00002680 // FunctionProtoType objects are allocated with extra bytes after
2681 // them for three variable size arrays at the end:
2682 // - parameter types
2683 // - exception types
2684 // - consumed-arguments flags
2685 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002686 // expression, or information used to resolve the exception
2687 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002688 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002689 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002690 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002691 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002692 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002693 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002694 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002695 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002696 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2697 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002698 }
John McCall31168b02011-06-15 23:02:42 +00002699 if (EPI.ConsumedArguments)
2700 Size += NumArgs * sizeof(bool);
2701
John McCalldb40c7f2010-12-14 08:05:40 +00002702 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002703 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2704 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002705 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002706 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002707 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002708 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002709}
Chris Lattneref51c202006-11-10 07:17:23 +00002710
John McCalle78aac42010-03-10 03:28:59 +00002711#ifndef NDEBUG
2712static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2713 if (!isa<CXXRecordDecl>(D)) return false;
2714 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2715 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2716 return true;
2717 if (RD->getDescribedClassTemplate() &&
2718 !isa<ClassTemplateSpecializationDecl>(RD))
2719 return true;
2720 return false;
2721}
2722#endif
2723
2724/// getInjectedClassNameType - Return the unique reference to the
2725/// injected class name type for the specified templated declaration.
2726QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002727 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002728 assert(NeedsInjectedClassNameType(Decl));
2729 if (Decl->TypeForDecl) {
2730 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002731 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002732 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2733 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2734 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2735 } else {
John McCall424cec92011-01-19 06:33:43 +00002736 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002737 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002738 Decl->TypeForDecl = newType;
2739 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002740 }
2741 return QualType(Decl->TypeForDecl, 0);
2742}
2743
Douglas Gregor83a586e2008-04-13 21:07:44 +00002744/// getTypeDeclType - Return the unique reference to the type for the
2745/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002746QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002747 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002748 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002749
Richard Smithdda56e42011-04-15 14:24:37 +00002750 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002751 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002752
John McCall96f0b5f2010-03-10 06:48:02 +00002753 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2754 "Template type parameter types are always available.");
2755
John McCall81e38502010-02-16 03:57:14 +00002756 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002757 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002758 "struct/union has previous declaration");
2759 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002760 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002761 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002762 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002763 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002764 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002765 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002766 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002767 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2768 Decl->TypeForDecl = newType;
2769 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002770 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002771 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002772
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002773 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002774}
2775
Chris Lattner32d920b2007-01-26 02:01:53 +00002776/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002777/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002778QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002779ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2780 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002781 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002782
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002783 if (Canonical.isNull())
2784 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002785 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002786 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002787 Decl->TypeForDecl = newType;
2788 Types.push_back(newType);
2789 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002790}
2791
Jay Foad39c79802011-01-12 09:06:06 +00002792QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002793 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2794
Douglas Gregorec9fd132012-01-14 16:38:05 +00002795 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002796 if (PrevDecl->TypeForDecl)
2797 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2798
John McCall424cec92011-01-19 06:33:43 +00002799 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2800 Decl->TypeForDecl = newType;
2801 Types.push_back(newType);
2802 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002803}
2804
Jay Foad39c79802011-01-12 09:06:06 +00002805QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002806 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2807
Douglas Gregorec9fd132012-01-14 16:38:05 +00002808 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002809 if (PrevDecl->TypeForDecl)
2810 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2811
John McCall424cec92011-01-19 06:33:43 +00002812 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2813 Decl->TypeForDecl = newType;
2814 Types.push_back(newType);
2815 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002816}
2817
John McCall81904512011-01-06 01:58:22 +00002818QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2819 QualType modifiedType,
2820 QualType equivalentType) {
2821 llvm::FoldingSetNodeID id;
2822 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2823
2824 void *insertPos = 0;
2825 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2826 if (type) return QualType(type, 0);
2827
2828 QualType canon = getCanonicalType(equivalentType);
2829 type = new (*this, TypeAlignment)
2830 AttributedType(canon, attrKind, modifiedType, equivalentType);
2831
2832 Types.push_back(type);
2833 AttributedTypes.InsertNode(type, insertPos);
2834
2835 return QualType(type, 0);
2836}
2837
2838
John McCallcebee162009-10-18 09:09:24 +00002839/// \brief Retrieve a substitution-result type.
2840QualType
2841ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002842 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002843 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002844 && "replacement types must always be canonical");
2845
2846 llvm::FoldingSetNodeID ID;
2847 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2848 void *InsertPos = 0;
2849 SubstTemplateTypeParmType *SubstParm
2850 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2851
2852 if (!SubstParm) {
2853 SubstParm = new (*this, TypeAlignment)
2854 SubstTemplateTypeParmType(Parm, Replacement);
2855 Types.push_back(SubstParm);
2856 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2857 }
2858
2859 return QualType(SubstParm, 0);
2860}
2861
Douglas Gregorada4b792011-01-14 02:55:32 +00002862/// \brief Retrieve a
2863QualType ASTContext::getSubstTemplateTypeParmPackType(
2864 const TemplateTypeParmType *Parm,
2865 const TemplateArgument &ArgPack) {
2866#ifndef NDEBUG
2867 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2868 PEnd = ArgPack.pack_end();
2869 P != PEnd; ++P) {
2870 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2871 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2872 }
2873#endif
2874
2875 llvm::FoldingSetNodeID ID;
2876 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2877 void *InsertPos = 0;
2878 if (SubstTemplateTypeParmPackType *SubstParm
2879 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2880 return QualType(SubstParm, 0);
2881
2882 QualType Canon;
2883 if (!Parm->isCanonicalUnqualified()) {
2884 Canon = getCanonicalType(QualType(Parm, 0));
2885 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2886 ArgPack);
2887 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2888 }
2889
2890 SubstTemplateTypeParmPackType *SubstParm
2891 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2892 ArgPack);
2893 Types.push_back(SubstParm);
2894 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2895 return QualType(SubstParm, 0);
2896}
2897
Douglas Gregoreff93e02009-02-05 23:33:38 +00002898/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002899/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002900/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002901QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002902 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002903 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002904 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002905 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002906 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002907 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002908 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2909
2910 if (TypeParm)
2911 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002912
Chandler Carruth08836322011-05-01 00:51:33 +00002913 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002914 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002915 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002916
2917 TemplateTypeParmType *TypeCheck
2918 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2919 assert(!TypeCheck && "Template type parameter canonical type broken");
2920 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002921 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002922 TypeParm = new (*this, TypeAlignment)
2923 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002924
2925 Types.push_back(TypeParm);
2926 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2927
2928 return QualType(TypeParm, 0);
2929}
2930
John McCalle78aac42010-03-10 03:28:59 +00002931TypeSourceInfo *
2932ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2933 SourceLocation NameLoc,
2934 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002935 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002936 assert(!Name.getAsDependentTemplateName() &&
2937 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002938 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002939
2940 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2941 TemplateSpecializationTypeLoc TL
2942 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002943 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002944 TL.setTemplateNameLoc(NameLoc);
2945 TL.setLAngleLoc(Args.getLAngleLoc());
2946 TL.setRAngleLoc(Args.getRAngleLoc());
2947 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2948 TL.setArgLocInfo(i, Args[i].getLocInfo());
2949 return DI;
2950}
2951
Mike Stump11289f42009-09-09 15:08:12 +00002952QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002953ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002954 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002955 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002956 assert(!Template.getAsDependentTemplateName() &&
2957 "No dependent template names here!");
2958
John McCall6b51f282009-11-23 01:53:49 +00002959 unsigned NumArgs = Args.size();
2960
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002961 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002962 ArgVec.reserve(NumArgs);
2963 for (unsigned i = 0; i != NumArgs; ++i)
2964 ArgVec.push_back(Args[i].getArgument());
2965
John McCall2408e322010-04-27 00:57:59 +00002966 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002967 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002968}
2969
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002970#ifndef NDEBUG
2971static bool hasAnyPackExpansions(const TemplateArgument *Args,
2972 unsigned NumArgs) {
2973 for (unsigned I = 0; I != NumArgs; ++I)
2974 if (Args[I].isPackExpansion())
2975 return true;
2976
2977 return true;
2978}
2979#endif
2980
John McCall0ad16662009-10-29 08:12:44 +00002981QualType
2982ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002983 const TemplateArgument *Args,
2984 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002985 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002986 assert(!Template.getAsDependentTemplateName() &&
2987 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002988 // Look through qualified template names.
2989 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2990 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002991
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002992 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002993 Template.getAsTemplateDecl() &&
2994 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002995 QualType CanonType;
2996 if (!Underlying.isNull())
2997 CanonType = getCanonicalType(Underlying);
2998 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002999 // We can get here with an alias template when the specialization contains
3000 // a pack expansion that does not match up with a parameter pack.
3001 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3002 "Caller must compute aliased type");
3003 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003004 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3005 NumArgs);
3006 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003007
Douglas Gregora8e02e72009-07-28 23:00:59 +00003008 // Allocate the (non-canonical) template specialization type, but don't
3009 // try to unique it: these types typically have location information that
3010 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003011 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3012 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003013 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003014 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003015 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003016 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3017 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003018
Douglas Gregor8bf42052009-02-09 18:46:07 +00003019 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003020 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003021}
3022
Mike Stump11289f42009-09-09 15:08:12 +00003023QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003024ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3025 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003026 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003027 assert(!Template.getAsDependentTemplateName() &&
3028 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003029
Douglas Gregore29139c2011-03-03 17:04:51 +00003030 // Look through qualified template names.
3031 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3032 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003033
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003034 // Build the canonical template specialization type.
3035 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003036 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003037 CanonArgs.reserve(NumArgs);
3038 for (unsigned I = 0; I != NumArgs; ++I)
3039 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3040
3041 // Determine whether this canonical template specialization type already
3042 // exists.
3043 llvm::FoldingSetNodeID ID;
3044 TemplateSpecializationType::Profile(ID, CanonTemplate,
3045 CanonArgs.data(), NumArgs, *this);
3046
3047 void *InsertPos = 0;
3048 TemplateSpecializationType *Spec
3049 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3050
3051 if (!Spec) {
3052 // Allocate a new canonical template specialization type.
3053 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3054 sizeof(TemplateArgument) * NumArgs),
3055 TypeAlignment);
3056 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3057 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003058 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003059 Types.push_back(Spec);
3060 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3061 }
3062
3063 assert(Spec->isDependentType() &&
3064 "Non-dependent template-id type must have a canonical type");
3065 return QualType(Spec, 0);
3066}
3067
3068QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003069ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3070 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003071 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003072 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003073 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003074
3075 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003076 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003077 if (T)
3078 return QualType(T, 0);
3079
Douglas Gregorc42075a2010-02-04 18:10:26 +00003080 QualType Canon = NamedType;
3081 if (!Canon.isCanonical()) {
3082 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003083 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3084 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003085 (void)CheckT;
3086 }
3087
Abramo Bagnara6150c882010-05-11 21:36:43 +00003088 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003089 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003090 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003091 return QualType(T, 0);
3092}
3093
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003094QualType
Jay Foad39c79802011-01-12 09:06:06 +00003095ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003096 llvm::FoldingSetNodeID ID;
3097 ParenType::Profile(ID, InnerType);
3098
3099 void *InsertPos = 0;
3100 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3101 if (T)
3102 return QualType(T, 0);
3103
3104 QualType Canon = InnerType;
3105 if (!Canon.isCanonical()) {
3106 Canon = getCanonicalType(InnerType);
3107 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3108 assert(!CheckT && "Paren canonical type broken");
3109 (void)CheckT;
3110 }
3111
3112 T = new (*this) ParenType(InnerType, Canon);
3113 Types.push_back(T);
3114 ParenTypes.InsertNode(T, InsertPos);
3115 return QualType(T, 0);
3116}
3117
Douglas Gregor02085352010-03-31 20:19:30 +00003118QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3119 NestedNameSpecifier *NNS,
3120 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003121 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003122 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3123
3124 if (Canon.isNull()) {
3125 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003126 ElaboratedTypeKeyword CanonKeyword = Keyword;
3127 if (Keyword == ETK_None)
3128 CanonKeyword = ETK_Typename;
3129
3130 if (CanonNNS != NNS || CanonKeyword != Keyword)
3131 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003132 }
3133
3134 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003135 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003136
3137 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003138 DependentNameType *T
3139 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003140 if (T)
3141 return QualType(T, 0);
3142
Douglas Gregor02085352010-03-31 20:19:30 +00003143 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003144 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003145 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003146 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003147}
3148
Mike Stump11289f42009-09-09 15:08:12 +00003149QualType
John McCallc392f372010-06-11 00:33:02 +00003150ASTContext::getDependentTemplateSpecializationType(
3151 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003152 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003153 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003154 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003155 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003156 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003157 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3158 ArgCopy.push_back(Args[I].getArgument());
3159 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3160 ArgCopy.size(),
3161 ArgCopy.data());
3162}
3163
3164QualType
3165ASTContext::getDependentTemplateSpecializationType(
3166 ElaboratedTypeKeyword Keyword,
3167 NestedNameSpecifier *NNS,
3168 const IdentifierInfo *Name,
3169 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003170 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003171 assert((!NNS || NNS->isDependent()) &&
3172 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003173
Douglas Gregorc42075a2010-02-04 18:10:26 +00003174 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003175 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3176 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003177
3178 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003179 DependentTemplateSpecializationType *T
3180 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003181 if (T)
3182 return QualType(T, 0);
3183
John McCallc392f372010-06-11 00:33:02 +00003184 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003185
John McCallc392f372010-06-11 00:33:02 +00003186 ElaboratedTypeKeyword CanonKeyword = Keyword;
3187 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3188
3189 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003190 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003191 for (unsigned I = 0; I != NumArgs; ++I) {
3192 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3193 if (!CanonArgs[I].structurallyEquals(Args[I]))
3194 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003195 }
3196
John McCallc392f372010-06-11 00:33:02 +00003197 QualType Canon;
3198 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3199 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3200 Name, NumArgs,
3201 CanonArgs.data());
3202
3203 // Find the insert position again.
3204 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3205 }
3206
3207 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3208 sizeof(TemplateArgument) * NumArgs),
3209 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003210 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003211 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003212 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003213 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003214 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003215}
3216
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003217QualType ASTContext::getPackExpansionType(QualType Pattern,
3218 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003219 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003220 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003221
3222 assert(Pattern->containsUnexpandedParameterPack() &&
3223 "Pack expansions must expand one or more parameter packs");
3224 void *InsertPos = 0;
3225 PackExpansionType *T
3226 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3227 if (T)
3228 return QualType(T, 0);
3229
3230 QualType Canon;
3231 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003232 Canon = getCanonicalType(Pattern);
3233 // The canonical type might not contain an unexpanded parameter pack, if it
3234 // contains an alias template specialization which ignores one of its
3235 // parameters.
3236 if (Canon->containsUnexpandedParameterPack()) {
3237 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003238
Richard Smith68eea502012-07-16 00:20:35 +00003239 // Find the insert position again, in case we inserted an element into
3240 // PackExpansionTypes and invalidated our insert position.
3241 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3242 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003243 }
3244
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003245 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003246 Types.push_back(T);
3247 PackExpansionTypes.InsertNode(T, InsertPos);
3248 return QualType(T, 0);
3249}
3250
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003251/// CmpProtocolNames - Comparison predicate for sorting protocols
3252/// alphabetically.
3253static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3254 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003255 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003256}
3257
John McCall8b07ec22010-05-15 11:32:37 +00003258static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003259 unsigned NumProtocols) {
3260 if (NumProtocols == 0) return true;
3261
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003262 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3263 return false;
3264
John McCallfc93cf92009-10-22 22:37:11 +00003265 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003266 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3267 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003268 return false;
3269 return true;
3270}
3271
3272static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003273 unsigned &NumProtocols) {
3274 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003275
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003276 // Sort protocols, keyed by name.
3277 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3278
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003279 // Canonicalize.
3280 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3281 Protocols[I] = Protocols[I]->getCanonicalDecl();
3282
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003283 // Remove duplicates.
3284 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3285 NumProtocols = ProtocolsEnd-Protocols;
3286}
3287
John McCall8b07ec22010-05-15 11:32:37 +00003288QualType ASTContext::getObjCObjectType(QualType BaseType,
3289 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003290 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003291 // If the base type is an interface and there aren't any protocols
3292 // to add, then the interface type will do just fine.
3293 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3294 return BaseType;
3295
3296 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003297 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003298 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003299 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003300 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3301 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003302
John McCall8b07ec22010-05-15 11:32:37 +00003303 // Build the canonical type, which has the canonical base type and
3304 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003305 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003306 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3307 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3308 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003309 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003310 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003311 unsigned UniqueCount = NumProtocols;
3312
John McCallfc93cf92009-10-22 22:37:11 +00003313 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003314 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3315 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003316 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003317 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3318 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003319 }
3320
3321 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003322 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3323 }
3324
3325 unsigned Size = sizeof(ObjCObjectTypeImpl);
3326 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3327 void *Mem = Allocate(Size, TypeAlignment);
3328 ObjCObjectTypeImpl *T =
3329 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3330
3331 Types.push_back(T);
3332 ObjCObjectTypes.InsertNode(T, InsertPos);
3333 return QualType(T, 0);
3334}
3335
3336/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3337/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003338QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003339 llvm::FoldingSetNodeID ID;
3340 ObjCObjectPointerType::Profile(ID, ObjectT);
3341
3342 void *InsertPos = 0;
3343 if (ObjCObjectPointerType *QT =
3344 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3345 return QualType(QT, 0);
3346
3347 // Find the canonical object type.
3348 QualType Canonical;
3349 if (!ObjectT.isCanonical()) {
3350 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3351
3352 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003353 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3354 }
3355
Douglas Gregorf85bee62010-02-08 22:59:26 +00003356 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003357 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3358 ObjCObjectPointerType *QType =
3359 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003360
Steve Narofffb4330f2009-06-17 22:40:22 +00003361 Types.push_back(QType);
3362 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003363 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003364}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003365
Douglas Gregor1c283312010-08-11 12:19:30 +00003366/// getObjCInterfaceType - Return the unique reference to the type for the
3367/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003368QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3369 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003370 if (Decl->TypeForDecl)
3371 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003372
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003373 if (PrevDecl) {
3374 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3375 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3376 return QualType(PrevDecl->TypeForDecl, 0);
3377 }
3378
Douglas Gregor7671e532011-12-16 16:34:57 +00003379 // Prefer the definition, if there is one.
3380 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3381 Decl = Def;
3382
Douglas Gregor1c283312010-08-11 12:19:30 +00003383 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3384 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3385 Decl->TypeForDecl = T;
3386 Types.push_back(T);
3387 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003388}
3389
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003390/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3391/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003392/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003393/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003394/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003395QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003396 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003397 if (tofExpr->isTypeDependent()) {
3398 llvm::FoldingSetNodeID ID;
3399 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003400
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003401 void *InsertPos = 0;
3402 DependentTypeOfExprType *Canon
3403 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3404 if (Canon) {
3405 // We already have a "canonical" version of an identical, dependent
3406 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003407 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003408 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003409 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003410 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003411 Canon
3412 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003413 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3414 toe = Canon;
3415 }
3416 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003417 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003418 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003419 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003420 Types.push_back(toe);
3421 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003422}
3423
Steve Naroffa773cd52007-08-01 18:02:17 +00003424/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3425/// TypeOfType AST's. The only motivation to unique these nodes would be
3426/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003427/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003428/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003429QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003430 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003431 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003432 Types.push_back(tot);
3433 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003434}
3435
Anders Carlssonad6bd352009-06-24 21:24:56 +00003436
Anders Carlsson81df7b82009-06-24 19:06:50 +00003437/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3438/// DecltypeType AST's. The only motivation to unique these nodes would be
3439/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003440/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003441/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003442QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003443 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003444
3445 // C++0x [temp.type]p2:
3446 // If an expression e involves a template parameter, decltype(e) denotes a
3447 // unique dependent type. Two such decltype-specifiers refer to the same
3448 // type only if their expressions are equivalent (14.5.6.1).
3449 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003450 llvm::FoldingSetNodeID ID;
3451 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003452
Douglas Gregora21f6c32009-07-30 23:36:40 +00003453 void *InsertPos = 0;
3454 DependentDecltypeType *Canon
3455 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3456 if (Canon) {
3457 // We already have a "canonical" version of an equivalent, dependent
3458 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003459 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003460 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003461 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003462 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003463 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003464 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3465 dt = Canon;
3466 }
3467 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003468 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3469 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003470 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003471 Types.push_back(dt);
3472 return QualType(dt, 0);
3473}
3474
Alexis Hunte852b102011-05-24 22:41:36 +00003475/// getUnaryTransformationType - We don't unique these, since the memory
3476/// savings are minimal and these are rare.
3477QualType ASTContext::getUnaryTransformType(QualType BaseType,
3478 QualType UnderlyingType,
3479 UnaryTransformType::UTTKind Kind)
3480 const {
3481 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003482 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3483 Kind,
3484 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003485 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003486 Types.push_back(Ty);
3487 return QualType(Ty, 0);
3488}
3489
Richard Smithb2bc2e62011-02-21 20:05:19 +00003490/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003491QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003492 void *InsertPos = 0;
3493 if (!DeducedType.isNull()) {
3494 // Look in the folding set for an existing type.
3495 llvm::FoldingSetNodeID ID;
3496 AutoType::Profile(ID, DeducedType);
3497 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3498 return QualType(AT, 0);
3499 }
3500
3501 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3502 Types.push_back(AT);
3503 if (InsertPos)
3504 AutoTypes.InsertNode(AT, InsertPos);
3505 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003506}
3507
Eli Friedman0dfb8892011-10-06 23:00:33 +00003508/// getAtomicType - Return the uniqued reference to the atomic type for
3509/// the given value type.
3510QualType ASTContext::getAtomicType(QualType T) const {
3511 // Unique pointers, to guarantee there is only one pointer of a particular
3512 // structure.
3513 llvm::FoldingSetNodeID ID;
3514 AtomicType::Profile(ID, T);
3515
3516 void *InsertPos = 0;
3517 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3518 return QualType(AT, 0);
3519
3520 // If the atomic value type isn't canonical, this won't be a canonical type
3521 // either, so fill in the canonical type field.
3522 QualType Canonical;
3523 if (!T.isCanonical()) {
3524 Canonical = getAtomicType(getCanonicalType(T));
3525
3526 // Get the new insert position for the node we care about.
3527 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3528 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3529 }
3530 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3531 Types.push_back(New);
3532 AtomicTypes.InsertNode(New, InsertPos);
3533 return QualType(New, 0);
3534}
3535
Richard Smith02e85f32011-04-14 22:09:26 +00003536/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3537QualType ASTContext::getAutoDeductType() const {
3538 if (AutoDeductTy.isNull())
3539 AutoDeductTy = getAutoType(QualType());
3540 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3541 return AutoDeductTy;
3542}
3543
3544/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3545QualType ASTContext::getAutoRRefDeductType() const {
3546 if (AutoRRefDeductTy.isNull())
3547 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3548 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3549 return AutoRRefDeductTy;
3550}
3551
Chris Lattnerfb072462007-01-23 05:45:31 +00003552/// getTagDeclType - Return the unique reference to the type for the
3553/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003554QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003555 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003556 // FIXME: What is the design on getTagDeclType when it requires casting
3557 // away const? mutable?
3558 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003559}
3560
Mike Stump11289f42009-09-09 15:08:12 +00003561/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3562/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3563/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003564CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003565 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003566}
Chris Lattnerfb072462007-01-23 05:45:31 +00003567
Hans Wennborg27541db2011-10-27 08:29:09 +00003568/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3569CanQualType ASTContext::getIntMaxType() const {
3570 return getFromTargetType(Target->getIntMaxType());
3571}
3572
3573/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3574CanQualType ASTContext::getUIntMaxType() const {
3575 return getFromTargetType(Target->getUIntMaxType());
3576}
3577
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003578/// getSignedWCharType - Return the type of "signed wchar_t".
3579/// Used when in C++, as a GCC extension.
3580QualType ASTContext::getSignedWCharType() const {
3581 // FIXME: derive from "Target" ?
3582 return WCharTy;
3583}
3584
3585/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3586/// Used when in C++, as a GCC extension.
3587QualType ASTContext::getUnsignedWCharType() const {
3588 // FIXME: derive from "Target" ?
3589 return UnsignedIntTy;
3590}
3591
Hans Wennborg27541db2011-10-27 08:29:09 +00003592/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003593/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3594QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003595 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003596}
3597
Eli Friedman4e91899e2012-11-27 02:58:24 +00003598/// \brief Return the unique type for "pid_t" defined in
3599/// <sys/types.h>. We need this to compute the correct type for vfork().
3600QualType ASTContext::getProcessIDType() const {
3601 return getFromTargetType(Target->getProcessIDType());
3602}
3603
Chris Lattnera21ad802008-04-02 05:18:44 +00003604//===----------------------------------------------------------------------===//
3605// Type Operators
3606//===----------------------------------------------------------------------===//
3607
Jay Foad39c79802011-01-12 09:06:06 +00003608CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003609 // Push qualifiers into arrays, and then discard any remaining
3610 // qualifiers.
3611 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003612 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003613 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003614 QualType Result;
3615 if (isa<ArrayType>(Ty)) {
3616 Result = getArrayDecayedType(QualType(Ty,0));
3617 } else if (isa<FunctionType>(Ty)) {
3618 Result = getPointerType(QualType(Ty, 0));
3619 } else {
3620 Result = QualType(Ty, 0);
3621 }
3622
3623 return CanQualType::CreateUnsafe(Result);
3624}
3625
John McCall6c9dd522011-01-18 07:41:22 +00003626QualType ASTContext::getUnqualifiedArrayType(QualType type,
3627 Qualifiers &quals) {
3628 SplitQualType splitType = type.getSplitUnqualifiedType();
3629
3630 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3631 // the unqualified desugared type and then drops it on the floor.
3632 // We then have to strip that sugar back off with
3633 // getUnqualifiedDesugaredType(), which is silly.
3634 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003635 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003636
3637 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003638 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003639 quals = splitType.Quals;
3640 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003641 }
3642
John McCall6c9dd522011-01-18 07:41:22 +00003643 // Otherwise, recurse on the array's element type.
3644 QualType elementType = AT->getElementType();
3645 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3646
3647 // If that didn't change the element type, AT has no qualifiers, so we
3648 // can just use the results in splitType.
3649 if (elementType == unqualElementType) {
3650 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003651 quals = splitType.Quals;
3652 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003653 }
3654
3655 // Otherwise, add in the qualifiers from the outermost type, then
3656 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003657 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003658
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003659 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003660 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003661 CAT->getSizeModifier(), 0);
3662 }
3663
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003664 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003665 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003666 }
3667
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003668 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003669 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003670 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003671 VAT->getSizeModifier(),
3672 VAT->getIndexTypeCVRQualifiers(),
3673 VAT->getBracketsRange());
3674 }
3675
3676 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003677 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003678 DSAT->getSizeModifier(), 0,
3679 SourceRange());
3680}
3681
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003682/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3683/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3684/// they point to and return true. If T1 and T2 aren't pointer types
3685/// or pointer-to-member types, or if they are not similar at this
3686/// level, returns false and leaves T1 and T2 unchanged. Top-level
3687/// qualifiers on T1 and T2 are ignored. This function will typically
3688/// be called in a loop that successively "unwraps" pointer and
3689/// pointer-to-member types to compare them at each level.
3690bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3691 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3692 *T2PtrType = T2->getAs<PointerType>();
3693 if (T1PtrType && T2PtrType) {
3694 T1 = T1PtrType->getPointeeType();
3695 T2 = T2PtrType->getPointeeType();
3696 return true;
3697 }
3698
3699 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3700 *T2MPType = T2->getAs<MemberPointerType>();
3701 if (T1MPType && T2MPType &&
3702 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3703 QualType(T2MPType->getClass(), 0))) {
3704 T1 = T1MPType->getPointeeType();
3705 T2 = T2MPType->getPointeeType();
3706 return true;
3707 }
3708
David Blaikiebbafb8a2012-03-11 07:00:24 +00003709 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003710 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3711 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3712 if (T1OPType && T2OPType) {
3713 T1 = T1OPType->getPointeeType();
3714 T2 = T2OPType->getPointeeType();
3715 return true;
3716 }
3717 }
3718
3719 // FIXME: Block pointers, too?
3720
3721 return false;
3722}
3723
Jay Foad39c79802011-01-12 09:06:06 +00003724DeclarationNameInfo
3725ASTContext::getNameForTemplate(TemplateName Name,
3726 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003727 switch (Name.getKind()) {
3728 case TemplateName::QualifiedTemplate:
3729 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003730 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003731 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3732 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003733
John McCalld9dfe3a2011-06-30 08:33:18 +00003734 case TemplateName::OverloadedTemplate: {
3735 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3736 // DNInfo work in progress: CHECKME: what about DNLoc?
3737 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3738 }
3739
3740 case TemplateName::DependentTemplate: {
3741 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003742 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003743 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003744 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3745 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003746 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003747 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3748 // DNInfo work in progress: FIXME: source locations?
3749 DeclarationNameLoc DNLoc;
3750 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3751 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3752 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003753 }
3754 }
3755
John McCalld9dfe3a2011-06-30 08:33:18 +00003756 case TemplateName::SubstTemplateTemplateParm: {
3757 SubstTemplateTemplateParmStorage *subst
3758 = Name.getAsSubstTemplateTemplateParm();
3759 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3760 NameLoc);
3761 }
3762
3763 case TemplateName::SubstTemplateTemplateParmPack: {
3764 SubstTemplateTemplateParmPackStorage *subst
3765 = Name.getAsSubstTemplateTemplateParmPack();
3766 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3767 NameLoc);
3768 }
3769 }
3770
3771 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003772}
3773
Jay Foad39c79802011-01-12 09:06:06 +00003774TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003775 switch (Name.getKind()) {
3776 case TemplateName::QualifiedTemplate:
3777 case TemplateName::Template: {
3778 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003779 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003780 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003781 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3782
3783 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003784 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003785 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003786
John McCalld9dfe3a2011-06-30 08:33:18 +00003787 case TemplateName::OverloadedTemplate:
3788 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003789
John McCalld9dfe3a2011-06-30 08:33:18 +00003790 case TemplateName::DependentTemplate: {
3791 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3792 assert(DTN && "Non-dependent template names must refer to template decls.");
3793 return DTN->CanonicalTemplateName;
3794 }
3795
3796 case TemplateName::SubstTemplateTemplateParm: {
3797 SubstTemplateTemplateParmStorage *subst
3798 = Name.getAsSubstTemplateTemplateParm();
3799 return getCanonicalTemplateName(subst->getReplacement());
3800 }
3801
3802 case TemplateName::SubstTemplateTemplateParmPack: {
3803 SubstTemplateTemplateParmPackStorage *subst
3804 = Name.getAsSubstTemplateTemplateParmPack();
3805 TemplateTemplateParmDecl *canonParameter
3806 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3807 TemplateArgument canonArgPack
3808 = getCanonicalTemplateArgument(subst->getArgumentPack());
3809 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3810 }
3811 }
3812
3813 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003814}
3815
Douglas Gregoradee3e32009-11-11 23:06:43 +00003816bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3817 X = getCanonicalTemplateName(X);
3818 Y = getCanonicalTemplateName(Y);
3819 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3820}
3821
Mike Stump11289f42009-09-09 15:08:12 +00003822TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003823ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003824 switch (Arg.getKind()) {
3825 case TemplateArgument::Null:
3826 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003827
Douglas Gregora8e02e72009-07-28 23:00:59 +00003828 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003829 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003830
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003831 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00003832 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3833 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003834 }
Mike Stump11289f42009-09-09 15:08:12 +00003835
Eli Friedmanb826a002012-09-26 02:36:12 +00003836 case TemplateArgument::NullPtr:
3837 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3838 /*isNullPtr*/true);
3839
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003840 case TemplateArgument::Template:
3841 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003842
3843 case TemplateArgument::TemplateExpansion:
3844 return TemplateArgument(getCanonicalTemplateName(
3845 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003846 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003847
Douglas Gregora8e02e72009-07-28 23:00:59 +00003848 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003849 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003850
Douglas Gregora8e02e72009-07-28 23:00:59 +00003851 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003852 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003853
Douglas Gregora8e02e72009-07-28 23:00:59 +00003854 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003855 if (Arg.pack_size() == 0)
3856 return Arg;
3857
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003858 TemplateArgument *CanonArgs
3859 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003860 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003861 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003862 AEnd = Arg.pack_end();
3863 A != AEnd; (void)++A, ++Idx)
3864 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003865
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003866 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003867 }
3868 }
3869
3870 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003871 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003872}
3873
Douglas Gregor333489b2009-03-27 23:10:48 +00003874NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003875ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003876 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003877 return 0;
3878
3879 switch (NNS->getKind()) {
3880 case NestedNameSpecifier::Identifier:
3881 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003882 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003883 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3884 NNS->getAsIdentifier());
3885
3886 case NestedNameSpecifier::Namespace:
3887 // A namespace is canonical; build a nested-name-specifier with
3888 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003889 return NestedNameSpecifier::Create(*this, 0,
3890 NNS->getAsNamespace()->getOriginalNamespace());
3891
3892 case NestedNameSpecifier::NamespaceAlias:
3893 // A namespace is canonical; build a nested-name-specifier with
3894 // this namespace and no prefix.
3895 return NestedNameSpecifier::Create(*this, 0,
3896 NNS->getAsNamespaceAlias()->getNamespace()
3897 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003898
3899 case NestedNameSpecifier::TypeSpec:
3900 case NestedNameSpecifier::TypeSpecWithTemplate: {
3901 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003902
3903 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3904 // break it apart into its prefix and identifier, then reconsititute those
3905 // as the canonical nested-name-specifier. This is required to canonicalize
3906 // a dependent nested-name-specifier involving typedefs of dependent-name
3907 // types, e.g.,
3908 // typedef typename T::type T1;
3909 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003910 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3911 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003912 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003913
Eli Friedman5358a0a2012-03-03 04:09:56 +00003914 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3915 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3916 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003917 return NestedNameSpecifier::Create(*this, 0, false,
3918 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003919 }
3920
3921 case NestedNameSpecifier::Global:
3922 // The global specifier is canonical and unique.
3923 return NNS;
3924 }
3925
David Blaikie8a40f702012-01-17 06:56:22 +00003926 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003927}
3928
Chris Lattner7adf0762008-08-04 07:31:14 +00003929
Jay Foad39c79802011-01-12 09:06:06 +00003930const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003931 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003932 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003933 // Handle the common positive case fast.
3934 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3935 return AT;
3936 }
Mike Stump11289f42009-09-09 15:08:12 +00003937
John McCall8ccfcb52009-09-24 19:53:00 +00003938 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003939 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003940 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003941
John McCall8ccfcb52009-09-24 19:53:00 +00003942 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003943 // implements C99 6.7.3p8: "If the specification of an array type includes
3944 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003945
Chris Lattner7adf0762008-08-04 07:31:14 +00003946 // If we get here, we either have type qualifiers on the type, or we have
3947 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003948 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003949
John McCall33ddac02011-01-19 10:06:00 +00003950 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003951 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003952
Chris Lattner7adf0762008-08-04 07:31:14 +00003953 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003954 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003955 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003956 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003957
Chris Lattner7adf0762008-08-04 07:31:14 +00003958 // Otherwise, we have an array and we have qualifiers on it. Push the
3959 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003960 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003961
Chris Lattner7adf0762008-08-04 07:31:14 +00003962 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3963 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3964 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003965 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003966 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3967 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3968 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003969 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003970
Mike Stump11289f42009-09-09 15:08:12 +00003971 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003972 = dyn_cast<DependentSizedArrayType>(ATy))
3973 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003974 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003975 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003976 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003977 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003978 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003979
Chris Lattner7adf0762008-08-04 07:31:14 +00003980 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003981 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003982 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003983 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003984 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003985 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003986}
3987
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003988QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003989 // C99 6.7.5.3p7:
3990 // A declaration of a parameter as "array of type" shall be
3991 // adjusted to "qualified pointer to type", where the type
3992 // qualifiers (if any) are those specified within the [ and ] of
3993 // the array type derivation.
3994 if (T->isArrayType())
3995 return getArrayDecayedType(T);
3996
3997 // C99 6.7.5.3p8:
3998 // A declaration of a parameter as "function returning type"
3999 // shall be adjusted to "pointer to function returning type", as
4000 // in 6.3.2.1.
4001 if (T->isFunctionType())
4002 return getPointerType(T);
4003
4004 return T;
4005}
4006
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004007QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004008 T = getVariableArrayDecayedType(T);
4009 T = getAdjustedParameterType(T);
4010 return T.getUnqualifiedType();
4011}
4012
Chris Lattnera21ad802008-04-02 05:18:44 +00004013/// getArrayDecayedType - Return the properly qualified result of decaying the
4014/// specified array type to a pointer. This operation is non-trivial when
4015/// handling typedefs etc. The canonical type of "T" must be an array type,
4016/// this returns a pointer to a properly qualified element of the array.
4017///
4018/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004019QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004020 // Get the element type with 'getAsArrayType' so that we don't lose any
4021 // typedefs in the element type of the array. This also handles propagation
4022 // of type qualifiers from the array type into the element type if present
4023 // (C99 6.7.3p8).
4024 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4025 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004026
Chris Lattner7adf0762008-08-04 07:31:14 +00004027 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004028
4029 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004030 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004031}
4032
John McCall33ddac02011-01-19 10:06:00 +00004033QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4034 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004035}
4036
John McCall33ddac02011-01-19 10:06:00 +00004037QualType ASTContext::getBaseElementType(QualType type) const {
4038 Qualifiers qs;
4039 while (true) {
4040 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004041 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004042 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004043
John McCall33ddac02011-01-19 10:06:00 +00004044 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004045 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004046 }
Mike Stump11289f42009-09-09 15:08:12 +00004047
John McCall33ddac02011-01-19 10:06:00 +00004048 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004049}
4050
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004051/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004052uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004053ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4054 uint64_t ElementCount = 1;
4055 do {
4056 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004057 CA = dyn_cast_or_null<ConstantArrayType>(
4058 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004059 } while (CA);
4060 return ElementCount;
4061}
4062
Steve Naroff0af91202007-04-27 21:51:21 +00004063/// getFloatingRank - Return a relative rank for floating point types.
4064/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004065static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004066 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004067 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004068
John McCall9dd450b2009-09-21 23:43:11 +00004069 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4070 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004071 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004072 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004073 case BuiltinType::Float: return FloatRank;
4074 case BuiltinType::Double: return DoubleRank;
4075 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004076 }
4077}
4078
Mike Stump11289f42009-09-09 15:08:12 +00004079/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4080/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004081/// 'typeDomain' is a real floating point or complex type.
4082/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004083QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4084 QualType Domain) const {
4085 FloatingRank EltRank = getFloatingRank(Size);
4086 if (Domain->isComplexType()) {
4087 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004088 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004089 case FloatRank: return FloatComplexTy;
4090 case DoubleRank: return DoubleComplexTy;
4091 case LongDoubleRank: return LongDoubleComplexTy;
4092 }
Steve Naroff0af91202007-04-27 21:51:21 +00004093 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004094
4095 assert(Domain->isRealFloatingType() && "Unknown domain!");
4096 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004097 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004098 case FloatRank: return FloatTy;
4099 case DoubleRank: return DoubleTy;
4100 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004101 }
David Blaikief47fa302012-01-17 02:30:50 +00004102 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004103}
4104
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004105/// getFloatingTypeOrder - Compare the rank of the two specified floating
4106/// point types, ignoring the domain of the type (i.e. 'double' ==
4107/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004108/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004109int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004110 FloatingRank LHSR = getFloatingRank(LHS);
4111 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004112
Chris Lattnerb90739d2008-04-06 23:38:49 +00004113 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004114 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004115 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004116 return 1;
4117 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004118}
4119
Chris Lattner76a00cf2008-04-06 22:59:24 +00004120/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4121/// routine will assert if passed a built-in type that isn't an integer or enum,
4122/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004123unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004124 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004125
Chris Lattner76a00cf2008-04-06 22:59:24 +00004126 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004127 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004128 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004129 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004130 case BuiltinType::Char_S:
4131 case BuiltinType::Char_U:
4132 case BuiltinType::SChar:
4133 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004134 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004135 case BuiltinType::Short:
4136 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004137 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004138 case BuiltinType::Int:
4139 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004140 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004141 case BuiltinType::Long:
4142 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004143 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004144 case BuiltinType::LongLong:
4145 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004146 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004147 case BuiltinType::Int128:
4148 case BuiltinType::UInt128:
4149 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004150 }
4151}
4152
Eli Friedman629ffb92009-08-20 04:21:42 +00004153/// \brief Whether this is a promotable bitfield reference according
4154/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4155///
4156/// \returns the type this bit-field will promote to, or NULL if no
4157/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004158QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004159 if (E->isTypeDependent() || E->isValueDependent())
4160 return QualType();
4161
Eli Friedman629ffb92009-08-20 04:21:42 +00004162 FieldDecl *Field = E->getBitField();
4163 if (!Field)
4164 return QualType();
4165
4166 QualType FT = Field->getType();
4167
Richard Smithcaf33902011-10-10 18:28:20 +00004168 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004169 uint64_t IntSize = getTypeSize(IntTy);
4170 // GCC extension compatibility: if the bit-field size is less than or equal
4171 // to the size of int, it gets promoted no matter what its type is.
4172 // For instance, unsigned long bf : 4 gets promoted to signed int.
4173 if (BitWidth < IntSize)
4174 return IntTy;
4175
4176 if (BitWidth == IntSize)
4177 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4178
4179 // Types bigger than int are not subject to promotions, and therefore act
4180 // like the base type.
4181 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4182 // is ridiculous.
4183 return QualType();
4184}
4185
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004186/// getPromotedIntegerType - Returns the type that Promotable will
4187/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4188/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004189QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004190 assert(!Promotable.isNull());
4191 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004192 if (const EnumType *ET = Promotable->getAs<EnumType>())
4193 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004194
4195 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4196 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4197 // (3.9.1) can be converted to a prvalue of the first of the following
4198 // types that can represent all the values of its underlying type:
4199 // int, unsigned int, long int, unsigned long int, long long int, or
4200 // unsigned long long int [...]
4201 // FIXME: Is there some better way to compute this?
4202 if (BT->getKind() == BuiltinType::WChar_S ||
4203 BT->getKind() == BuiltinType::WChar_U ||
4204 BT->getKind() == BuiltinType::Char16 ||
4205 BT->getKind() == BuiltinType::Char32) {
4206 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4207 uint64_t FromSize = getTypeSize(BT);
4208 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4209 LongLongTy, UnsignedLongLongTy };
4210 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4211 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4212 if (FromSize < ToSize ||
4213 (FromSize == ToSize &&
4214 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4215 return PromoteTypes[Idx];
4216 }
4217 llvm_unreachable("char type should fit into long long");
4218 }
4219 }
4220
4221 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004222 if (Promotable->isSignedIntegerType())
4223 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004224 uint64_t PromotableSize = getIntWidth(Promotable);
4225 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004226 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4227 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4228}
4229
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004230/// \brief Recurses in pointer/array types until it finds an objc retainable
4231/// type and returns its ownership.
4232Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4233 while (!T.isNull()) {
4234 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4235 return T.getObjCLifetime();
4236 if (T->isArrayType())
4237 T = getBaseElementType(T);
4238 else if (const PointerType *PT = T->getAs<PointerType>())
4239 T = PT->getPointeeType();
4240 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004241 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004242 else
4243 break;
4244 }
4245
4246 return Qualifiers::OCL_None;
4247}
4248
Mike Stump11289f42009-09-09 15:08:12 +00004249/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004250/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004251/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004252int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004253 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4254 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004255 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004256
Chris Lattner76a00cf2008-04-06 22:59:24 +00004257 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4258 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004259
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004260 unsigned LHSRank = getIntegerRank(LHSC);
4261 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004262
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004263 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4264 if (LHSRank == RHSRank) return 0;
4265 return LHSRank > RHSRank ? 1 : -1;
4266 }
Mike Stump11289f42009-09-09 15:08:12 +00004267
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004268 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4269 if (LHSUnsigned) {
4270 // If the unsigned [LHS] type is larger, return it.
4271 if (LHSRank >= RHSRank)
4272 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004273
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004274 // If the signed type can represent all values of the unsigned type, it
4275 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004276 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004277 return -1;
4278 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004279
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004280 // If the unsigned [RHS] type is larger, return it.
4281 if (RHSRank >= LHSRank)
4282 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004283
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004284 // If the signed type can represent all values of the unsigned type, it
4285 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004286 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004287 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004288}
Anders Carlsson98f07902007-08-17 05:31:46 +00004289
Anders Carlsson6d417272009-11-14 21:45:58 +00004290static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004291CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4292 DeclContext *DC, IdentifierInfo *Id) {
4293 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004294 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004295 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004296 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004297 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004298}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004299
Mike Stump11289f42009-09-09 15:08:12 +00004300// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004301QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004302 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004303 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004304 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004305 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004306 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004307
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004308 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004309
Anders Carlsson98f07902007-08-17 05:31:46 +00004310 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004311 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004312 // int flags;
4313 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004314 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004315 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004316 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004317 FieldTypes[3] = LongTy;
4318
Anders Carlsson98f07902007-08-17 05:31:46 +00004319 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004320 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004321 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004322 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004323 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004324 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004325 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004326 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004327 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004328 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004329 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004330 }
4331
Douglas Gregord5058122010-02-11 01:19:42 +00004332 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004333 }
Mike Stump11289f42009-09-09 15:08:12 +00004334
Anders Carlsson98f07902007-08-17 05:31:46 +00004335 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004336}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004337
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004338QualType ASTContext::getObjCSuperType() const {
4339 if (ObjCSuperType.isNull()) {
4340 RecordDecl *ObjCSuperTypeDecl =
4341 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4342 TUDecl->addDecl(ObjCSuperTypeDecl);
4343 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4344 }
4345 return ObjCSuperType;
4346}
4347
Douglas Gregor512b0772009-04-23 22:29:11 +00004348void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004349 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004350 assert(Rec && "Invalid CFConstantStringType");
4351 CFConstantStringTypeDecl = Rec->getDecl();
4352}
4353
Jay Foad39c79802011-01-12 09:06:06 +00004354QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004355 if (BlockDescriptorType)
4356 return getTagDeclType(BlockDescriptorType);
4357
4358 RecordDecl *T;
4359 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004360 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004361 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004362 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004363
4364 QualType FieldTypes[] = {
4365 UnsignedLongTy,
4366 UnsignedLongTy,
4367 };
4368
4369 const char *FieldNames[] = {
4370 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004371 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004372 };
4373
4374 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004375 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004376 SourceLocation(),
4377 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004378 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004379 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004380 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004381 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004382 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004383 T->addDecl(Field);
4384 }
4385
Douglas Gregord5058122010-02-11 01:19:42 +00004386 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004387
4388 BlockDescriptorType = T;
4389
4390 return getTagDeclType(BlockDescriptorType);
4391}
4392
Jay Foad39c79802011-01-12 09:06:06 +00004393QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004394 if (BlockDescriptorExtendedType)
4395 return getTagDeclType(BlockDescriptorExtendedType);
4396
4397 RecordDecl *T;
4398 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004399 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004400 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004401 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004402
4403 QualType FieldTypes[] = {
4404 UnsignedLongTy,
4405 UnsignedLongTy,
4406 getPointerType(VoidPtrTy),
4407 getPointerType(VoidPtrTy)
4408 };
4409
4410 const char *FieldNames[] = {
4411 "reserved",
4412 "Size",
4413 "CopyFuncPtr",
4414 "DestroyFuncPtr"
4415 };
4416
4417 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004418 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004419 SourceLocation(),
4420 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004421 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004422 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004423 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004424 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004425 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004426 T->addDecl(Field);
4427 }
4428
Douglas Gregord5058122010-02-11 01:19:42 +00004429 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004430
4431 BlockDescriptorExtendedType = T;
4432
4433 return getTagDeclType(BlockDescriptorExtendedType);
4434}
4435
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004436/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4437/// requires copy/dispose. Note that this must match the logic
4438/// in buildByrefHelpers.
4439bool ASTContext::BlockRequiresCopying(QualType Ty,
4440 const VarDecl *D) {
4441 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4442 const Expr *copyExpr = getBlockVarCopyInits(D);
4443 if (!copyExpr && record->hasTrivialDestructor()) return false;
4444
Mike Stump94967902009-10-21 18:16:27 +00004445 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004446 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004447
4448 if (!Ty->isObjCRetainableType()) return false;
4449
4450 Qualifiers qs = Ty.getQualifiers();
4451
4452 // If we have lifetime, that dominates.
4453 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4454 assert(getLangOpts().ObjCAutoRefCount);
4455
4456 switch (lifetime) {
4457 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4458
4459 // These are just bits as far as the runtime is concerned.
4460 case Qualifiers::OCL_ExplicitNone:
4461 case Qualifiers::OCL_Autoreleasing:
4462 return false;
4463
4464 // Tell the runtime that this is ARC __weak, called by the
4465 // byref routines.
4466 case Qualifiers::OCL_Weak:
4467 // ARC __strong __block variables need to be retained.
4468 case Qualifiers::OCL_Strong:
4469 return true;
4470 }
4471 llvm_unreachable("fell out of lifetime switch!");
4472 }
4473 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4474 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004475}
4476
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004477bool ASTContext::getByrefLifetime(QualType Ty,
4478 Qualifiers::ObjCLifetime &LifeTime,
4479 bool &HasByrefExtendedLayout) const {
4480
4481 if (!getLangOpts().ObjC1 ||
4482 getLangOpts().getGC() != LangOptions::NonGC)
4483 return false;
4484
4485 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004486 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004487 HasByrefExtendedLayout = true;
4488 LifeTime = Qualifiers::OCL_None;
4489 }
4490 else if (getLangOpts().ObjCAutoRefCount)
4491 LifeTime = Ty.getObjCLifetime();
4492 // MRR.
4493 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4494 LifeTime = Qualifiers::OCL_ExplicitNone;
4495 else
4496 LifeTime = Qualifiers::OCL_None;
4497 return true;
4498}
4499
Douglas Gregorbab8a962011-09-08 01:46:34 +00004500TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4501 if (!ObjCInstanceTypeDecl)
4502 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4503 getTranslationUnitDecl(),
4504 SourceLocation(),
4505 SourceLocation(),
4506 &Idents.get("instancetype"),
4507 getTrivialTypeSourceInfo(getObjCIdType()));
4508 return ObjCInstanceTypeDecl;
4509}
4510
Anders Carlsson18acd442007-10-29 06:33:42 +00004511// This returns true if a type has been typedefed to BOOL:
4512// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004513static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004514 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004515 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4516 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004517
Anders Carlssond8499822007-10-29 05:01:08 +00004518 return false;
4519}
4520
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004521/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004522/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004523CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004524 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4525 return CharUnits::Zero();
4526
Ken Dyck40775002010-01-11 17:06:35 +00004527 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004528
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004529 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004530 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004531 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004532 // Treat arrays as pointers, since that's how they're passed in.
4533 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004534 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004535 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004536}
4537
4538static inline
4539std::string charUnitsToString(const CharUnits &CU) {
4540 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004541}
4542
John McCall351762c2011-02-07 10:33:21 +00004543/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004544/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004545std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4546 std::string S;
4547
David Chisnall950a9512009-11-17 19:33:30 +00004548 const BlockDecl *Decl = Expr->getBlockDecl();
4549 QualType BlockTy =
4550 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4551 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004552 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004553 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4554 BlockTy->getAs<FunctionType>()->getResultType(),
4555 S, true /*Extended*/);
4556 else
4557 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4558 S);
David Chisnall950a9512009-11-17 19:33:30 +00004559 // Compute size of all parameters.
4560 // Start with computing size of a pointer in number of bytes.
4561 // FIXME: There might(should) be a better way of doing this computation!
4562 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004563 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4564 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004565 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004566 E = Decl->param_end(); PI != E; ++PI) {
4567 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004568 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004569 if (sz.isZero())
4570 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004571 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004572 ParmOffset += sz;
4573 }
4574 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004575 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004576 // Block pointer and offset.
4577 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004578
4579 // Argument types.
4580 ParmOffset = PtrSize;
4581 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4582 Decl->param_end(); PI != E; ++PI) {
4583 ParmVarDecl *PVDecl = *PI;
4584 QualType PType = PVDecl->getOriginalType();
4585 if (const ArrayType *AT =
4586 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4587 // Use array's original type only if it has known number of
4588 // elements.
4589 if (!isa<ConstantArrayType>(AT))
4590 PType = PVDecl->getType();
4591 } else if (PType->isFunctionType())
4592 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004593 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004594 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4595 S, true /*Extended*/);
4596 else
4597 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004598 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004599 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004600 }
John McCall351762c2011-02-07 10:33:21 +00004601
4602 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004603}
4604
Douglas Gregora9d84932011-05-27 01:19:52 +00004605bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004606 std::string& S) {
4607 // Encode result type.
4608 getObjCEncodingForType(Decl->getResultType(), S);
4609 CharUnits ParmOffset;
4610 // Compute size of all parameters.
4611 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4612 E = Decl->param_end(); PI != E; ++PI) {
4613 QualType PType = (*PI)->getType();
4614 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004615 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004616 continue;
4617
David Chisnall50e4eba2010-12-30 14:05:53 +00004618 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004619 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004620 ParmOffset += sz;
4621 }
4622 S += charUnitsToString(ParmOffset);
4623 ParmOffset = CharUnits::Zero();
4624
4625 // Argument types.
4626 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4627 E = Decl->param_end(); PI != E; ++PI) {
4628 ParmVarDecl *PVDecl = *PI;
4629 QualType PType = PVDecl->getOriginalType();
4630 if (const ArrayType *AT =
4631 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4632 // Use array's original type only if it has known number of
4633 // elements.
4634 if (!isa<ConstantArrayType>(AT))
4635 PType = PVDecl->getType();
4636 } else if (PType->isFunctionType())
4637 PType = PVDecl->getType();
4638 getObjCEncodingForType(PType, S);
4639 S += charUnitsToString(ParmOffset);
4640 ParmOffset += getObjCEncodingTypeSize(PType);
4641 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004642
4643 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004644}
4645
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004646/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4647/// method parameter or return type. If Extended, include class names and
4648/// block object types.
4649void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4650 QualType T, std::string& S,
4651 bool Extended) const {
4652 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4653 getObjCEncodingForTypeQualifier(QT, S);
4654 // Encode parameter type.
4655 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4656 true /*OutermostType*/,
4657 false /*EncodingProperty*/,
4658 false /*StructField*/,
4659 Extended /*EncodeBlockParameters*/,
4660 Extended /*EncodeClassNames*/);
4661}
4662
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004663/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004664/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004665bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004666 std::string& S,
4667 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004668 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004669 // Encode return type.
4670 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4671 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004672 // Compute size of all parameters.
4673 // Start with computing size of a pointer in number of bytes.
4674 // FIXME: There might(should) be a better way of doing this computation!
4675 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004676 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004677 // The first two arguments (self and _cmd) are pointers; account for
4678 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004679 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004680 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004681 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004682 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004683 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004684 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004685 continue;
4686
Ken Dyck40775002010-01-11 17:06:35 +00004687 assert (sz.isPositive() &&
4688 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004689 ParmOffset += sz;
4690 }
Ken Dyck40775002010-01-11 17:06:35 +00004691 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004692 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004693 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004694
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004695 // Argument types.
4696 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004697 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004698 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004699 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004700 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004701 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004702 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4703 // Use array's original type only if it has known number of
4704 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004705 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004706 PType = PVDecl->getType();
4707 } else if (PType->isFunctionType())
4708 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004709 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4710 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004711 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004712 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004713 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004714
4715 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004716}
4717
Daniel Dunbar4932b362008-08-28 04:38:10 +00004718/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004719/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004720/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4721/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004722/// Property attributes are stored as a comma-delimited C string. The simple
4723/// attributes readonly and bycopy are encoded as single characters. The
4724/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4725/// encoded as single characters, followed by an identifier. Property types
4726/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004727/// these attributes are defined by the following enumeration:
4728/// @code
4729/// enum PropertyAttributes {
4730/// kPropertyReadOnly = 'R', // property is read-only.
4731/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4732/// kPropertyByref = '&', // property is a reference to the value last assigned
4733/// kPropertyDynamic = 'D', // property is dynamic
4734/// kPropertyGetter = 'G', // followed by getter selector name
4735/// kPropertySetter = 'S', // followed by setter selector name
4736/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004737/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004738/// kPropertyWeak = 'W' // 'weak' property
4739/// kPropertyStrong = 'P' // property GC'able
4740/// kPropertyNonAtomic = 'N' // property non-atomic
4741/// };
4742/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004743void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004744 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004745 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004746 // Collect information from the property implementation decl(s).
4747 bool Dynamic = false;
4748 ObjCPropertyImplDecl *SynthesizePID = 0;
4749
4750 // FIXME: Duplicated code due to poor abstraction.
4751 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004752 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004753 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4754 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004755 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004756 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004757 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004758 if (PID->getPropertyDecl() == PD) {
4759 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4760 Dynamic = true;
4761 } else {
4762 SynthesizePID = PID;
4763 }
4764 }
4765 }
4766 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004767 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004768 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004769 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004770 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004771 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004772 if (PID->getPropertyDecl() == PD) {
4773 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4774 Dynamic = true;
4775 } else {
4776 SynthesizePID = PID;
4777 }
4778 }
Mike Stump11289f42009-09-09 15:08:12 +00004779 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004780 }
4781 }
4782
4783 // FIXME: This is not very efficient.
4784 S = "T";
4785
4786 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004787 // GCC has some special rules regarding encoding of properties which
4788 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004789 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004790 true /* outermost type */,
4791 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004792
4793 if (PD->isReadOnly()) {
4794 S += ",R";
4795 } else {
4796 switch (PD->getSetterKind()) {
4797 case ObjCPropertyDecl::Assign: break;
4798 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004799 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004800 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004801 }
4802 }
4803
4804 // It really isn't clear at all what this means, since properties
4805 // are "dynamic by default".
4806 if (Dynamic)
4807 S += ",D";
4808
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004809 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4810 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004811
Daniel Dunbar4932b362008-08-28 04:38:10 +00004812 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4813 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004814 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004815 }
4816
4817 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4818 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004819 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004820 }
4821
4822 if (SynthesizePID) {
4823 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4824 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004825 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004826 }
4827
4828 // FIXME: OBJCGC: weak & strong
4829}
4830
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004831/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004832/// Another legacy compatibility encoding: 32-bit longs are encoded as
4833/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004834/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4835///
4836void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004837 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004838 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004839 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004840 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004841 else
Jay Foad39c79802011-01-12 09:06:06 +00004842 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004843 PointeeTy = IntTy;
4844 }
4845 }
4846}
4847
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004848void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004849 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004850 // We follow the behavior of gcc, expanding structures which are
4851 // directly pointed to, and expanding embedded structures. Note that
4852 // these rules are sufficient to prevent recursive encoding of the
4853 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004854 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004855 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004856}
4857
John McCall393a78d2012-12-20 02:45:14 +00004858static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4859 BuiltinType::Kind kind) {
4860 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004861 case BuiltinType::Void: return 'v';
4862 case BuiltinType::Bool: return 'B';
4863 case BuiltinType::Char_U:
4864 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00004865 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00004866 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00004867 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00004868 case BuiltinType::UInt: return 'I';
4869 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00004870 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004871 case BuiltinType::UInt128: return 'T';
4872 case BuiltinType::ULongLong: return 'Q';
4873 case BuiltinType::Char_S:
4874 case BuiltinType::SChar: return 'c';
4875 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004876 case BuiltinType::WChar_S:
4877 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004878 case BuiltinType::Int: return 'i';
4879 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00004880 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004881 case BuiltinType::LongLong: return 'q';
4882 case BuiltinType::Int128: return 't';
4883 case BuiltinType::Float: return 'f';
4884 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004885 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00004886 case BuiltinType::NullPtr: return '*'; // like char*
4887
4888 case BuiltinType::Half:
4889 // FIXME: potentially need @encodes for these!
4890 return ' ';
4891
4892 case BuiltinType::ObjCId:
4893 case BuiltinType::ObjCClass:
4894 case BuiltinType::ObjCSel:
4895 llvm_unreachable("@encoding ObjC primitive type");
4896
4897 // OpenCL and placeholder types don't need @encodings.
4898 case BuiltinType::OCLImage1d:
4899 case BuiltinType::OCLImage1dArray:
4900 case BuiltinType::OCLImage1dBuffer:
4901 case BuiltinType::OCLImage2d:
4902 case BuiltinType::OCLImage2dArray:
4903 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004904 case BuiltinType::OCLEvent:
John McCall393a78d2012-12-20 02:45:14 +00004905 case BuiltinType::Dependent:
4906#define BUILTIN_TYPE(KIND, ID)
4907#define PLACEHOLDER_TYPE(KIND, ID) \
4908 case BuiltinType::KIND:
4909#include "clang/AST/BuiltinTypes.def"
4910 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00004911 }
David Blaikie5a6a0202013-01-09 17:48:41 +00004912 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00004913}
4914
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004915static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4916 EnumDecl *Enum = ET->getDecl();
4917
4918 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4919 if (!Enum->isFixed())
4920 return 'i';
4921
4922 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00004923 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
4924 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004925}
4926
Jay Foad39c79802011-01-12 09:06:06 +00004927static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004928 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004929 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004930 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004931 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4932 // The GNU runtime requires more information; bitfields are encoded as b,
4933 // then the offset (in bits) of the first element, then the type of the
4934 // bitfield, then the size in bits. For example, in this structure:
4935 //
4936 // struct
4937 // {
4938 // int integer;
4939 // int flags:2;
4940 // };
4941 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4942 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4943 // information is not especially sensible, but we're stuck with it for
4944 // compatibility with GCC, although providing it breaks anything that
4945 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004946 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004947 const RecordDecl *RD = FD->getParent();
4948 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004949 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004950 if (const EnumType *ET = T->getAs<EnumType>())
4951 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00004952 else {
4953 const BuiltinType *BT = T->castAs<BuiltinType>();
4954 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
4955 }
David Chisnallb190a2c2010-06-04 01:10:52 +00004956 }
Richard Smithcaf33902011-10-10 18:28:20 +00004957 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004958}
4959
Daniel Dunbar07d07852009-10-18 21:17:35 +00004960// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004961void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4962 bool ExpandPointedToStructures,
4963 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004964 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004965 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004966 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004967 bool StructField,
4968 bool EncodeBlockParameters,
4969 bool EncodeClassNames) const {
John McCall393a78d2012-12-20 02:45:14 +00004970 CanQualType CT = getCanonicalType(T);
4971 switch (CT->getTypeClass()) {
4972 case Type::Builtin:
4973 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00004974 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004975 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00004976 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
4977 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
4978 else
4979 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00004980 return;
Mike Stump11289f42009-09-09 15:08:12 +00004981
John McCall393a78d2012-12-20 02:45:14 +00004982 case Type::Complex: {
4983 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00004984 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004985 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004986 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004987 return;
4988 }
John McCall393a78d2012-12-20 02:45:14 +00004989
4990 case Type::Atomic: {
4991 const AtomicType *AT = T->castAs<AtomicType>();
4992 S += 'A';
4993 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
4994 false, false);
4995 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004996 }
John McCall393a78d2012-12-20 02:45:14 +00004997
4998 // encoding for pointer or reference types.
4999 case Type::Pointer:
5000 case Type::LValueReference:
5001 case Type::RValueReference: {
5002 QualType PointeeTy;
5003 if (isa<PointerType>(CT)) {
5004 const PointerType *PT = T->castAs<PointerType>();
5005 if (PT->isObjCSelType()) {
5006 S += ':';
5007 return;
5008 }
5009 PointeeTy = PT->getPointeeType();
5010 } else {
5011 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5012 }
5013
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005014 bool isReadOnly = false;
5015 // For historical/compatibility reasons, the read-only qualifier of the
5016 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5017 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005018 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005019 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005020 if (OutermostType && T.isConstQualified()) {
5021 isReadOnly = true;
5022 S += 'r';
5023 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005024 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005025 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005026 while (P->getAs<PointerType>())
5027 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005028 if (P.isConstQualified()) {
5029 isReadOnly = true;
5030 S += 'r';
5031 }
5032 }
5033 if (isReadOnly) {
5034 // Another legacy compatibility encoding. Some ObjC qualifier and type
5035 // combinations need to be rearranged.
5036 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005037 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005038 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005039 }
Mike Stump11289f42009-09-09 15:08:12 +00005040
Anders Carlssond8499822007-10-29 05:01:08 +00005041 if (PointeeTy->isCharType()) {
5042 // char pointer types should be encoded as '*' unless it is a
5043 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005044 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005045 S += '*';
5046 return;
5047 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005048 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005049 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5050 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5051 S += '#';
5052 return;
5053 }
5054 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5055 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5056 S += '@';
5057 return;
5058 }
5059 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005060 }
Anders Carlssond8499822007-10-29 05:01:08 +00005061 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005062 getLegacyIntegralTypeEncoding(PointeeTy);
5063
Mike Stump11289f42009-09-09 15:08:12 +00005064 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005065 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005066 return;
5067 }
John McCall393a78d2012-12-20 02:45:14 +00005068
5069 case Type::ConstantArray:
5070 case Type::IncompleteArray:
5071 case Type::VariableArray: {
5072 const ArrayType *AT = cast<ArrayType>(CT);
5073
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005074 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005075 // Incomplete arrays are encoded as a pointer to the array element.
5076 S += '^';
5077
Mike Stump11289f42009-09-09 15:08:12 +00005078 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005079 false, ExpandStructures, FD);
5080 } else {
5081 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005082
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005083 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5084 if (getTypeSize(CAT->getElementType()) == 0)
5085 S += '0';
5086 else
5087 S += llvm::utostr(CAT->getSize().getZExtValue());
5088 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005089 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005090 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5091 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005092 S += '0';
5093 }
Mike Stump11289f42009-09-09 15:08:12 +00005094
5095 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005096 false, ExpandStructures, FD);
5097 S += ']';
5098 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005099 return;
5100 }
Mike Stump11289f42009-09-09 15:08:12 +00005101
John McCall393a78d2012-12-20 02:45:14 +00005102 case Type::FunctionNoProto:
5103 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005104 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005105 return;
Mike Stump11289f42009-09-09 15:08:12 +00005106
John McCall393a78d2012-12-20 02:45:14 +00005107 case Type::Record: {
5108 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005109 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005110 // Anonymous structures print as '?'
5111 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5112 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005113 if (ClassTemplateSpecializationDecl *Spec
5114 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5115 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5116 std::string TemplateArgsStr
5117 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005118 TemplateArgs.data(),
5119 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005120 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005121
5122 S += TemplateArgsStr;
5123 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005124 } else {
5125 S += '?';
5126 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005127 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005128 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005129 if (!RDecl->isUnion()) {
5130 getObjCEncodingForStructureImpl(RDecl, S, FD);
5131 } else {
5132 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5133 FieldEnd = RDecl->field_end();
5134 Field != FieldEnd; ++Field) {
5135 if (FD) {
5136 S += '"';
5137 S += Field->getNameAsString();
5138 S += '"';
5139 }
Mike Stump11289f42009-09-09 15:08:12 +00005140
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005141 // Special case bit-fields.
5142 if (Field->isBitField()) {
5143 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005144 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005145 } else {
5146 QualType qt = Field->getType();
5147 getLegacyIntegralTypeEncoding(qt);
5148 getObjCEncodingForTypeImpl(qt, S, false, true,
5149 FD, /*OutermostType*/false,
5150 /*EncodingProperty*/false,
5151 /*StructField*/true);
5152 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005153 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005154 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005155 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005156 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005157 return;
5158 }
Mike Stump11289f42009-09-09 15:08:12 +00005159
John McCall393a78d2012-12-20 02:45:14 +00005160 case Type::BlockPointer: {
5161 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005162 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005163 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005164 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005165
5166 S += '<';
5167 // Block return type
5168 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5169 ExpandPointedToStructures, ExpandStructures,
5170 FD,
5171 false /* OutermostType */,
5172 EncodingProperty,
5173 false /* StructField */,
5174 EncodeBlockParameters,
5175 EncodeClassNames);
5176 // Block self
5177 S += "@?";
5178 // Block parameters
5179 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5180 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5181 E = FPT->arg_type_end(); I && (I != E); ++I) {
5182 getObjCEncodingForTypeImpl(*I, S,
5183 ExpandPointedToStructures,
5184 ExpandStructures,
5185 FD,
5186 false /* OutermostType */,
5187 EncodingProperty,
5188 false /* StructField */,
5189 EncodeBlockParameters,
5190 EncodeClassNames);
5191 }
5192 }
5193 S += '>';
5194 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005195 return;
5196 }
Mike Stump11289f42009-09-09 15:08:12 +00005197
John McCall393a78d2012-12-20 02:45:14 +00005198 case Type::ObjCObject:
5199 case Type::ObjCInterface: {
5200 // Ignore protocol qualifiers when mangling at this level.
5201 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005202
John McCall393a78d2012-12-20 02:45:14 +00005203 // The assumption seems to be that this assert will succeed
5204 // because nested levels will have filtered out 'id' and 'Class'.
5205 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005206 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005207 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005208 S += '{';
5209 const IdentifierInfo *II = OI->getIdentifier();
5210 S += II->getName();
5211 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005212 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005213 DeepCollectObjCIvars(OI, true, Ivars);
5214 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005215 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005216 if (Field->isBitField())
5217 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005218 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005219 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005220 }
5221 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005222 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005223 }
Mike Stump11289f42009-09-09 15:08:12 +00005224
John McCall393a78d2012-12-20 02:45:14 +00005225 case Type::ObjCObjectPointer: {
5226 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005227 if (OPT->isObjCIdType()) {
5228 S += '@';
5229 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005230 }
Mike Stump11289f42009-09-09 15:08:12 +00005231
Steve Narofff0c86112009-10-28 22:03:49 +00005232 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5233 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5234 // Since this is a binary compatibility issue, need to consult with runtime
5235 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005236 S += '#';
5237 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005238 }
Mike Stump11289f42009-09-09 15:08:12 +00005239
Chris Lattnere7cabb92009-07-13 00:10:46 +00005240 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005241 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005242 ExpandPointedToStructures,
5243 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005244 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005245 // Note that we do extended encoding of protocol qualifer list
5246 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005247 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005248 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5249 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005250 S += '<';
5251 S += (*I)->getNameAsString();
5252 S += '>';
5253 }
5254 S += '"';
5255 }
5256 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005257 }
Mike Stump11289f42009-09-09 15:08:12 +00005258
Chris Lattnere7cabb92009-07-13 00:10:46 +00005259 QualType PointeeTy = OPT->getPointeeType();
5260 if (!EncodingProperty &&
5261 isa<TypedefType>(PointeeTy.getTypePtr())) {
5262 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005263 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005264 // {...};
5265 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005266 getObjCEncodingForTypeImpl(PointeeTy, S,
5267 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00005268 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005269 return;
5270 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005271
5272 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005273 if (OPT->getInterfaceDecl() &&
5274 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005275 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005276 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005277 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5278 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005279 S += '<';
5280 S += (*I)->getNameAsString();
5281 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005282 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005283 S += '"';
5284 }
5285 return;
5286 }
Mike Stump11289f42009-09-09 15:08:12 +00005287
John McCalla9e6e8d2010-05-17 23:56:34 +00005288 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005289 // FIXME: we shoul do better than that. 'M' is available.
5290 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005291 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005292
John McCall393a78d2012-12-20 02:45:14 +00005293 case Type::Vector:
5294 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005295 // This matches gcc's encoding, even though technically it is
5296 // insufficient.
5297 // FIXME. We should do a better job than gcc.
5298 return;
John McCall393a78d2012-12-20 02:45:14 +00005299
5300#define ABSTRACT_TYPE(KIND, BASE)
5301#define TYPE(KIND, BASE)
5302#define DEPENDENT_TYPE(KIND, BASE) \
5303 case Type::KIND:
5304#define NON_CANONICAL_TYPE(KIND, BASE) \
5305 case Type::KIND:
5306#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5307 case Type::KIND:
5308#include "clang/AST/TypeNodes.def"
5309 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005310 }
John McCall393a78d2012-12-20 02:45:14 +00005311 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005312}
5313
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005314void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5315 std::string &S,
5316 const FieldDecl *FD,
5317 bool includeVBases) const {
5318 assert(RDecl && "Expected non-null RecordDecl");
5319 assert(!RDecl->isUnion() && "Should not be called for unions");
5320 if (!RDecl->getDefinition())
5321 return;
5322
5323 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5324 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5325 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5326
5327 if (CXXRec) {
5328 for (CXXRecordDecl::base_class_iterator
5329 BI = CXXRec->bases_begin(),
5330 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5331 if (!BI->isVirtual()) {
5332 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005333 if (base->isEmpty())
5334 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005335 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005336 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5337 std::make_pair(offs, base));
5338 }
5339 }
5340 }
5341
5342 unsigned i = 0;
5343 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5344 FieldEnd = RDecl->field_end();
5345 Field != FieldEnd; ++Field, ++i) {
5346 uint64_t offs = layout.getFieldOffset(i);
5347 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005348 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005349 }
5350
5351 if (CXXRec && includeVBases) {
5352 for (CXXRecordDecl::base_class_iterator
5353 BI = CXXRec->vbases_begin(),
5354 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5355 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005356 if (base->isEmpty())
5357 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005358 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005359 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5360 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5361 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005362 }
5363 }
5364
5365 CharUnits size;
5366 if (CXXRec) {
5367 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5368 } else {
5369 size = layout.getSize();
5370 }
5371
5372 uint64_t CurOffs = 0;
5373 std::multimap<uint64_t, NamedDecl *>::iterator
5374 CurLayObj = FieldOrBaseOffsets.begin();
5375
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005376 if (CXXRec && CXXRec->isDynamicClass() &&
5377 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005378 if (FD) {
5379 S += "\"_vptr$";
5380 std::string recname = CXXRec->getNameAsString();
5381 if (recname.empty()) recname = "?";
5382 S += recname;
5383 S += '"';
5384 }
5385 S += "^^?";
5386 CurOffs += getTypeSize(VoidPtrTy);
5387 }
5388
5389 if (!RDecl->hasFlexibleArrayMember()) {
5390 // Mark the end of the structure.
5391 uint64_t offs = toBits(size);
5392 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5393 std::make_pair(offs, (NamedDecl*)0));
5394 }
5395
5396 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5397 assert(CurOffs <= CurLayObj->first);
5398
5399 if (CurOffs < CurLayObj->first) {
5400 uint64_t padding = CurLayObj->first - CurOffs;
5401 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5402 // packing/alignment of members is different that normal, in which case
5403 // the encoding will be out-of-sync with the real layout.
5404 // If the runtime switches to just consider the size of types without
5405 // taking into account alignment, we could make padding explicit in the
5406 // encoding (e.g. using arrays of chars). The encoding strings would be
5407 // longer then though.
5408 CurOffs += padding;
5409 }
5410
5411 NamedDecl *dcl = CurLayObj->second;
5412 if (dcl == 0)
5413 break; // reached end of structure.
5414
5415 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5416 // We expand the bases without their virtual bases since those are going
5417 // in the initial structure. Note that this differs from gcc which
5418 // expands virtual bases each time one is encountered in the hierarchy,
5419 // making the encoding type bigger than it really is.
5420 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005421 assert(!base->isEmpty());
5422 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005423 } else {
5424 FieldDecl *field = cast<FieldDecl>(dcl);
5425 if (FD) {
5426 S += '"';
5427 S += field->getNameAsString();
5428 S += '"';
5429 }
5430
5431 if (field->isBitField()) {
5432 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005433 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005434 } else {
5435 QualType qt = field->getType();
5436 getLegacyIntegralTypeEncoding(qt);
5437 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5438 /*OutermostType*/false,
5439 /*EncodingProperty*/false,
5440 /*StructField*/true);
5441 CurOffs += getTypeSize(field->getType());
5442 }
5443 }
5444 }
5445}
5446
Mike Stump11289f42009-09-09 15:08:12 +00005447void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005448 std::string& S) const {
5449 if (QT & Decl::OBJC_TQ_In)
5450 S += 'n';
5451 if (QT & Decl::OBJC_TQ_Inout)
5452 S += 'N';
5453 if (QT & Decl::OBJC_TQ_Out)
5454 S += 'o';
5455 if (QT & Decl::OBJC_TQ_Bycopy)
5456 S += 'O';
5457 if (QT & Decl::OBJC_TQ_Byref)
5458 S += 'R';
5459 if (QT & Decl::OBJC_TQ_Oneway)
5460 S += 'V';
5461}
5462
Douglas Gregor3ea72692011-08-12 05:46:01 +00005463TypedefDecl *ASTContext::getObjCIdDecl() const {
5464 if (!ObjCIdDecl) {
5465 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5466 T = getObjCObjectPointerType(T);
5467 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5468 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5469 getTranslationUnitDecl(),
5470 SourceLocation(), SourceLocation(),
5471 &Idents.get("id"), IdInfo);
5472 }
5473
5474 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005475}
5476
Douglas Gregor52e02802011-08-12 06:17:30 +00005477TypedefDecl *ASTContext::getObjCSelDecl() const {
5478 if (!ObjCSelDecl) {
5479 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5480 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5481 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5482 getTranslationUnitDecl(),
5483 SourceLocation(), SourceLocation(),
5484 &Idents.get("SEL"), SelInfo);
5485 }
5486 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005487}
5488
Douglas Gregor0a586182011-08-12 05:59:41 +00005489TypedefDecl *ASTContext::getObjCClassDecl() const {
5490 if (!ObjCClassDecl) {
5491 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5492 T = getObjCObjectPointerType(T);
5493 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5494 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5495 getTranslationUnitDecl(),
5496 SourceLocation(), SourceLocation(),
5497 &Idents.get("Class"), ClassInfo);
5498 }
5499
5500 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005501}
5502
Douglas Gregord53ae832012-01-17 18:09:05 +00005503ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5504 if (!ObjCProtocolClassDecl) {
5505 ObjCProtocolClassDecl
5506 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5507 SourceLocation(),
5508 &Idents.get("Protocol"),
5509 /*PrevDecl=*/0,
5510 SourceLocation(), true);
5511 }
5512
5513 return ObjCProtocolClassDecl;
5514}
5515
Meador Inge5d3fb222012-06-16 03:34:49 +00005516//===----------------------------------------------------------------------===//
5517// __builtin_va_list Construction Functions
5518//===----------------------------------------------------------------------===//
5519
5520static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5521 // typedef char* __builtin_va_list;
5522 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5523 TypeSourceInfo *TInfo
5524 = Context->getTrivialTypeSourceInfo(CharPtrType);
5525
5526 TypedefDecl *VaListTypeDecl
5527 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5528 Context->getTranslationUnitDecl(),
5529 SourceLocation(), SourceLocation(),
5530 &Context->Idents.get("__builtin_va_list"),
5531 TInfo);
5532 return VaListTypeDecl;
5533}
5534
5535static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5536 // typedef void* __builtin_va_list;
5537 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5538 TypeSourceInfo *TInfo
5539 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5540
5541 TypedefDecl *VaListTypeDecl
5542 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5543 Context->getTranslationUnitDecl(),
5544 SourceLocation(), SourceLocation(),
5545 &Context->Idents.get("__builtin_va_list"),
5546 TInfo);
5547 return VaListTypeDecl;
5548}
5549
5550static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5551 // typedef struct __va_list_tag {
5552 RecordDecl *VaListTagDecl;
5553
5554 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5555 Context->getTranslationUnitDecl(),
5556 &Context->Idents.get("__va_list_tag"));
5557 VaListTagDecl->startDefinition();
5558
5559 const size_t NumFields = 5;
5560 QualType FieldTypes[NumFields];
5561 const char *FieldNames[NumFields];
5562
5563 // unsigned char gpr;
5564 FieldTypes[0] = Context->UnsignedCharTy;
5565 FieldNames[0] = "gpr";
5566
5567 // unsigned char fpr;
5568 FieldTypes[1] = Context->UnsignedCharTy;
5569 FieldNames[1] = "fpr";
5570
5571 // unsigned short reserved;
5572 FieldTypes[2] = Context->UnsignedShortTy;
5573 FieldNames[2] = "reserved";
5574
5575 // void* overflow_arg_area;
5576 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5577 FieldNames[3] = "overflow_arg_area";
5578
5579 // void* reg_save_area;
5580 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5581 FieldNames[4] = "reg_save_area";
5582
5583 // Create fields
5584 for (unsigned i = 0; i < NumFields; ++i) {
5585 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5586 SourceLocation(),
5587 SourceLocation(),
5588 &Context->Idents.get(FieldNames[i]),
5589 FieldTypes[i], /*TInfo=*/0,
5590 /*BitWidth=*/0,
5591 /*Mutable=*/false,
5592 ICIS_NoInit);
5593 Field->setAccess(AS_public);
5594 VaListTagDecl->addDecl(Field);
5595 }
5596 VaListTagDecl->completeDefinition();
5597 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005598 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005599
5600 // } __va_list_tag;
5601 TypedefDecl *VaListTagTypedefDecl
5602 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5603 Context->getTranslationUnitDecl(),
5604 SourceLocation(), SourceLocation(),
5605 &Context->Idents.get("__va_list_tag"),
5606 Context->getTrivialTypeSourceInfo(VaListTagType));
5607 QualType VaListTagTypedefType =
5608 Context->getTypedefType(VaListTagTypedefDecl);
5609
5610 // typedef __va_list_tag __builtin_va_list[1];
5611 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5612 QualType VaListTagArrayType
5613 = Context->getConstantArrayType(VaListTagTypedefType,
5614 Size, ArrayType::Normal, 0);
5615 TypeSourceInfo *TInfo
5616 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5617 TypedefDecl *VaListTypedefDecl
5618 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5619 Context->getTranslationUnitDecl(),
5620 SourceLocation(), SourceLocation(),
5621 &Context->Idents.get("__builtin_va_list"),
5622 TInfo);
5623
5624 return VaListTypedefDecl;
5625}
5626
5627static TypedefDecl *
5628CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5629 // typedef struct __va_list_tag {
5630 RecordDecl *VaListTagDecl;
5631 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5632 Context->getTranslationUnitDecl(),
5633 &Context->Idents.get("__va_list_tag"));
5634 VaListTagDecl->startDefinition();
5635
5636 const size_t NumFields = 4;
5637 QualType FieldTypes[NumFields];
5638 const char *FieldNames[NumFields];
5639
5640 // unsigned gp_offset;
5641 FieldTypes[0] = Context->UnsignedIntTy;
5642 FieldNames[0] = "gp_offset";
5643
5644 // unsigned fp_offset;
5645 FieldTypes[1] = Context->UnsignedIntTy;
5646 FieldNames[1] = "fp_offset";
5647
5648 // void* overflow_arg_area;
5649 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5650 FieldNames[2] = "overflow_arg_area";
5651
5652 // void* reg_save_area;
5653 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5654 FieldNames[3] = "reg_save_area";
5655
5656 // Create fields
5657 for (unsigned i = 0; i < NumFields; ++i) {
5658 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5659 VaListTagDecl,
5660 SourceLocation(),
5661 SourceLocation(),
5662 &Context->Idents.get(FieldNames[i]),
5663 FieldTypes[i], /*TInfo=*/0,
5664 /*BitWidth=*/0,
5665 /*Mutable=*/false,
5666 ICIS_NoInit);
5667 Field->setAccess(AS_public);
5668 VaListTagDecl->addDecl(Field);
5669 }
5670 VaListTagDecl->completeDefinition();
5671 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005672 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005673
5674 // } __va_list_tag;
5675 TypedefDecl *VaListTagTypedefDecl
5676 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5677 Context->getTranslationUnitDecl(),
5678 SourceLocation(), SourceLocation(),
5679 &Context->Idents.get("__va_list_tag"),
5680 Context->getTrivialTypeSourceInfo(VaListTagType));
5681 QualType VaListTagTypedefType =
5682 Context->getTypedefType(VaListTagTypedefDecl);
5683
5684 // typedef __va_list_tag __builtin_va_list[1];
5685 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5686 QualType VaListTagArrayType
5687 = Context->getConstantArrayType(VaListTagTypedefType,
5688 Size, ArrayType::Normal,0);
5689 TypeSourceInfo *TInfo
5690 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5691 TypedefDecl *VaListTypedefDecl
5692 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5693 Context->getTranslationUnitDecl(),
5694 SourceLocation(), SourceLocation(),
5695 &Context->Idents.get("__builtin_va_list"),
5696 TInfo);
5697
5698 return VaListTypedefDecl;
5699}
5700
5701static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5702 // typedef int __builtin_va_list[4];
5703 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5704 QualType IntArrayType
5705 = Context->getConstantArrayType(Context->IntTy,
5706 Size, ArrayType::Normal, 0);
5707 TypedefDecl *VaListTypedefDecl
5708 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5709 Context->getTranslationUnitDecl(),
5710 SourceLocation(), SourceLocation(),
5711 &Context->Idents.get("__builtin_va_list"),
5712 Context->getTrivialTypeSourceInfo(IntArrayType));
5713
5714 return VaListTypedefDecl;
5715}
5716
Logan Chien57086ce2012-10-10 06:56:20 +00005717static TypedefDecl *
5718CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5719 RecordDecl *VaListDecl;
5720 if (Context->getLangOpts().CPlusPlus) {
5721 // namespace std { struct __va_list {
5722 NamespaceDecl *NS;
5723 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5724 Context->getTranslationUnitDecl(),
5725 /*Inline*/false, SourceLocation(),
5726 SourceLocation(), &Context->Idents.get("std"),
5727 /*PrevDecl*/0);
5728
5729 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5730 Context->getTranslationUnitDecl(),
5731 SourceLocation(), SourceLocation(),
5732 &Context->Idents.get("__va_list"));
5733
5734 VaListDecl->setDeclContext(NS);
5735
5736 } else {
5737 // struct __va_list {
5738 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5739 Context->getTranslationUnitDecl(),
5740 &Context->Idents.get("__va_list"));
5741 }
5742
5743 VaListDecl->startDefinition();
5744
5745 // void * __ap;
5746 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5747 VaListDecl,
5748 SourceLocation(),
5749 SourceLocation(),
5750 &Context->Idents.get("__ap"),
5751 Context->getPointerType(Context->VoidTy),
5752 /*TInfo=*/0,
5753 /*BitWidth=*/0,
5754 /*Mutable=*/false,
5755 ICIS_NoInit);
5756 Field->setAccess(AS_public);
5757 VaListDecl->addDecl(Field);
5758
5759 // };
5760 VaListDecl->completeDefinition();
5761
5762 // typedef struct __va_list __builtin_va_list;
5763 TypeSourceInfo *TInfo
5764 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5765
5766 TypedefDecl *VaListTypeDecl
5767 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5768 Context->getTranslationUnitDecl(),
5769 SourceLocation(), SourceLocation(),
5770 &Context->Idents.get("__builtin_va_list"),
5771 TInfo);
5772
5773 return VaListTypeDecl;
5774}
5775
Meador Inge5d3fb222012-06-16 03:34:49 +00005776static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5777 TargetInfo::BuiltinVaListKind Kind) {
5778 switch (Kind) {
5779 case TargetInfo::CharPtrBuiltinVaList:
5780 return CreateCharPtrBuiltinVaListDecl(Context);
5781 case TargetInfo::VoidPtrBuiltinVaList:
5782 return CreateVoidPtrBuiltinVaListDecl(Context);
5783 case TargetInfo::PowerABIBuiltinVaList:
5784 return CreatePowerABIBuiltinVaListDecl(Context);
5785 case TargetInfo::X86_64ABIBuiltinVaList:
5786 return CreateX86_64ABIBuiltinVaListDecl(Context);
5787 case TargetInfo::PNaClABIBuiltinVaList:
5788 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00005789 case TargetInfo::AAPCSABIBuiltinVaList:
5790 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00005791 }
5792
5793 llvm_unreachable("Unhandled __builtin_va_list type kind");
5794}
5795
5796TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5797 if (!BuiltinVaListDecl)
5798 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5799
5800 return BuiltinVaListDecl;
5801}
5802
Meador Ingecfb60902012-07-01 15:57:25 +00005803QualType ASTContext::getVaListTagType() const {
5804 // Force the creation of VaListTagTy by building the __builtin_va_list
5805 // declaration.
5806 if (VaListTagTy.isNull())
5807 (void) getBuiltinVaListDecl();
5808
5809 return VaListTagTy;
5810}
5811
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005812void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005813 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005814 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005815
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005816 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005817}
5818
John McCalld28ae272009-12-02 08:04:21 +00005819/// \brief Retrieve the template name that corresponds to a non-empty
5820/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005821TemplateName
5822ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5823 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005824 unsigned size = End - Begin;
5825 assert(size > 1 && "set is not overloaded!");
5826
5827 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5828 size * sizeof(FunctionTemplateDecl*));
5829 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5830
5831 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005832 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005833 NamedDecl *D = *I;
5834 assert(isa<FunctionTemplateDecl>(D) ||
5835 (isa<UsingShadowDecl>(D) &&
5836 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5837 *Storage++ = D;
5838 }
5839
5840 return TemplateName(OT);
5841}
5842
Douglas Gregordc572a32009-03-30 22:58:21 +00005843/// \brief Retrieve the template name that represents a qualified
5844/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005845TemplateName
5846ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5847 bool TemplateKeyword,
5848 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005849 assert(NNS && "Missing nested-name-specifier in qualified template name");
5850
Douglas Gregorc42075a2010-02-04 18:10:26 +00005851 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005852 llvm::FoldingSetNodeID ID;
5853 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5854
5855 void *InsertPos = 0;
5856 QualifiedTemplateName *QTN =
5857 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5858 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00005859 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5860 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00005861 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5862 }
5863
5864 return TemplateName(QTN);
5865}
5866
5867/// \brief Retrieve the template name that represents a dependent
5868/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005869TemplateName
5870ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5871 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005872 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005873 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005874
5875 llvm::FoldingSetNodeID ID;
5876 DependentTemplateName::Profile(ID, NNS, Name);
5877
5878 void *InsertPos = 0;
5879 DependentTemplateName *QTN =
5880 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5881
5882 if (QTN)
5883 return TemplateName(QTN);
5884
5885 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5886 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005887 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5888 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00005889 } else {
5890 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00005891 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5892 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005893 DependentTemplateName *CheckQTN =
5894 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5895 assert(!CheckQTN && "Dependent type name canonicalization broken");
5896 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005897 }
5898
5899 DependentTemplateNames.InsertNode(QTN, InsertPos);
5900 return TemplateName(QTN);
5901}
5902
Douglas Gregor71395fa2009-11-04 00:56:37 +00005903/// \brief Retrieve the template name that represents a dependent
5904/// template name such as \c MetaFun::template operator+.
5905TemplateName
5906ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005907 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005908 assert((!NNS || NNS->isDependent()) &&
5909 "Nested name specifier must be dependent");
5910
5911 llvm::FoldingSetNodeID ID;
5912 DependentTemplateName::Profile(ID, NNS, Operator);
5913
5914 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005915 DependentTemplateName *QTN
5916 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005917
5918 if (QTN)
5919 return TemplateName(QTN);
5920
5921 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5922 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005923 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5924 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005925 } else {
5926 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00005927 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5928 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005929
5930 DependentTemplateName *CheckQTN
5931 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5932 assert(!CheckQTN && "Dependent template name canonicalization broken");
5933 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005934 }
5935
5936 DependentTemplateNames.InsertNode(QTN, InsertPos);
5937 return TemplateName(QTN);
5938}
5939
Douglas Gregor5590be02011-01-15 06:45:20 +00005940TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005941ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5942 TemplateName replacement) const {
5943 llvm::FoldingSetNodeID ID;
5944 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5945
5946 void *insertPos = 0;
5947 SubstTemplateTemplateParmStorage *subst
5948 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5949
5950 if (!subst) {
5951 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5952 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5953 }
5954
5955 return TemplateName(subst);
5956}
5957
5958TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005959ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5960 const TemplateArgument &ArgPack) const {
5961 ASTContext &Self = const_cast<ASTContext &>(*this);
5962 llvm::FoldingSetNodeID ID;
5963 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5964
5965 void *InsertPos = 0;
5966 SubstTemplateTemplateParmPackStorage *Subst
5967 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5968
5969 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005970 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005971 ArgPack.pack_size(),
5972 ArgPack.pack_begin());
5973 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5974 }
5975
5976 return TemplateName(Subst);
5977}
5978
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005979/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005980/// TargetInfo, produce the corresponding type. The unsigned @p Type
5981/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005982CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005983 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005984 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005985 case TargetInfo::SignedShort: return ShortTy;
5986 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5987 case TargetInfo::SignedInt: return IntTy;
5988 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5989 case TargetInfo::SignedLong: return LongTy;
5990 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5991 case TargetInfo::SignedLongLong: return LongLongTy;
5992 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5993 }
5994
David Blaikie83d382b2011-09-23 05:06:16 +00005995 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005996}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005997
5998//===----------------------------------------------------------------------===//
5999// Type Predicates.
6000//===----------------------------------------------------------------------===//
6001
Fariborz Jahanian96207692009-02-18 21:49:28 +00006002/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6003/// garbage collection attribute.
6004///
John McCall553d45a2011-01-12 00:34:59 +00006005Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006006 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006007 return Qualifiers::GCNone;
6008
David Blaikiebbafb8a2012-03-11 07:00:24 +00006009 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006010 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6011
6012 // Default behaviour under objective-C's gc is for ObjC pointers
6013 // (or pointers to them) be treated as though they were declared
6014 // as __strong.
6015 if (GCAttrs == Qualifiers::GCNone) {
6016 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6017 return Qualifiers::Strong;
6018 else if (Ty->isPointerType())
6019 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6020 } else {
6021 // It's not valid to set GC attributes on anything that isn't a
6022 // pointer.
6023#ifndef NDEBUG
6024 QualType CT = Ty->getCanonicalTypeInternal();
6025 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6026 CT = AT->getElementType();
6027 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6028#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006029 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006030 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006031}
6032
Chris Lattner49af6a42008-04-07 06:51:04 +00006033//===----------------------------------------------------------------------===//
6034// Type Compatibility Testing
6035//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006036
Mike Stump11289f42009-09-09 15:08:12 +00006037/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006038/// compatible.
6039static bool areCompatVectorTypes(const VectorType *LHS,
6040 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006041 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006042 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006043 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006044}
6045
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006046bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6047 QualType SecondVec) {
6048 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6049 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6050
6051 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6052 return true;
6053
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006054 // Treat Neon vector types and most AltiVec vector types as if they are the
6055 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006056 const VectorType *First = FirstVec->getAs<VectorType>();
6057 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006058 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006059 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006060 First->getVectorKind() != VectorType::AltiVecPixel &&
6061 First->getVectorKind() != VectorType::AltiVecBool &&
6062 Second->getVectorKind() != VectorType::AltiVecPixel &&
6063 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006064 return true;
6065
6066 return false;
6067}
6068
Steve Naroff8e6aee52009-07-23 01:01:38 +00006069//===----------------------------------------------------------------------===//
6070// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6071//===----------------------------------------------------------------------===//
6072
6073/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6074/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006075bool
6076ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6077 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006078 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006079 return true;
6080 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6081 E = rProto->protocol_end(); PI != E; ++PI)
6082 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6083 return true;
6084 return false;
6085}
6086
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006087/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00006088/// return true if lhs's protocols conform to rhs's protocol; false
6089/// otherwise.
6090bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6091 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6092 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6093 return false;
6094}
6095
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006096/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6097/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006098bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6099 QualType rhs) {
6100 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6101 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6102 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6103
6104 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6105 E = lhsQID->qual_end(); I != E; ++I) {
6106 bool match = false;
6107 ObjCProtocolDecl *lhsProto = *I;
6108 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6109 E = rhsOPT->qual_end(); J != E; ++J) {
6110 ObjCProtocolDecl *rhsProto = *J;
6111 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6112 match = true;
6113 break;
6114 }
6115 }
6116 if (!match)
6117 return false;
6118 }
6119 return true;
6120}
6121
Steve Naroff8e6aee52009-07-23 01:01:38 +00006122/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6123/// ObjCQualifiedIDType.
6124bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6125 bool compare) {
6126 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006127 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006128 lhs->isObjCIdType() || lhs->isObjCClassType())
6129 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006130 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006131 rhs->isObjCIdType() || rhs->isObjCClassType())
6132 return true;
6133
6134 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006135 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006136
Steve Naroff8e6aee52009-07-23 01:01:38 +00006137 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006138
Steve Naroff8e6aee52009-07-23 01:01:38 +00006139 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006140 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006141 // make sure we check the class hierarchy.
6142 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6143 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6144 E = lhsQID->qual_end(); I != E; ++I) {
6145 // when comparing an id<P> on lhs with a static type on rhs,
6146 // see if static class implements all of id's protocols, directly or
6147 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006148 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006149 return false;
6150 }
6151 }
6152 // If there are no qualifiers and no interface, we have an 'id'.
6153 return true;
6154 }
Mike Stump11289f42009-09-09 15:08:12 +00006155 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006156 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6157 E = lhsQID->qual_end(); I != E; ++I) {
6158 ObjCProtocolDecl *lhsProto = *I;
6159 bool match = false;
6160
6161 // when comparing an id<P> on lhs with a static type on rhs,
6162 // see if static class implements all of id's protocols, directly or
6163 // through its super class and categories.
6164 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6165 E = rhsOPT->qual_end(); J != E; ++J) {
6166 ObjCProtocolDecl *rhsProto = *J;
6167 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6168 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6169 match = true;
6170 break;
6171 }
6172 }
Mike Stump11289f42009-09-09 15:08:12 +00006173 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006174 // make sure we check the class hierarchy.
6175 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6176 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6177 E = lhsQID->qual_end(); I != E; ++I) {
6178 // when comparing an id<P> on lhs with a static type on rhs,
6179 // see if static class implements all of id's protocols, directly or
6180 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006181 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006182 match = true;
6183 break;
6184 }
6185 }
6186 }
6187 if (!match)
6188 return false;
6189 }
Mike Stump11289f42009-09-09 15:08:12 +00006190
Steve Naroff8e6aee52009-07-23 01:01:38 +00006191 return true;
6192 }
Mike Stump11289f42009-09-09 15:08:12 +00006193
Steve Naroff8e6aee52009-07-23 01:01:38 +00006194 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6195 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6196
Mike Stump11289f42009-09-09 15:08:12 +00006197 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006198 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006199 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006200 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6201 E = lhsOPT->qual_end(); I != E; ++I) {
6202 ObjCProtocolDecl *lhsProto = *I;
6203 bool match = false;
6204
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006205 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006206 // see if static class implements all of id's protocols, directly or
6207 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006208 // First, lhs protocols in the qualifier list must be found, direct
6209 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006210 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6211 E = rhsQID->qual_end(); J != E; ++J) {
6212 ObjCProtocolDecl *rhsProto = *J;
6213 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6214 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6215 match = true;
6216 break;
6217 }
6218 }
6219 if (!match)
6220 return false;
6221 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006222
6223 // Static class's protocols, or its super class or category protocols
6224 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6225 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6226 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6227 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6228 // This is rather dubious but matches gcc's behavior. If lhs has
6229 // no type qualifier and its class has no static protocol(s)
6230 // assume that it is mismatch.
6231 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6232 return false;
6233 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6234 LHSInheritedProtocols.begin(),
6235 E = LHSInheritedProtocols.end(); I != E; ++I) {
6236 bool match = false;
6237 ObjCProtocolDecl *lhsProto = (*I);
6238 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6239 E = rhsQID->qual_end(); J != E; ++J) {
6240 ObjCProtocolDecl *rhsProto = *J;
6241 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6242 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6243 match = true;
6244 break;
6245 }
6246 }
6247 if (!match)
6248 return false;
6249 }
6250 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006251 return true;
6252 }
6253 return false;
6254}
6255
Eli Friedman47f77112008-08-22 00:56:42 +00006256/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006257/// compatible for assignment from RHS to LHS. This handles validation of any
6258/// protocol qualifiers on the LHS or RHS.
6259///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006260bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6261 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006262 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6263 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6264
Steve Naroff1329fa02009-07-15 18:40:39 +00006265 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006266 if (LHS->isObjCUnqualifiedIdOrClass() ||
6267 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006268 return true;
6269
John McCall8b07ec22010-05-15 11:32:37 +00006270 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006271 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6272 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006273 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006274
6275 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6276 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6277 QualType(RHSOPT,0));
6278
John McCall8b07ec22010-05-15 11:32:37 +00006279 // If we have 2 user-defined types, fall into that path.
6280 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006281 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006282
Steve Naroff8e6aee52009-07-23 01:01:38 +00006283 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006284}
6285
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006286/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006287/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006288/// arguments in block literals. When passed as arguments, passing 'A*' where
6289/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6290/// not OK. For the return type, the opposite is not OK.
6291bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6292 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006293 const ObjCObjectPointerType *RHSOPT,
6294 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006295 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006296 return true;
6297
6298 if (LHSOPT->isObjCBuiltinType()) {
6299 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6300 }
6301
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006302 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006303 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6304 QualType(RHSOPT,0),
6305 false);
6306
6307 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6308 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6309 if (LHS && RHS) { // We have 2 user-defined types.
6310 if (LHS != RHS) {
6311 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006312 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006313 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006314 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006315 }
6316 else
6317 return true;
6318 }
6319 return false;
6320}
6321
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006322/// getIntersectionOfProtocols - This routine finds the intersection of set
6323/// of protocols inherited from two distinct objective-c pointer objects.
6324/// It is used to build composite qualifier list of the composite type of
6325/// the conditional expression involving two objective-c pointer objects.
6326static
6327void getIntersectionOfProtocols(ASTContext &Context,
6328 const ObjCObjectPointerType *LHSOPT,
6329 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006330 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006331
John McCall8b07ec22010-05-15 11:32:37 +00006332 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6333 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6334 assert(LHS->getInterface() && "LHS must have an interface base");
6335 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006336
6337 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6338 unsigned LHSNumProtocols = LHS->getNumProtocols();
6339 if (LHSNumProtocols > 0)
6340 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6341 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006342 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006343 Context.CollectInheritedProtocols(LHS->getInterface(),
6344 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006345 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6346 LHSInheritedProtocols.end());
6347 }
6348
6349 unsigned RHSNumProtocols = RHS->getNumProtocols();
6350 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006351 ObjCProtocolDecl **RHSProtocols =
6352 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006353 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6354 if (InheritedProtocolSet.count(RHSProtocols[i]))
6355 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006356 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006357 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006358 Context.CollectInheritedProtocols(RHS->getInterface(),
6359 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006360 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6361 RHSInheritedProtocols.begin(),
6362 E = RHSInheritedProtocols.end(); I != E; ++I)
6363 if (InheritedProtocolSet.count((*I)))
6364 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006365 }
6366}
6367
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006368/// areCommonBaseCompatible - Returns common base class of the two classes if
6369/// one found. Note that this is O'2 algorithm. But it will be called as the
6370/// last type comparison in a ?-exp of ObjC pointer types before a
6371/// warning is issued. So, its invokation is extremely rare.
6372QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006373 const ObjCObjectPointerType *Lptr,
6374 const ObjCObjectPointerType *Rptr) {
6375 const ObjCObjectType *LHS = Lptr->getObjectType();
6376 const ObjCObjectType *RHS = Rptr->getObjectType();
6377 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6378 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006379 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006380 return QualType();
6381
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006382 do {
John McCall8b07ec22010-05-15 11:32:37 +00006383 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006384 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006385 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006386 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6387
6388 QualType Result = QualType(LHS, 0);
6389 if (!Protocols.empty())
6390 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6391 Result = getObjCObjectPointerType(Result);
6392 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006393 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006394 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006395
6396 return QualType();
6397}
6398
John McCall8b07ec22010-05-15 11:32:37 +00006399bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6400 const ObjCObjectType *RHS) {
6401 assert(LHS->getInterface() && "LHS is not an interface type");
6402 assert(RHS->getInterface() && "RHS is not an interface type");
6403
Chris Lattner49af6a42008-04-07 06:51:04 +00006404 // Verify that the base decls are compatible: the RHS must be a subclass of
6405 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006406 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006407 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006408
Chris Lattner49af6a42008-04-07 06:51:04 +00006409 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6410 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006411 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006412 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006413
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006414 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6415 // more detailed analysis is required.
6416 if (RHS->getNumProtocols() == 0) {
6417 // OK, if LHS is a superclass of RHS *and*
6418 // this superclass is assignment compatible with LHS.
6419 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006420 bool IsSuperClass =
6421 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6422 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006423 // OK if conversion of LHS to SuperClass results in narrowing of types
6424 // ; i.e., SuperClass may implement at least one of the protocols
6425 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6426 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6427 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006428 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006429 // If super class has no protocols, it is not a match.
6430 if (SuperClassInheritedProtocols.empty())
6431 return false;
6432
6433 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6434 LHSPE = LHS->qual_end();
6435 LHSPI != LHSPE; LHSPI++) {
6436 bool SuperImplementsProtocol = false;
6437 ObjCProtocolDecl *LHSProto = (*LHSPI);
6438
6439 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6440 SuperClassInheritedProtocols.begin(),
6441 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6442 ObjCProtocolDecl *SuperClassProto = (*I);
6443 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6444 SuperImplementsProtocol = true;
6445 break;
6446 }
6447 }
6448 if (!SuperImplementsProtocol)
6449 return false;
6450 }
6451 return true;
6452 }
6453 return false;
6454 }
Mike Stump11289f42009-09-09 15:08:12 +00006455
John McCall8b07ec22010-05-15 11:32:37 +00006456 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6457 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006458 LHSPI != LHSPE; LHSPI++) {
6459 bool RHSImplementsProtocol = false;
6460
6461 // If the RHS doesn't implement the protocol on the left, the types
6462 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006463 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6464 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006465 RHSPI != RHSPE; RHSPI++) {
6466 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006467 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006468 break;
6469 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006470 }
6471 // FIXME: For better diagnostics, consider passing back the protocol name.
6472 if (!RHSImplementsProtocol)
6473 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006474 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006475 // The RHS implements all protocols listed on the LHS.
6476 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006477}
6478
Steve Naroffb7605152009-02-12 17:52:19 +00006479bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6480 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006481 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6482 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006483
Steve Naroff7cae42b2009-07-10 23:34:53 +00006484 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006485 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006486
6487 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6488 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006489}
6490
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006491bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6492 return canAssignObjCInterfaces(
6493 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6494 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6495}
6496
Mike Stump11289f42009-09-09 15:08:12 +00006497/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006498/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006499/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006500/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006501bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6502 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006503 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006504 return hasSameType(LHS, RHS);
6505
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006506 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006507}
6508
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006509bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006510 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006511}
6512
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006513bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6514 return !mergeTypes(LHS, RHS, true).isNull();
6515}
6516
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006517/// mergeTransparentUnionType - if T is a transparent union type and a member
6518/// of T is compatible with SubType, return the merged type, else return
6519/// QualType()
6520QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6521 bool OfBlockPointer,
6522 bool Unqualified) {
6523 if (const RecordType *UT = T->getAsUnionType()) {
6524 RecordDecl *UD = UT->getDecl();
6525 if (UD->hasAttr<TransparentUnionAttr>()) {
6526 for (RecordDecl::field_iterator it = UD->field_begin(),
6527 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006528 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006529 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6530 if (!MT.isNull())
6531 return MT;
6532 }
6533 }
6534 }
6535
6536 return QualType();
6537}
6538
6539/// mergeFunctionArgumentTypes - merge two types which appear as function
6540/// argument types
6541QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6542 bool OfBlockPointer,
6543 bool Unqualified) {
6544 // GNU extension: two types are compatible if they appear as a function
6545 // argument, one of the types is a transparent union type and the other
6546 // type is compatible with a union member
6547 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6548 Unqualified);
6549 if (!lmerge.isNull())
6550 return lmerge;
6551
6552 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6553 Unqualified);
6554 if (!rmerge.isNull())
6555 return rmerge;
6556
6557 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6558}
6559
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006560QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006561 bool OfBlockPointer,
6562 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006563 const FunctionType *lbase = lhs->getAs<FunctionType>();
6564 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006565 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6566 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006567 bool allLTypes = true;
6568 bool allRTypes = true;
6569
6570 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006571 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006572 if (OfBlockPointer) {
6573 QualType RHS = rbase->getResultType();
6574 QualType LHS = lbase->getResultType();
6575 bool UnqualifiedResult = Unqualified;
6576 if (!UnqualifiedResult)
6577 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006578 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006579 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006580 else
John McCall8c6b56f2010-12-15 01:06:38 +00006581 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6582 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006583 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006584
6585 if (Unqualified)
6586 retType = retType.getUnqualifiedType();
6587
6588 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6589 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6590 if (Unqualified) {
6591 LRetType = LRetType.getUnqualifiedType();
6592 RRetType = RRetType.getUnqualifiedType();
6593 }
6594
6595 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006596 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006597 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006598 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006599
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006600 // FIXME: double check this
6601 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6602 // rbase->getRegParmAttr() != 0 &&
6603 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006604 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6605 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006606
Douglas Gregor8c940862010-01-18 17:14:39 +00006607 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006608 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006609 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006610
John McCall8c6b56f2010-12-15 01:06:38 +00006611 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006612 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6613 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006614 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6615 return QualType();
6616
John McCall31168b02011-06-15 23:02:42 +00006617 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6618 return QualType();
6619
John McCall8c6b56f2010-12-15 01:06:38 +00006620 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6621 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006622
Rafael Espindola8778c282012-11-29 16:09:03 +00006623 if (lbaseInfo.getNoReturn() != NoReturn)
6624 allLTypes = false;
6625 if (rbaseInfo.getNoReturn() != NoReturn)
6626 allRTypes = false;
6627
John McCall31168b02011-06-15 23:02:42 +00006628 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006629
Eli Friedman47f77112008-08-22 00:56:42 +00006630 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006631 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6632 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006633 unsigned lproto_nargs = lproto->getNumArgs();
6634 unsigned rproto_nargs = rproto->getNumArgs();
6635
6636 // Compatible functions must have the same number of arguments
6637 if (lproto_nargs != rproto_nargs)
6638 return QualType();
6639
6640 // Variadic and non-variadic functions aren't compatible
6641 if (lproto->isVariadic() != rproto->isVariadic())
6642 return QualType();
6643
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006644 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6645 return QualType();
6646
Fariborz Jahanian97676972011-09-28 21:52:05 +00006647 if (LangOpts.ObjCAutoRefCount &&
6648 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6649 return QualType();
6650
Eli Friedman47f77112008-08-22 00:56:42 +00006651 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006652 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006653 for (unsigned i = 0; i < lproto_nargs; i++) {
6654 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6655 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006656 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6657 OfBlockPointer,
6658 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006659 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006660
6661 if (Unqualified)
6662 argtype = argtype.getUnqualifiedType();
6663
Eli Friedman47f77112008-08-22 00:56:42 +00006664 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006665 if (Unqualified) {
6666 largtype = largtype.getUnqualifiedType();
6667 rargtype = rargtype.getUnqualifiedType();
6668 }
6669
Chris Lattner465fa322008-10-05 17:34:18 +00006670 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6671 allLTypes = false;
6672 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6673 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006674 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006675
Eli Friedman47f77112008-08-22 00:56:42 +00006676 if (allLTypes) return lhs;
6677 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006678
6679 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6680 EPI.ExtInfo = einfo;
6681 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006682 }
6683
6684 if (lproto) allRTypes = false;
6685 if (rproto) allLTypes = false;
6686
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006687 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006688 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006689 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006690 if (proto->isVariadic()) return QualType();
6691 // Check that the types are compatible with the types that
6692 // would result from default argument promotions (C99 6.7.5.3p15).
6693 // The only types actually affected are promotable integer
6694 // types and floats, which would be passed as a different
6695 // type depending on whether the prototype is visible.
6696 unsigned proto_nargs = proto->getNumArgs();
6697 for (unsigned i = 0; i < proto_nargs; ++i) {
6698 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006699
Eli Friedman448ce402012-08-30 00:44:15 +00006700 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006701 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00006702 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6703 argTy = Enum->getDecl()->getIntegerType();
6704 if (argTy.isNull())
6705 return QualType();
6706 }
Douglas Gregor2973d402010-02-03 19:27:29 +00006707
Eli Friedman47f77112008-08-22 00:56:42 +00006708 if (argTy->isPromotableIntegerType() ||
6709 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6710 return QualType();
6711 }
6712
6713 if (allLTypes) return lhs;
6714 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006715
6716 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6717 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006718 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006719 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006720 }
6721
6722 if (allLTypes) return lhs;
6723 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006724 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006725}
6726
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006727QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006728 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006729 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006730 // C++ [expr]: If an expression initially has the type "reference to T", the
6731 // type is adjusted to "T" prior to any further analysis, the expression
6732 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006733 // expression is an lvalue unless the reference is an rvalue reference and
6734 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006735 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6736 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006737
6738 if (Unqualified) {
6739 LHS = LHS.getUnqualifiedType();
6740 RHS = RHS.getUnqualifiedType();
6741 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006742
Eli Friedman47f77112008-08-22 00:56:42 +00006743 QualType LHSCan = getCanonicalType(LHS),
6744 RHSCan = getCanonicalType(RHS);
6745
6746 // If two types are identical, they are compatible.
6747 if (LHSCan == RHSCan)
6748 return LHS;
6749
John McCall8ccfcb52009-09-24 19:53:00 +00006750 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006751 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6752 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006753 if (LQuals != RQuals) {
6754 // If any of these qualifiers are different, we have a type
6755 // mismatch.
6756 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006757 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6758 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006759 return QualType();
6760
6761 // Exactly one GC qualifier difference is allowed: __strong is
6762 // okay if the other type has no GC qualifier but is an Objective
6763 // C object pointer (i.e. implicitly strong by default). We fix
6764 // this by pretending that the unqualified type was actually
6765 // qualified __strong.
6766 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6767 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6768 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6769
6770 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6771 return QualType();
6772
6773 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6774 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6775 }
6776 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6777 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6778 }
Eli Friedman47f77112008-08-22 00:56:42 +00006779 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006780 }
6781
6782 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006783
Eli Friedmandcca6332009-06-01 01:22:52 +00006784 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6785 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006786
Chris Lattnerfd652912008-01-14 05:45:46 +00006787 // We want to consider the two function types to be the same for these
6788 // comparisons, just force one to the other.
6789 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6790 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006791
6792 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006793 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6794 LHSClass = Type::ConstantArray;
6795 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6796 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006797
John McCall8b07ec22010-05-15 11:32:37 +00006798 // ObjCInterfaces are just specialized ObjCObjects.
6799 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6800 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6801
Nate Begemance4d7fc2008-04-18 23:10:10 +00006802 // Canonicalize ExtVector -> Vector.
6803 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6804 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006805
Chris Lattner95554662008-04-07 05:43:21 +00006806 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006807 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006808 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006809 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006810 // Compatibility is based on the underlying type, not the promotion
6811 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006812 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006813 QualType TINT = ETy->getDecl()->getIntegerType();
6814 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006815 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006816 }
John McCall9dd450b2009-09-21 23:43:11 +00006817 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006818 QualType TINT = ETy->getDecl()->getIntegerType();
6819 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006820 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006821 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006822 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006823 if (OfBlockPointer && !BlockReturnType) {
6824 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6825 return LHS;
6826 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6827 return RHS;
6828 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006829
Eli Friedman47f77112008-08-22 00:56:42 +00006830 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006831 }
Eli Friedman47f77112008-08-22 00:56:42 +00006832
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006833 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006834 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006835#define TYPE(Class, Base)
6836#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006837#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006838#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6839#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6840#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006841 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006842
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006843 case Type::LValueReference:
6844 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006845 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006846 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006847
John McCall8b07ec22010-05-15 11:32:37 +00006848 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006849 case Type::IncompleteArray:
6850 case Type::VariableArray:
6851 case Type::FunctionProto:
6852 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006853 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006854
Chris Lattnerfd652912008-01-14 05:45:46 +00006855 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006856 {
6857 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006858 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6859 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006860 if (Unqualified) {
6861 LHSPointee = LHSPointee.getUnqualifiedType();
6862 RHSPointee = RHSPointee.getUnqualifiedType();
6863 }
6864 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6865 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006866 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006867 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006868 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006869 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006870 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006871 return getPointerType(ResultType);
6872 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006873 case Type::BlockPointer:
6874 {
6875 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006876 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6877 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006878 if (Unqualified) {
6879 LHSPointee = LHSPointee.getUnqualifiedType();
6880 RHSPointee = RHSPointee.getUnqualifiedType();
6881 }
6882 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6883 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006884 if (ResultType.isNull()) return QualType();
6885 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6886 return LHS;
6887 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6888 return RHS;
6889 return getBlockPointerType(ResultType);
6890 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006891 case Type::Atomic:
6892 {
6893 // Merge two pointer types, while trying to preserve typedef info
6894 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6895 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6896 if (Unqualified) {
6897 LHSValue = LHSValue.getUnqualifiedType();
6898 RHSValue = RHSValue.getUnqualifiedType();
6899 }
6900 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6901 Unqualified);
6902 if (ResultType.isNull()) return QualType();
6903 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6904 return LHS;
6905 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6906 return RHS;
6907 return getAtomicType(ResultType);
6908 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006909 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006910 {
6911 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6912 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6913 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6914 return QualType();
6915
6916 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6917 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006918 if (Unqualified) {
6919 LHSElem = LHSElem.getUnqualifiedType();
6920 RHSElem = RHSElem.getUnqualifiedType();
6921 }
6922
6923 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006924 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006925 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6926 return LHS;
6927 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6928 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006929 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6930 ArrayType::ArraySizeModifier(), 0);
6931 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6932 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006933 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6934 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006935 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6936 return LHS;
6937 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6938 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006939 if (LVAT) {
6940 // FIXME: This isn't correct! But tricky to implement because
6941 // the array's size has to be the size of LHS, but the type
6942 // has to be different.
6943 return LHS;
6944 }
6945 if (RVAT) {
6946 // FIXME: This isn't correct! But tricky to implement because
6947 // the array's size has to be the size of RHS, but the type
6948 // has to be different.
6949 return RHS;
6950 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006951 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6952 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006953 return getIncompleteArrayType(ResultType,
6954 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006955 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006956 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006957 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006958 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006959 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006960 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006961 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006962 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006963 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006964 case Type::Complex:
6965 // Distinct complex types are incompatible.
6966 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006967 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006968 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006969 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6970 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006971 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006972 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006973 case Type::ObjCObject: {
6974 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006975 // FIXME: This should be type compatibility, e.g. whether
6976 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006977 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6978 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6979 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006980 return LHS;
6981
Eli Friedman47f77112008-08-22 00:56:42 +00006982 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006983 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006984 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006985 if (OfBlockPointer) {
6986 if (canAssignObjCInterfacesInBlockPointer(
6987 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006988 RHS->getAs<ObjCObjectPointerType>(),
6989 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006990 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006991 return QualType();
6992 }
John McCall9dd450b2009-09-21 23:43:11 +00006993 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6994 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006995 return LHS;
6996
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006997 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006998 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006999 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007000
David Blaikie8a40f702012-01-17 06:56:22 +00007001 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007002}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007003
Fariborz Jahanian97676972011-09-28 21:52:05 +00007004bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7005 const FunctionProtoType *FromFunctionType,
7006 const FunctionProtoType *ToFunctionType) {
7007 if (FromFunctionType->hasAnyConsumedArgs() !=
7008 ToFunctionType->hasAnyConsumedArgs())
7009 return false;
7010 FunctionProtoType::ExtProtoInfo FromEPI =
7011 FromFunctionType->getExtProtoInfo();
7012 FunctionProtoType::ExtProtoInfo ToEPI =
7013 ToFunctionType->getExtProtoInfo();
7014 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7015 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7016 ArgIdx != NumArgs; ++ArgIdx) {
7017 if (FromEPI.ConsumedArguments[ArgIdx] !=
7018 ToEPI.ConsumedArguments[ArgIdx])
7019 return false;
7020 }
7021 return true;
7022}
7023
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007024/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7025/// 'RHS' attributes and returns the merged version; including for function
7026/// return types.
7027QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7028 QualType LHSCan = getCanonicalType(LHS),
7029 RHSCan = getCanonicalType(RHS);
7030 // If two types are identical, they are compatible.
7031 if (LHSCan == RHSCan)
7032 return LHS;
7033 if (RHSCan->isFunctionType()) {
7034 if (!LHSCan->isFunctionType())
7035 return QualType();
7036 QualType OldReturnType =
7037 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7038 QualType NewReturnType =
7039 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7040 QualType ResReturnType =
7041 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7042 if (ResReturnType.isNull())
7043 return QualType();
7044 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7045 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7046 // In either case, use OldReturnType to build the new function type.
7047 const FunctionType *F = LHS->getAs<FunctionType>();
7048 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007049 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7050 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007051 QualType ResultType
7052 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00007053 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007054 return ResultType;
7055 }
7056 }
7057 return QualType();
7058 }
7059
7060 // If the qualifiers are different, the types can still be merged.
7061 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7062 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7063 if (LQuals != RQuals) {
7064 // If any of these qualifiers are different, we have a type mismatch.
7065 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7066 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7067 return QualType();
7068
7069 // Exactly one GC qualifier difference is allowed: __strong is
7070 // okay if the other type has no GC qualifier but is an Objective
7071 // C object pointer (i.e. implicitly strong by default). We fix
7072 // this by pretending that the unqualified type was actually
7073 // qualified __strong.
7074 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7075 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7076 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7077
7078 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7079 return QualType();
7080
7081 if (GC_L == Qualifiers::Strong)
7082 return LHS;
7083 if (GC_R == Qualifiers::Strong)
7084 return RHS;
7085 return QualType();
7086 }
7087
7088 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7089 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7090 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7091 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7092 if (ResQT == LHSBaseQT)
7093 return LHS;
7094 if (ResQT == RHSBaseQT)
7095 return RHS;
7096 }
7097 return QualType();
7098}
7099
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007100//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007101// Integer Predicates
7102//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007103
Jay Foad39c79802011-01-12 09:06:06 +00007104unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00007105 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00007106 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007107 if (T->isBooleanType())
7108 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007109 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007110 return (unsigned)getTypeSize(T);
7111}
7112
Abramo Bagnara13640492012-09-09 10:21:24 +00007113QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007114 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007115
7116 // Turn <4 x signed int> -> <4 x unsigned int>
7117 if (const VectorType *VTy = T->getAs<VectorType>())
7118 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007119 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007120
7121 // For enums, we return the unsigned version of the base type.
7122 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007123 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007124
7125 const BuiltinType *BTy = T->getAs<BuiltinType>();
7126 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007127 switch (BTy->getKind()) {
7128 case BuiltinType::Char_S:
7129 case BuiltinType::SChar:
7130 return UnsignedCharTy;
7131 case BuiltinType::Short:
7132 return UnsignedShortTy;
7133 case BuiltinType::Int:
7134 return UnsignedIntTy;
7135 case BuiltinType::Long:
7136 return UnsignedLongTy;
7137 case BuiltinType::LongLong:
7138 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007139 case BuiltinType::Int128:
7140 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007141 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007142 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007143 }
7144}
7145
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007146ASTMutationListener::~ASTMutationListener() { }
7147
Chris Lattnerecd79c62009-06-14 00:45:47 +00007148
7149//===----------------------------------------------------------------------===//
7150// Builtin Type Computation
7151//===----------------------------------------------------------------------===//
7152
7153/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007154/// pointer over the consumed characters. This returns the resultant type. If
7155/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7156/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7157/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007158///
7159/// RequiresICE is filled in on return to indicate whether the value is required
7160/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007161static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007162 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007163 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007164 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007165 // Modifiers.
7166 int HowLong = 0;
7167 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007168 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007169
Chris Lattnerdc226c22010-10-01 22:42:38 +00007170 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007171 bool Done = false;
7172 while (!Done) {
7173 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007174 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007175 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007176 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007177 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007178 case 'S':
7179 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7180 assert(!Signed && "Can't use 'S' modifier multiple times!");
7181 Signed = true;
7182 break;
7183 case 'U':
7184 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7185 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7186 Unsigned = true;
7187 break;
7188 case 'L':
7189 assert(HowLong <= 2 && "Can't have LLLL modifier");
7190 ++HowLong;
7191 break;
7192 }
7193 }
7194
7195 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007196
Chris Lattnerecd79c62009-06-14 00:45:47 +00007197 // Read the base type.
7198 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007199 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007200 case 'v':
7201 assert(HowLong == 0 && !Signed && !Unsigned &&
7202 "Bad modifiers used with 'v'!");
7203 Type = Context.VoidTy;
7204 break;
7205 case 'f':
7206 assert(HowLong == 0 && !Signed && !Unsigned &&
7207 "Bad modifiers used with 'f'!");
7208 Type = Context.FloatTy;
7209 break;
7210 case 'd':
7211 assert(HowLong < 2 && !Signed && !Unsigned &&
7212 "Bad modifiers used with 'd'!");
7213 if (HowLong)
7214 Type = Context.LongDoubleTy;
7215 else
7216 Type = Context.DoubleTy;
7217 break;
7218 case 's':
7219 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7220 if (Unsigned)
7221 Type = Context.UnsignedShortTy;
7222 else
7223 Type = Context.ShortTy;
7224 break;
7225 case 'i':
7226 if (HowLong == 3)
7227 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7228 else if (HowLong == 2)
7229 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7230 else if (HowLong == 1)
7231 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7232 else
7233 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7234 break;
7235 case 'c':
7236 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7237 if (Signed)
7238 Type = Context.SignedCharTy;
7239 else if (Unsigned)
7240 Type = Context.UnsignedCharTy;
7241 else
7242 Type = Context.CharTy;
7243 break;
7244 case 'b': // boolean
7245 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7246 Type = Context.BoolTy;
7247 break;
7248 case 'z': // size_t.
7249 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7250 Type = Context.getSizeType();
7251 break;
7252 case 'F':
7253 Type = Context.getCFConstantStringType();
7254 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007255 case 'G':
7256 Type = Context.getObjCIdType();
7257 break;
7258 case 'H':
7259 Type = Context.getObjCSelType();
7260 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007261 case 'M':
7262 Type = Context.getObjCSuperType();
7263 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007264 case 'a':
7265 Type = Context.getBuiltinVaListType();
7266 assert(!Type.isNull() && "builtin va list type not initialized!");
7267 break;
7268 case 'A':
7269 // This is a "reference" to a va_list; however, what exactly
7270 // this means depends on how va_list is defined. There are two
7271 // different kinds of va_list: ones passed by value, and ones
7272 // passed by reference. An example of a by-value va_list is
7273 // x86, where va_list is a char*. An example of by-ref va_list
7274 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7275 // we want this argument to be a char*&; for x86-64, we want
7276 // it to be a __va_list_tag*.
7277 Type = Context.getBuiltinVaListType();
7278 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007279 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007280 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007281 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007282 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007283 break;
7284 case 'V': {
7285 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007286 unsigned NumElements = strtoul(Str, &End, 10);
7287 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007288 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007289
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007290 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7291 RequiresICE, false);
7292 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007293
7294 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007295 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007296 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007297 break;
7298 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007299 case 'E': {
7300 char *End;
7301
7302 unsigned NumElements = strtoul(Str, &End, 10);
7303 assert(End != Str && "Missing vector size");
7304
7305 Str = End;
7306
7307 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7308 false);
7309 Type = Context.getExtVectorType(ElementType, NumElements);
7310 break;
7311 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007312 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007313 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7314 false);
7315 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007316 Type = Context.getComplexType(ElementType);
7317 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007318 }
7319 case 'Y' : {
7320 Type = Context.getPointerDiffType();
7321 break;
7322 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007323 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007324 Type = Context.getFILEType();
7325 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007326 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007327 return QualType();
7328 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007329 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007330 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007331 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007332 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007333 else
7334 Type = Context.getjmp_bufType();
7335
Mike Stump2adb4da2009-07-28 23:47:15 +00007336 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007337 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007338 return QualType();
7339 }
7340 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007341 case 'K':
7342 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7343 Type = Context.getucontext_tType();
7344
7345 if (Type.isNull()) {
7346 Error = ASTContext::GE_Missing_ucontext;
7347 return QualType();
7348 }
7349 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007350 case 'p':
7351 Type = Context.getProcessIDType();
7352 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007353 }
Mike Stump11289f42009-09-09 15:08:12 +00007354
Chris Lattnerdc226c22010-10-01 22:42:38 +00007355 // If there are modifiers and if we're allowed to parse them, go for it.
7356 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007357 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007358 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007359 default: Done = true; --Str; break;
7360 case '*':
7361 case '&': {
7362 // Both pointers and references can have their pointee types
7363 // qualified with an address space.
7364 char *End;
7365 unsigned AddrSpace = strtoul(Str, &End, 10);
7366 if (End != Str && AddrSpace != 0) {
7367 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7368 Str = End;
7369 }
7370 if (c == '*')
7371 Type = Context.getPointerType(Type);
7372 else
7373 Type = Context.getLValueReferenceType(Type);
7374 break;
7375 }
7376 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7377 case 'C':
7378 Type = Type.withConst();
7379 break;
7380 case 'D':
7381 Type = Context.getVolatileType(Type);
7382 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007383 case 'R':
7384 Type = Type.withRestrict();
7385 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007386 }
7387 }
Chris Lattner84733392010-10-01 07:13:18 +00007388
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007389 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007390 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007391
Chris Lattnerecd79c62009-06-14 00:45:47 +00007392 return Type;
7393}
7394
7395/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007396QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007397 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007398 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007399 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007400
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007401 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007402
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007403 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007404 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007405 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7406 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007407 if (Error != GE_None)
7408 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007409
7410 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7411
Chris Lattnerecd79c62009-06-14 00:45:47 +00007412 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007413 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007414 if (Error != GE_None)
7415 return QualType();
7416
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007417 // If this argument is required to be an IntegerConstantExpression and the
7418 // caller cares, fill in the bitmask we return.
7419 if (RequiresICE && IntegerConstantArgs)
7420 *IntegerConstantArgs |= 1 << ArgTypes.size();
7421
Chris Lattnerecd79c62009-06-14 00:45:47 +00007422 // Do array -> pointer decay. The builtin should use the decayed type.
7423 if (Ty->isArrayType())
7424 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007425
Chris Lattnerecd79c62009-06-14 00:45:47 +00007426 ArgTypes.push_back(Ty);
7427 }
7428
7429 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7430 "'.' should only occur at end of builtin type list!");
7431
John McCall991eb4b2010-12-21 00:44:39 +00007432 FunctionType::ExtInfo EI;
7433 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7434
7435 bool Variadic = (TypeStr[0] == '.');
7436
7437 // We really shouldn't be making a no-proto type here, especially in C++.
7438 if (ArgTypes.empty() && Variadic)
7439 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007440
John McCalldb40c7f2010-12-14 08:05:40 +00007441 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007442 EPI.ExtInfo = EI;
7443 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007444
7445 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007446}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007447
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007448GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7449 GVALinkage External = GVA_StrongExternal;
7450
7451 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007452 switch (L) {
7453 case NoLinkage:
7454 case InternalLinkage:
7455 case UniqueExternalLinkage:
7456 return GVA_Internal;
7457
7458 case ExternalLinkage:
7459 switch (FD->getTemplateSpecializationKind()) {
7460 case TSK_Undeclared:
7461 case TSK_ExplicitSpecialization:
7462 External = GVA_StrongExternal;
7463 break;
7464
7465 case TSK_ExplicitInstantiationDefinition:
7466 return GVA_ExplicitTemplateInstantiation;
7467
7468 case TSK_ExplicitInstantiationDeclaration:
7469 case TSK_ImplicitInstantiation:
7470 External = GVA_TemplateInstantiation;
7471 break;
7472 }
7473 }
7474
7475 if (!FD->isInlined())
7476 return External;
7477
David Blaikiebbafb8a2012-03-11 07:00:24 +00007478 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007479 // GNU or C99 inline semantics. Determine whether this symbol should be
7480 // externally visible.
7481 if (FD->isInlineDefinitionExternallyVisible())
7482 return External;
7483
7484 // C99 inline semantics, where the symbol is not externally visible.
7485 return GVA_C99Inline;
7486 }
7487
7488 // C++0x [temp.explicit]p9:
7489 // [ Note: The intent is that an inline function that is the subject of
7490 // an explicit instantiation declaration will still be implicitly
7491 // instantiated when used so that the body can be considered for
7492 // inlining, but that no out-of-line copy of the inline function would be
7493 // generated in the translation unit. -- end note ]
7494 if (FD->getTemplateSpecializationKind()
7495 == TSK_ExplicitInstantiationDeclaration)
7496 return GVA_C99Inline;
7497
7498 return GVA_CXXInline;
7499}
7500
7501GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7502 // If this is a static data member, compute the kind of template
7503 // specialization. Otherwise, this variable is not part of a
7504 // template.
7505 TemplateSpecializationKind TSK = TSK_Undeclared;
7506 if (VD->isStaticDataMember())
7507 TSK = VD->getTemplateSpecializationKind();
7508
7509 Linkage L = VD->getLinkage();
Rafael Espindola6525f962013-01-02 04:19:07 +00007510 assert (!(L == ExternalLinkage && getLangOpts().CPlusPlus &&
7511 VD->getType()->getLinkage() == UniqueExternalLinkage));
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007512
7513 switch (L) {
7514 case NoLinkage:
7515 case InternalLinkage:
7516 case UniqueExternalLinkage:
7517 return GVA_Internal;
7518
7519 case ExternalLinkage:
7520 switch (TSK) {
7521 case TSK_Undeclared:
7522 case TSK_ExplicitSpecialization:
7523 return GVA_StrongExternal;
7524
7525 case TSK_ExplicitInstantiationDeclaration:
7526 llvm_unreachable("Variable should not be instantiated");
7527 // Fall through to treat this like any other instantiation.
7528
7529 case TSK_ExplicitInstantiationDefinition:
7530 return GVA_ExplicitTemplateInstantiation;
7531
7532 case TSK_ImplicitInstantiation:
7533 return GVA_TemplateInstantiation;
7534 }
7535 }
7536
David Blaikie8a40f702012-01-17 06:56:22 +00007537 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007538}
7539
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007540bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007541 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7542 if (!VD->isFileVarDecl())
7543 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007544 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007545 return false;
7546
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007547 // Weak references don't produce any output by themselves.
7548 if (D->hasAttr<WeakRefAttr>())
7549 return false;
7550
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007551 // Aliases and used decls are required.
7552 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7553 return true;
7554
7555 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7556 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007557 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007558 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007559
7560 // Constructors and destructors are required.
7561 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7562 return true;
7563
John McCall6bd2a892013-01-25 22:31:03 +00007564 // The key function for a class is required. This rule only comes
7565 // into play when inline functions can be key functions, though.
7566 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7567 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7568 const CXXRecordDecl *RD = MD->getParent();
7569 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7570 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7571 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7572 return true;
7573 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007574 }
7575 }
7576
7577 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7578
7579 // static, static inline, always_inline, and extern inline functions can
7580 // always be deferred. Normal inline functions can be deferred in C99/C++.
7581 // Implicit template instantiations can also be deferred in C++.
7582 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007583 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007584 return false;
7585 return true;
7586 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007587
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007588 const VarDecl *VD = cast<VarDecl>(D);
7589 assert(VD->isFileVarDecl() && "Expected file scoped var");
7590
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007591 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7592 return false;
7593
Richard Smitha0e5e542012-11-12 21:38:00 +00007594 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007595 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007596 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7597 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007598
Richard Smitha0e5e542012-11-12 21:38:00 +00007599 // Variables that have destruction with side-effects are required.
7600 if (VD->getType().isDestructedType())
7601 return true;
7602
7603 // Variables that have initialization with side-effects are required.
7604 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7605 return true;
7606
7607 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007608}
Charles Davis53c59df2010-08-16 03:33:14 +00007609
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007610CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007611 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007612 return ABI->getDefaultMethodCallConv(isVariadic);
7613}
7614
7615CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCall359b8852013-01-25 22:30:49 +00007616 if (CC == CC_C && !LangOpts.MRTD &&
7617 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007618 return CC_Default;
7619 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007620}
7621
Jay Foad39c79802011-01-12 09:06:06 +00007622bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007623 // Pass through to the C++ ABI object
7624 return ABI->isNearlyEmpty(RD);
7625}
7626
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007627MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007628 switch (Target->getCXXABI().getKind()) {
7629 case TargetCXXABI::GenericItanium:
7630 case TargetCXXABI::GenericARM:
7631 case TargetCXXABI::iOS:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007632 return createItaniumMangleContext(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007633 case TargetCXXABI::Microsoft:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007634 return createMicrosoftMangleContext(*this, getDiagnostics());
7635 }
David Blaikie83d382b2011-09-23 05:06:16 +00007636 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007637}
7638
Charles Davis53c59df2010-08-16 03:33:14 +00007639CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007640
7641size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007642 return ASTRecordLayouts.getMemorySize()
7643 + llvm::capacity_in_bytes(ObjCLayouts)
7644 + llvm::capacity_in_bytes(KeyFunctions)
7645 + llvm::capacity_in_bytes(ObjCImpls)
7646 + llvm::capacity_in_bytes(BlockVarCopyInits)
7647 + llvm::capacity_in_bytes(DeclAttrs)
7648 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7649 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7650 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7651 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7652 + llvm::capacity_in_bytes(OverriddenMethods)
7653 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007654 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007655 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007656}
Ted Kremenek540017e2011-10-06 05:00:56 +00007657
David Blaikie095deba2012-11-14 01:52:05 +00007658void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7659 // FIXME: This mangling should be applied to function local classes too
7660 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7661 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7662 return;
7663
7664 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7665 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7666 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7667}
7668
7669int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7670 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7671 UnnamedMangleNumbers.find(Tag);
7672 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7673}
7674
Douglas Gregor63798542012-02-20 19:44:39 +00007675unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7676 CXXRecordDecl *Lambda = CallOperator->getParent();
7677 return LambdaMangleContexts[Lambda->getDeclContext()]
7678 .getManglingNumber(CallOperator);
7679}
7680
7681
Ted Kremenek540017e2011-10-06 05:00:56 +00007682void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7683 ParamIndices[D] = index;
7684}
7685
7686unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7687 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7688 assert(I != ParamIndices.end() &&
7689 "ParmIndices lacks entry set by ParmVarDecl");
7690 return I->second;
7691}