blob: 7b61c25b1d3a2a299f6345543e7a932d7093aa6a [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"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000016#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000017#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000020#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000021#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000023#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000024#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000026#include "clang/AST/Mangle.h"
Fariborz Jahanian1c883b92012-10-10 18:34:52 +000027#include "clang/AST/Comment.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000028#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000029#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000030#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000031#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000032#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000033#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000034#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000035#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000036#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000037#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000038
Chris Lattnerddc135e2006-11-10 06:34:16 +000039using namespace clang;
40
Douglas Gregor9672f922010-07-03 00:47:00 +000041unsigned ASTContext::NumImplicitDefaultConstructors;
42unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000043unsigned ASTContext::NumImplicitCopyConstructors;
44unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000045unsigned ASTContext::NumImplicitMoveConstructors;
46unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000047unsigned ASTContext::NumImplicitCopyAssignmentOperators;
48unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000049unsigned ASTContext::NumImplicitMoveAssignmentOperators;
50unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000051unsigned ASTContext::NumImplicitDestructors;
52unsigned ASTContext::NumImplicitDestructorsDeclared;
53
Steve Naroff0af91202007-04-27 21:51:21 +000054enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000055 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000056};
57
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000058RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000059 if (!CommentsLoaded && ExternalSource) {
60 ExternalSource->ReadComments();
61 CommentsLoaded = true;
62 }
63
64 assert(D);
65
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000066 // User can not attach documentation to implicit declarations.
67 if (D->isImplicit())
68 return NULL;
69
Dmitri Gribenkob2610882012-08-14 17:17:18 +000070 // User can not attach documentation to implicit instantiations.
71 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
72 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
73 return NULL;
74 }
75
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000076 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
77 if (VD->isStaticDataMember() &&
78 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
79 return NULL;
80 }
81
82 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
83 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
84 return NULL;
85 }
86
87 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
88 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
89 return NULL;
90 }
91
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000092 // TODO: handle comments for function parameters properly.
93 if (isa<ParmVarDecl>(D))
94 return NULL;
95
Dmitri Gribenko34df2202012-07-31 22:37:06 +000096 // TODO: we could look up template parameter documentation in the template
97 // documentation.
98 if (isa<TemplateTypeParmDecl>(D) ||
99 isa<NonTypeTemplateParmDecl>(D) ||
100 isa<TemplateTemplateParmDecl>(D))
101 return NULL;
102
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000103 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000104
105 // If there are no comments anywhere, we won't find anything.
106 if (RawComments.empty())
107 return NULL;
108
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000109 // Find declaration location.
110 // For Objective-C declarations we generally don't expect to have multiple
111 // declarators, thus use declaration starting location as the "declaration
112 // location".
113 // For all other declarations multiple declarators are used quite frequently,
114 // so we use the location of the identifier as the "declaration location".
115 SourceLocation DeclLoc;
116 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000117 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000118 isa<RedeclarableTemplateDecl>(D) ||
119 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000120 DeclLoc = D->getLocStart();
121 else
122 DeclLoc = D->getLocation();
123
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000124 // If the declaration doesn't map directly to a location in a file, we
125 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000126 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
127 return NULL;
128
129 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000130 ArrayRef<RawComment *>::iterator Comment;
131 {
132 // When searching for comments during parsing, the comment we are looking
133 // for is usually among the last two comments we parsed -- check them
134 // first.
135 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
136 BeforeThanCompare<RawComment> Compare(SourceMgr);
137 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
138 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
139 if (!Found && RawComments.size() >= 2) {
140 MaybeBeforeDecl--;
141 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
142 }
143
144 if (Found) {
145 Comment = MaybeBeforeDecl + 1;
146 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
147 &CommentAtDeclLoc, Compare));
148 } else {
149 // Slow path.
150 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
151 &CommentAtDeclLoc, Compare);
152 }
153 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000154
155 // Decompose the location for the declaration and find the beginning of the
156 // file buffer.
157 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
158
159 // First check whether we have a trailing comment.
160 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000161 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000162 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000163 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000164 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000165 // Check that Doxygen trailing comment comes after the declaration, starts
166 // on the same line and in the same file as the declaration.
167 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
168 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
169 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
170 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000171 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000172 }
173 }
174
175 // The comment just after the declaration was not a trailing comment.
176 // Let's look at the previous comment.
177 if (Comment == RawComments.begin())
178 return NULL;
179 --Comment;
180
181 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000182 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000183 return NULL;
184
185 // Decompose the end of the comment.
186 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000187 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000188
189 // If the comment and the declaration aren't in the same file, then they
190 // aren't related.
191 if (DeclLocDecomp.first != CommentEndDecomp.first)
192 return NULL;
193
194 // Get the corresponding buffer.
195 bool Invalid = false;
196 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
197 &Invalid).data();
198 if (Invalid)
199 return NULL;
200
201 // Extract text between the comment and declaration.
202 StringRef Text(Buffer + CommentEndDecomp.second,
203 DeclLocDecomp.second - CommentEndDecomp.second);
204
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000205 // There should be no other declarations or preprocessor directives between
206 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000207 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000208 return NULL;
209
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000210 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000211}
212
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000213namespace {
214/// If we have a 'templated' declaration for a template, adjust 'D' to
215/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000216/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000217const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000218 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000219 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000220 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000221 return FTD;
222
223 // Nothing to do if function is not an implicit instantiation.
224 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
225 return D;
226
227 // Function is an implicit instantiation of a function template?
228 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
229 return FTD;
230
231 // Function is instantiated from a member definition of a class template?
232 if (const FunctionDecl *MemberDecl =
233 FD->getInstantiatedFromMemberFunction())
234 return MemberDecl;
235
236 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000237 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000238 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
239 // Static data member is instantiated from a member definition of a class
240 // template?
241 if (VD->isStaticDataMember())
242 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
243 return MemberDecl;
244
245 return D;
246 }
247 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
248 // Is this class declaration part of a class template?
249 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
250 return CTD;
251
252 // Class is an implicit instantiation of a class template or partial
253 // specialization?
254 if (const ClassTemplateSpecializationDecl *CTSD =
255 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
256 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
257 return D;
258 llvm::PointerUnion<ClassTemplateDecl *,
259 ClassTemplatePartialSpecializationDecl *>
260 PU = CTSD->getSpecializedTemplateOrPartial();
261 return PU.is<ClassTemplateDecl*>() ?
262 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
263 static_cast<const Decl*>(
264 PU.get<ClassTemplatePartialSpecializationDecl *>());
265 }
266
267 // Class is instantiated from a member definition of a class template?
268 if (const MemberSpecializationInfo *Info =
269 CRD->getMemberSpecializationInfo())
270 return Info->getInstantiatedFrom();
271
272 return D;
273 }
274 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
275 // Enum is instantiated from a member definition of a class template?
276 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
277 return MemberDecl;
278
279 return D;
280 }
281 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000282 return D;
283}
284} // unnamed namespace
285
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000286const RawComment *ASTContext::getRawCommentForAnyRedecl(
287 const Decl *D,
288 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000289 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000290
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000291 // Check whether we have cached a comment for this declaration already.
292 {
293 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
294 RedeclComments.find(D);
295 if (Pos != RedeclComments.end()) {
296 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000297 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
298 if (OriginalDecl)
299 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000300 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000301 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000302 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000303 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000304
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000305 // Search for comments attached to declarations in the redeclaration chain.
306 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000307 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000308 for (Decl::redecl_iterator I = D->redecls_begin(),
309 E = D->redecls_end();
310 I != E; ++I) {
311 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
312 RedeclComments.find(*I);
313 if (Pos != RedeclComments.end()) {
314 const RawCommentAndCacheFlags &Raw = Pos->second;
315 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
316 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000317 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000318 break;
319 }
320 } else {
321 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000322 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000323 RawCommentAndCacheFlags Raw;
324 if (RC) {
325 Raw.setRaw(RC);
326 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
327 } else
328 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000329 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000330 RedeclComments[*I] = Raw;
331 if (RC)
332 break;
333 }
334 }
335
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000336 // If we found a comment, it should be a documentation comment.
337 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000338
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000339 if (OriginalDecl)
340 *OriginalDecl = OriginalDeclForRC;
341
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000342 // Update cache for every declaration in the redeclaration chain.
343 RawCommentAndCacheFlags Raw;
344 Raw.setRaw(RC);
345 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000346 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000347
348 for (Decl::redecl_iterator I = D->redecls_begin(),
349 E = D->redecls_end();
350 I != E; ++I) {
351 RawCommentAndCacheFlags &R = RedeclComments[*I];
352 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
353 R = Raw;
354 }
355
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000356 return RC;
357}
358
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000359static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
360 SmallVectorImpl<const NamedDecl *> &Redeclared) {
361 const DeclContext *DC = ObjCMethod->getDeclContext();
362 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
363 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
364 if (!ID)
365 return;
366 // Add redeclared method here.
367 for (const ObjCCategoryDecl *ClsExtDecl = ID->getFirstClassExtension();
368 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
369 if (ObjCMethodDecl *RedeclaredMethod =
370 ClsExtDecl->getMethod(ObjCMethod->getSelector(),
371 ObjCMethod->isInstanceMethod()))
372 Redeclared.push_back(RedeclaredMethod);
373 }
374 }
375}
376
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000377comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
378 const Decl *D) const {
379 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
380 ThisDeclInfo->CommentDecl = D;
381 ThisDeclInfo->IsFilled = false;
382 ThisDeclInfo->fill();
383 ThisDeclInfo->CommentDecl = FC->getDecl();
384 comments::FullComment *CFC =
385 new (*this) comments::FullComment(FC->getBlocks(),
386 ThisDeclInfo);
387 return CFC;
388
389}
390
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000391comments::FullComment *ASTContext::getCommentForDecl(
392 const Decl *D,
393 const Preprocessor *PP) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000394 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000395
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000396 const Decl *Canonical = D->getCanonicalDecl();
397 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
398 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000399
400 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000401 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000402 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000403 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000404 return CFC;
405 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000406 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000407 }
408
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000409 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000410
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000411 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 if (!RC) {
413 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000414 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000415 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D))
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000416 addRedeclaredMethods(OMD, Overridden);
417 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
418 for (unsigned i = 0, e = Overridden.size(); i < e; i++) {
419 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000420 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000421 return CFC;
422 }
423 }
424 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000425 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000426 }
427
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000428 // If the RawComment was attached to other redeclaration of this Decl, we
429 // should parse the comment in context of that other Decl. This is important
430 // because comments can contain references to parameter names which can be
431 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000432 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000433 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000434
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000435 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000436 ParsedComments[Canonical] = FC;
437 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000438}
439
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000440void
441ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
442 TemplateTemplateParmDecl *Parm) {
443 ID.AddInteger(Parm->getDepth());
444 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000445 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000446
447 TemplateParameterList *Params = Parm->getTemplateParameters();
448 ID.AddInteger(Params->size());
449 for (TemplateParameterList::const_iterator P = Params->begin(),
450 PEnd = Params->end();
451 P != PEnd; ++P) {
452 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
453 ID.AddInteger(0);
454 ID.AddBoolean(TTP->isParameterPack());
455 continue;
456 }
457
458 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
459 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000460 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000461 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000462 if (NTTP->isExpandedParameterPack()) {
463 ID.AddBoolean(true);
464 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000465 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
466 QualType T = NTTP->getExpansionType(I);
467 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
468 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000469 } else
470 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000471 continue;
472 }
473
474 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
475 ID.AddInteger(2);
476 Profile(ID, TTP);
477 }
478}
479
480TemplateTemplateParmDecl *
481ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000482 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000483 // Check if we already have a canonical template template parameter.
484 llvm::FoldingSetNodeID ID;
485 CanonicalTemplateTemplateParm::Profile(ID, TTP);
486 void *InsertPos = 0;
487 CanonicalTemplateTemplateParm *Canonical
488 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
489 if (Canonical)
490 return Canonical->getParam();
491
492 // Build a canonical template parameter list.
493 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000494 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000495 CanonParams.reserve(Params->size());
496 for (TemplateParameterList::const_iterator P = Params->begin(),
497 PEnd = Params->end();
498 P != PEnd; ++P) {
499 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
500 CanonParams.push_back(
501 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000502 SourceLocation(),
503 SourceLocation(),
504 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000505 TTP->getIndex(), 0, false,
506 TTP->isParameterPack()));
507 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000508 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
509 QualType T = getCanonicalType(NTTP->getType());
510 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
511 NonTypeTemplateParmDecl *Param;
512 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000513 SmallVector<QualType, 2> ExpandedTypes;
514 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000515 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
516 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
517 ExpandedTInfos.push_back(
518 getTrivialTypeSourceInfo(ExpandedTypes.back()));
519 }
520
521 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000522 SourceLocation(),
523 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000524 NTTP->getDepth(),
525 NTTP->getPosition(), 0,
526 T,
527 TInfo,
528 ExpandedTypes.data(),
529 ExpandedTypes.size(),
530 ExpandedTInfos.data());
531 } else {
532 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000533 SourceLocation(),
534 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000535 NTTP->getDepth(),
536 NTTP->getPosition(), 0,
537 T,
538 NTTP->isParameterPack(),
539 TInfo);
540 }
541 CanonParams.push_back(Param);
542
543 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000544 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
545 cast<TemplateTemplateParmDecl>(*P)));
546 }
547
548 TemplateTemplateParmDecl *CanonTTP
549 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
550 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000551 TTP->getPosition(),
552 TTP->isParameterPack(),
553 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000554 TemplateParameterList::Create(*this, SourceLocation(),
555 SourceLocation(),
556 CanonParams.data(),
557 CanonParams.size(),
558 SourceLocation()));
559
560 // Get the new insert position for the node we care about.
561 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
562 assert(Canonical == 0 && "Shouldn't be in the map!");
563 (void)Canonical;
564
565 // Create the canonical template template parameter entry.
566 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
567 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
568 return CanonTTP;
569}
570
Charles Davis53c59df2010-08-16 03:33:14 +0000571CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000572 if (!LangOpts.CPlusPlus) return 0;
573
Charles Davis6bcb07a2010-08-19 02:18:14 +0000574 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000575 case CXXABI_ARM:
576 return CreateARMCXXABI(*this);
577 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000578 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000579 case CXXABI_Microsoft:
580 return CreateMicrosoftCXXABI(*this);
581 }
David Blaikie8a40f702012-01-17 06:56:22 +0000582 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000583}
584
Douglas Gregore8bbc122011-09-02 00:18:52 +0000585static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000586 const LangOptions &LOpts) {
587 if (LOpts.FakeAddressSpaceMap) {
588 // The fake address space map must have a distinct entry for each
589 // language-specific address space.
590 static const unsigned FakeAddrSpaceMap[] = {
591 1, // opencl_global
592 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000593 3, // opencl_constant
594 4, // cuda_device
595 5, // cuda_constant
596 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000597 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000598 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000599 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000600 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000601 }
602}
603
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000604ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000605 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000606 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000607 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000608 unsigned size_reserve,
609 bool DelayInitialization)
610 : FunctionProtoTypes(this_()),
611 TemplateSpecializationTypes(this_()),
612 DependentTemplateSpecializationTypes(this_()),
613 SubstTemplateTemplateParmPacks(this_()),
614 GlobalNestedNameSpecifier(0),
615 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000616 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000617 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000618 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000619 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000620 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000621 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
622 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
623 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000624 NullTypeSourceInfo(QualType()),
625 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000626 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000627 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000628 Idents(idents), Selectors(sels),
629 BuiltinInfo(builtins),
630 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000631 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000632 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000633 CommentCommandTraits(BumpAlloc),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000634 LastSDM(0, 0),
635 UniqueBlockByRefTypeID(0)
636{
Mike Stump11289f42009-09-09 15:08:12 +0000637 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000638 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000639
640 if (!DelayInitialization) {
641 assert(t && "No target supplied for ASTContext initialization");
642 InitBuiltinTypes(*t);
643 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000644}
645
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000646ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000647 // Release the DenseMaps associated with DeclContext objects.
648 // FIXME: Is this the ideal solution?
649 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000650
Douglas Gregor5b11d492010-07-25 17:53:33 +0000651 // Call all of the deallocation functions.
652 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
653 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000654
Ted Kremenek076baeb2010-06-08 23:00:58 +0000655 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000656 // because they can contain DenseMaps.
657 for (llvm::DenseMap<const ObjCContainerDecl*,
658 const ASTRecordLayout*>::iterator
659 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
660 // Increment in loop to prevent using deallocated memory.
661 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
662 R->Destroy(*this);
663
Ted Kremenek076baeb2010-06-08 23:00:58 +0000664 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
665 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
666 // Increment in loop to prevent using deallocated memory.
667 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
668 R->Destroy(*this);
669 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000670
671 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
672 AEnd = DeclAttrs.end();
673 A != AEnd; ++A)
674 A->second->~AttrVec();
675}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000676
Douglas Gregor1a809332010-05-23 18:26:36 +0000677void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
678 Deallocations.push_back(std::make_pair(Callback, Data));
679}
680
Mike Stump11289f42009-09-09 15:08:12 +0000681void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000682ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000683 ExternalSource.reset(Source.take());
684}
685
Chris Lattner4eb445d2007-01-26 01:27:23 +0000686void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000687 llvm::errs() << "\n*** AST Context Stats:\n";
688 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000689
Douglas Gregora30d0462009-05-26 14:40:08 +0000690 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000691#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000692#define ABSTRACT_TYPE(Name, Parent)
693#include "clang/AST/TypeNodes.def"
694 0 // Extra
695 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000696
Chris Lattner4eb445d2007-01-26 01:27:23 +0000697 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
698 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000699 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000700 }
701
Douglas Gregora30d0462009-05-26 14:40:08 +0000702 unsigned Idx = 0;
703 unsigned TotalBytes = 0;
704#define TYPE(Name, Parent) \
705 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000706 llvm::errs() << " " << counts[Idx] << " " << #Name \
707 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000708 TotalBytes += counts[Idx] * sizeof(Name##Type); \
709 ++Idx;
710#define ABSTRACT_TYPE(Name, Parent)
711#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000712
Chandler Carruth3c147a72011-07-04 05:32:14 +0000713 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
714
Douglas Gregor7454c562010-07-02 20:37:36 +0000715 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000716 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
717 << NumImplicitDefaultConstructors
718 << " implicit default constructors created\n";
719 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
720 << NumImplicitCopyConstructors
721 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000722 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000723 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
724 << NumImplicitMoveConstructors
725 << " implicit move constructors created\n";
726 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
727 << NumImplicitCopyAssignmentOperators
728 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000729 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000730 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
731 << NumImplicitMoveAssignmentOperators
732 << " implicit move assignment operators created\n";
733 llvm::errs() << NumImplicitDestructorsDeclared << "/"
734 << NumImplicitDestructors
735 << " implicit destructors created\n";
736
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000737 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000738 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000739 ExternalSource->PrintStats();
740 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000741
Douglas Gregor5b11d492010-07-25 17:53:33 +0000742 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000743}
744
Douglas Gregor801c99d2011-08-12 06:49:56 +0000745TypedefDecl *ASTContext::getInt128Decl() const {
746 if (!Int128Decl) {
747 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
748 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
749 getTranslationUnitDecl(),
750 SourceLocation(),
751 SourceLocation(),
752 &Idents.get("__int128_t"),
753 TInfo);
754 }
755
756 return Int128Decl;
757}
758
759TypedefDecl *ASTContext::getUInt128Decl() const {
760 if (!UInt128Decl) {
761 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
762 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
763 getTranslationUnitDecl(),
764 SourceLocation(),
765 SourceLocation(),
766 &Idents.get("__uint128_t"),
767 TInfo);
768 }
769
770 return UInt128Decl;
771}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000772
John McCall48f2d582009-10-23 23:03:21 +0000773void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000774 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000775 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000776 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000777}
778
Douglas Gregore8bbc122011-09-02 00:18:52 +0000779void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
780 assert((!this->Target || this->Target == &Target) &&
781 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000782 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000783
Douglas Gregore8bbc122011-09-02 00:18:52 +0000784 this->Target = &Target;
785
786 ABI.reset(createCXXABI(Target));
787 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
788
Chris Lattner970e54e2006-11-12 00:37:36 +0000789 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000790 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000791
Chris Lattner970e54e2006-11-12 00:37:36 +0000792 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000793 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000794 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000795 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000796 InitBuiltinType(CharTy, BuiltinType::Char_S);
797 else
798 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000799 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000800 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
801 InitBuiltinType(ShortTy, BuiltinType::Short);
802 InitBuiltinType(IntTy, BuiltinType::Int);
803 InitBuiltinType(LongTy, BuiltinType::Long);
804 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000805
Chris Lattner970e54e2006-11-12 00:37:36 +0000806 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000807 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
808 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
809 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
810 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
811 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000812
Chris Lattner970e54e2006-11-12 00:37:36 +0000813 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000814 InitBuiltinType(FloatTy, BuiltinType::Float);
815 InitBuiltinType(DoubleTy, BuiltinType::Double);
816 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000817
Chris Lattnerf122cef2009-04-30 02:43:43 +0000818 // GNU extension, 128-bit integers.
819 InitBuiltinType(Int128Ty, BuiltinType::Int128);
820 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
821
Abramo Bagnara06782942012-09-09 10:13:32 +0000822 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000823 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000824 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
825 else // -fshort-wchar makes wchar_t be unsigned.
826 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnara06782942012-09-09 10:13:32 +0000827 } else // C99 (or C++ using -fno-wchar)
Chris Lattner007cb022009-02-26 23:43:47 +0000828 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000829
James Molloy36365542012-05-04 10:55:22 +0000830 WIntTy = getFromTargetType(Target.getWIntType());
831
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000832 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
833 InitBuiltinType(Char16Ty, BuiltinType::Char16);
834 else // C99
835 Char16Ty = getFromTargetType(Target.getChar16Type());
836
837 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
838 InitBuiltinType(Char32Ty, BuiltinType::Char32);
839 else // C99
840 Char32Ty = getFromTargetType(Target.getChar32Type());
841
Douglas Gregor4619e432008-12-05 23:32:09 +0000842 // Placeholder type for type-dependent expressions whose type is
843 // completely unknown. No code should ever check a type against
844 // DependentTy and users should never see it; however, it is here to
845 // help diagnose failures to properly check for type-dependent
846 // expressions.
847 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000848
John McCall36e7fe32010-10-12 00:20:44 +0000849 // Placeholder type for functions.
850 InitBuiltinType(OverloadTy, BuiltinType::Overload);
851
John McCall0009fcc2011-04-26 20:42:42 +0000852 // Placeholder type for bound members.
853 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
854
John McCall526ab472011-10-25 17:37:35 +0000855 // Placeholder type for pseudo-objects.
856 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
857
John McCall31996342011-04-07 08:22:57 +0000858 // "any" type; useful for debugger-like clients.
859 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
860
John McCall8a6b59a2011-10-17 18:09:15 +0000861 // Placeholder type for unbridged ARC casts.
862 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
863
Eli Friedman34866c72012-08-31 00:14:07 +0000864 // Placeholder type for builtin functions.
865 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
866
Chris Lattner970e54e2006-11-12 00:37:36 +0000867 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000868 FloatComplexTy = getComplexType(FloatTy);
869 DoubleComplexTy = getComplexType(DoubleTy);
870 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000871
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000872 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000873 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
874 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000875 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000876
877 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000878 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
879 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000880
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000881 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000882
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000883 // void * type
884 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000885
886 // nullptr type (C++0x 2.14.7)
887 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000888
889 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
890 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000891
892 // Builtin type used to help define __builtin_va_list.
893 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000894}
895
David Blaikie9c902b52011-09-25 23:23:43 +0000896DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000897 return SourceMgr.getDiagnostics();
898}
899
Douglas Gregor561eceb2010-08-30 16:49:28 +0000900AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
901 AttrVec *&Result = DeclAttrs[D];
902 if (!Result) {
903 void *Mem = Allocate(sizeof(AttrVec));
904 Result = new (Mem) AttrVec;
905 }
906
907 return *Result;
908}
909
910/// \brief Erase the attributes corresponding to the given declaration.
911void ASTContext::eraseDeclAttrs(const Decl *D) {
912 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
913 if (Pos != DeclAttrs.end()) {
914 Pos->second->~AttrVec();
915 DeclAttrs.erase(Pos);
916 }
917}
918
Douglas Gregor86d142a2009-10-08 07:24:58 +0000919MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000920ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000921 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000922 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000923 = InstantiatedFromStaticDataMember.find(Var);
924 if (Pos == InstantiatedFromStaticDataMember.end())
925 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000926
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000927 return Pos->second;
928}
929
Mike Stump11289f42009-09-09 15:08:12 +0000930void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000931ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000932 TemplateSpecializationKind TSK,
933 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000934 assert(Inst->isStaticDataMember() && "Not a static data member");
935 assert(Tmpl->isStaticDataMember() && "Not a static data member");
936 assert(!InstantiatedFromStaticDataMember[Inst] &&
937 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000938 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000939 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000940}
941
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000942FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
943 const FunctionDecl *FD){
944 assert(FD && "Specialization is 0");
945 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000946 = ClassScopeSpecializationPattern.find(FD);
947 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000948 return 0;
949
950 return Pos->second;
951}
952
953void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
954 FunctionDecl *Pattern) {
955 assert(FD && "Specialization is 0");
956 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000957 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000958}
959
John McCalle61f2ba2009-11-18 02:36:19 +0000960NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000961ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000962 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000963 = InstantiatedFromUsingDecl.find(UUD);
964 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000965 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000966
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000967 return Pos->second;
968}
969
970void
John McCallb96ec562009-12-04 22:46:56 +0000971ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
972 assert((isa<UsingDecl>(Pattern) ||
973 isa<UnresolvedUsingValueDecl>(Pattern) ||
974 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
975 "pattern decl is not a using decl");
976 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
977 InstantiatedFromUsingDecl[Inst] = Pattern;
978}
979
980UsingShadowDecl *
981ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
982 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
983 = InstantiatedFromUsingShadowDecl.find(Inst);
984 if (Pos == InstantiatedFromUsingShadowDecl.end())
985 return 0;
986
987 return Pos->second;
988}
989
990void
991ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
992 UsingShadowDecl *Pattern) {
993 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
994 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000995}
996
Anders Carlsson5da84842009-09-01 04:26:58 +0000997FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
998 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
999 = InstantiatedFromUnnamedFieldDecl.find(Field);
1000 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1001 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001002
Anders Carlsson5da84842009-09-01 04:26:58 +00001003 return Pos->second;
1004}
1005
1006void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1007 FieldDecl *Tmpl) {
1008 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1009 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1010 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1011 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001012
Anders Carlsson5da84842009-09-01 04:26:58 +00001013 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1014}
1015
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001016bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1017 const FieldDecl *LastFD) const {
1018 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001019 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001020}
1021
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001022bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1023 const FieldDecl *LastFD) const {
1024 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001025 FD->getBitWidthValue(*this) == 0 &&
1026 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001027}
1028
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001029bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1030 const FieldDecl *LastFD) const {
1031 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001032 FD->getBitWidthValue(*this) &&
1033 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001034}
1035
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001036bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001037 const FieldDecl *LastFD) const {
1038 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001039 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001040}
1041
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001042bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001043 const FieldDecl *LastFD) const {
1044 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001045 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001046}
1047
Douglas Gregor832940b2010-03-02 23:58:15 +00001048ASTContext::overridden_cxx_method_iterator
1049ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1050 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001051 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001052 if (Pos == OverriddenMethods.end())
1053 return 0;
1054
1055 return Pos->second.begin();
1056}
1057
1058ASTContext::overridden_cxx_method_iterator
1059ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1060 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001061 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001062 if (Pos == OverriddenMethods.end())
1063 return 0;
1064
1065 return Pos->second.end();
1066}
1067
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001068unsigned
1069ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1070 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001071 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001072 if (Pos == OverriddenMethods.end())
1073 return 0;
1074
1075 return Pos->second.size();
1076}
1077
Douglas Gregor832940b2010-03-02 23:58:15 +00001078void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1079 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001080 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001081 OverriddenMethods[Method].push_back(Overridden);
1082}
1083
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001084void ASTContext::getOverriddenMethods(
1085 const NamedDecl *D,
1086 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001087 assert(D);
1088
1089 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001090 Overridden.append(CXXMethod->begin_overridden_methods(),
1091 CXXMethod->end_overridden_methods());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001092 return;
1093 }
1094
1095 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1096 if (!Method)
1097 return;
1098
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001099 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1100 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001101 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001102}
1103
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001104void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1105 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1106 assert(!Import->isFromASTFile() && "Non-local import declaration");
1107 if (!FirstLocalImport) {
1108 FirstLocalImport = Import;
1109 LastLocalImport = Import;
1110 return;
1111 }
1112
1113 LastLocalImport->NextLocalImport = Import;
1114 LastLocalImport = Import;
1115}
1116
Chris Lattner53cfe802007-07-18 17:52:12 +00001117//===----------------------------------------------------------------------===//
1118// Type Sizing and Analysis
1119//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001120
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001121/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1122/// scalar floating point type.
1123const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001124 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001125 assert(BT && "Not a floating point type!");
1126 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001127 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001128 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001129 case BuiltinType::Float: return Target->getFloatFormat();
1130 case BuiltinType::Double: return Target->getDoubleFormat();
1131 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001132 }
1133}
1134
Ken Dyck160146e2010-01-27 17:10:57 +00001135/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001136/// specified decl. Note that bitfields do not have a valid alignment, so
1137/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001138/// If @p RefAsPointee, references are treated like their underlying type
1139/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001140CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001141 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001142
John McCall94268702010-10-08 18:24:19 +00001143 bool UseAlignAttrOnly = false;
1144 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1145 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001146
John McCall94268702010-10-08 18:24:19 +00001147 // __attribute__((aligned)) can increase or decrease alignment
1148 // *except* on a struct or struct member, where it only increases
1149 // alignment unless 'packed' is also specified.
1150 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001151 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001152 // ignore that possibility; Sema should diagnose it.
1153 if (isa<FieldDecl>(D)) {
1154 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1155 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1156 } else {
1157 UseAlignAttrOnly = true;
1158 }
1159 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001160 else if (isa<FieldDecl>(D))
1161 UseAlignAttrOnly =
1162 D->hasAttr<PackedAttr>() ||
1163 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001164
John McCall4e819612011-01-20 07:57:12 +00001165 // If we're using the align attribute only, just ignore everything
1166 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001167 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001168 // do nothing
1169
John McCall94268702010-10-08 18:24:19 +00001170 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001171 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001172 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001173 if (RefAsPointee)
1174 T = RT->getPointeeType();
1175 else
1176 T = getPointerType(RT->getPointeeType());
1177 }
1178 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001179 // Adjust alignments of declarations with array type by the
1180 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001181 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001182 const ArrayType *arrayType;
1183 if (MinWidth && (arrayType = getAsArrayType(T))) {
1184 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001185 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001186 else if (isa<ConstantArrayType>(arrayType) &&
1187 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001188 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001189
John McCall33ddac02011-01-19 10:06:00 +00001190 // Walk through any array types while we're at it.
1191 T = getBaseElementType(arrayType);
1192 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001193 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001194 }
John McCall4e819612011-01-20 07:57:12 +00001195
1196 // Fields can be subject to extra alignment constraints, like if
1197 // the field is packed, the struct is packed, or the struct has a
1198 // a max-field-alignment constraint (#pragma pack). So calculate
1199 // the actual alignment of the field within the struct, and then
1200 // (as we're expected to) constrain that by the alignment of the type.
1201 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1202 // So calculate the alignment of the field.
1203 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1204
1205 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001206 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001207
1208 // Use the GCD of that and the offset within the record.
1209 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1210 if (offset > 0) {
1211 // Alignment is always a power of 2, so the GCD will be a power of 2,
1212 // which means we get to do this crazy thing instead of Euclid's.
1213 uint64_t lowBitOfOffset = offset & (~offset + 1);
1214 if (lowBitOfOffset < fieldAlign)
1215 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1216 }
1217
1218 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001219 }
Chris Lattner68061312009-01-24 21:53:27 +00001220 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001221
Ken Dyckcc56c542011-01-15 18:38:59 +00001222 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001223}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001224
John McCallf1249922012-08-21 04:10:00 +00001225// getTypeInfoDataSizeInChars - Return the size of a type, in
1226// chars. If the type is a record, its data size is returned. This is
1227// the size of the memcpy that's performed when assigning this type
1228// using a trivial copy/move assignment operator.
1229std::pair<CharUnits, CharUnits>
1230ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1231 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1232
1233 // In C++, objects can sometimes be allocated into the tail padding
1234 // of a base-class subobject. We decide whether that's possible
1235 // during class layout, so here we can just trust the layout results.
1236 if (getLangOpts().CPlusPlus) {
1237 if (const RecordType *RT = T->getAs<RecordType>()) {
1238 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1239 sizeAndAlign.first = layout.getDataSize();
1240 }
1241 }
1242
1243 return sizeAndAlign;
1244}
1245
John McCall87fe5d52010-05-20 01:18:31 +00001246std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001247ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001248 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001249 return std::make_pair(toCharUnitsFromBits(Info.first),
1250 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001251}
1252
1253std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001254ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001255 return getTypeInfoInChars(T.getTypePtr());
1256}
1257
Daniel Dunbarc6475872012-03-09 04:12:54 +00001258std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1259 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1260 if (it != MemoizedTypeInfo.end())
1261 return it->second;
1262
1263 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1264 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1265 return Info;
1266}
1267
1268/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1269/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001270///
1271/// FIXME: Pointers into different addr spaces could have different sizes and
1272/// alignment requirements: getPointerInfo should take an AddrSpace, this
1273/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001274std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001275ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001276 uint64_t Width=0;
1277 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001278 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001279#define TYPE(Class, Base)
1280#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001281#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001282#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1283#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001284 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001285
Chris Lattner355332d2007-07-13 22:27:08 +00001286 case Type::FunctionNoProto:
1287 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001288 // GCC extension: alignof(function) = 32 bits
1289 Width = 0;
1290 Align = 32;
1291 break;
1292
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001293 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001294 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001295 Width = 0;
1296 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1297 break;
1298
Steve Naroff5c131802007-08-30 01:06:46 +00001299 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001300 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001301
Chris Lattner37e05872008-03-05 18:54:05 +00001302 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001303 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001304 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1305 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001306 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001307 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001308 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001309 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001310 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001311 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001312 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001313 const VectorType *VT = cast<VectorType>(T);
1314 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1315 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001316 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001317 // If the alignment is not a power of 2, round up to the next power of 2.
1318 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001319 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001320 Align = llvm::NextPowerOf2(Align);
1321 Width = llvm::RoundUpToAlignment(Width, Align);
1322 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001323 // Adjust the alignment based on the target max.
1324 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1325 if (TargetVectorAlign && TargetVectorAlign < Align)
1326 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001327 break;
1328 }
Chris Lattner647fb222007-07-18 18:26:58 +00001329
Chris Lattner7570e9c2008-03-08 08:52:55 +00001330 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001331 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001332 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001333 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001334 // GCC extension: alignof(void) = 8 bits.
1335 Width = 0;
1336 Align = 8;
1337 break;
1338
Chris Lattner6a4f7452007-12-19 19:23:28 +00001339 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001340 Width = Target->getBoolWidth();
1341 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001342 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001343 case BuiltinType::Char_S:
1344 case BuiltinType::Char_U:
1345 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001346 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001347 Width = Target->getCharWidth();
1348 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001349 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001350 case BuiltinType::WChar_S:
1351 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001352 Width = Target->getWCharWidth();
1353 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001354 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001355 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001356 Width = Target->getChar16Width();
1357 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001358 break;
1359 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001360 Width = Target->getChar32Width();
1361 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001362 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001363 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001364 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001365 Width = Target->getShortWidth();
1366 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001367 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001368 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001369 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001370 Width = Target->getIntWidth();
1371 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001372 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001373 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001374 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001375 Width = Target->getLongWidth();
1376 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001377 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001378 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001379 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001380 Width = Target->getLongLongWidth();
1381 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001382 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001383 case BuiltinType::Int128:
1384 case BuiltinType::UInt128:
1385 Width = 128;
1386 Align = 128; // int128_t is 128-bit aligned on all targets.
1387 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001388 case BuiltinType::Half:
1389 Width = Target->getHalfWidth();
1390 Align = Target->getHalfAlign();
1391 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001392 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001393 Width = Target->getFloatWidth();
1394 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001395 break;
1396 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001397 Width = Target->getDoubleWidth();
1398 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001399 break;
1400 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001401 Width = Target->getLongDoubleWidth();
1402 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001403 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001404 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001405 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1406 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001407 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001408 case BuiltinType::ObjCId:
1409 case BuiltinType::ObjCClass:
1410 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001411 Width = Target->getPointerWidth(0);
1412 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001413 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001414 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001415 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001416 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001417 Width = Target->getPointerWidth(0);
1418 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001419 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001420 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001421 unsigned AS = getTargetAddressSpace(
1422 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001423 Width = Target->getPointerWidth(AS);
1424 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001425 break;
1426 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001427 case Type::LValueReference:
1428 case Type::RValueReference: {
1429 // alignof and sizeof should never enter this code path here, so we go
1430 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001431 unsigned AS = getTargetAddressSpace(
1432 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001433 Width = Target->getPointerWidth(AS);
1434 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001435 break;
1436 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001437 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001438 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001439 Width = Target->getPointerWidth(AS);
1440 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001441 break;
1442 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001443 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001444 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001445 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001446 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001447 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001448 Align = PtrDiffInfo.second;
1449 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001450 }
Chris Lattner647fb222007-07-18 18:26:58 +00001451 case Type::Complex: {
1452 // Complex types have the same alignment as their elements, but twice the
1453 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001454 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001455 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001456 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001457 Align = EltInfo.second;
1458 break;
1459 }
John McCall8b07ec22010-05-15 11:32:37 +00001460 case Type::ObjCObject:
1461 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001462 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001463 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001464 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001465 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001466 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001467 break;
1468 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001469 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001470 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001471 const TagType *TT = cast<TagType>(T);
1472
1473 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001474 Width = 8;
1475 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001476 break;
1477 }
Mike Stump11289f42009-09-09 15:08:12 +00001478
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001479 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001480 return getTypeInfo(ET->getDecl()->getIntegerType());
1481
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001482 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001483 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001484 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001485 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001486 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001487 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001488
Chris Lattner63d2b362009-10-22 05:17:15 +00001489 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001490 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1491 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001492
Richard Smith30482bc2011-02-20 03:19:35 +00001493 case Type::Auto: {
1494 const AutoType *A = cast<AutoType>(T);
1495 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001496 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001497 }
1498
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001499 case Type::Paren:
1500 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1501
Douglas Gregoref462e62009-04-30 17:32:17 +00001502 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001503 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001504 std::pair<uint64_t, unsigned> Info
1505 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001506 // If the typedef has an aligned attribute on it, it overrides any computed
1507 // alignment we have. This violates the GCC documentation (which says that
1508 // attribute(aligned) can only round up) but matches its implementation.
1509 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1510 Align = AttrAlign;
1511 else
1512 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001513 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001514 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001515 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001516
1517 case Type::TypeOfExpr:
1518 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1519 .getTypePtr());
1520
1521 case Type::TypeOf:
1522 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1523
Anders Carlsson81df7b82009-06-24 19:06:50 +00001524 case Type::Decltype:
1525 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1526 .getTypePtr());
1527
Alexis Hunte852b102011-05-24 22:41:36 +00001528 case Type::UnaryTransform:
1529 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1530
Abramo Bagnara6150c882010-05-11 21:36:43 +00001531 case Type::Elaborated:
1532 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001533
John McCall81904512011-01-06 01:58:22 +00001534 case Type::Attributed:
1535 return getTypeInfo(
1536 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1537
Richard Smith3f1b5d02011-05-05 21:57:07 +00001538 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001539 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001540 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001541 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1542 // A type alias template specialization may refer to a typedef with the
1543 // aligned attribute on it.
1544 if (TST->isTypeAlias())
1545 return getTypeInfo(TST->getAliasedType().getTypePtr());
1546 else
1547 return getTypeInfo(getCanonicalType(T));
1548 }
1549
Eli Friedman0dfb8892011-10-06 23:00:33 +00001550 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001551 std::pair<uint64_t, unsigned> Info
1552 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1553 Width = Info.first;
1554 Align = Info.second;
1555 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1556 llvm::isPowerOf2_64(Width)) {
1557 // We can potentially perform lock-free atomic operations for this
1558 // type; promote the alignment appropriately.
1559 // FIXME: We could potentially promote the width here as well...
1560 // is that worthwhile? (Non-struct atomic types generally have
1561 // power-of-two size anyway, but structs might not. Requires a bit
1562 // of implementation work to make sure we zero out the extra bits.)
1563 Align = static_cast<unsigned>(Width);
1564 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001565 }
1566
Douglas Gregoref462e62009-04-30 17:32:17 +00001567 }
Mike Stump11289f42009-09-09 15:08:12 +00001568
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001569 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001570 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001571}
1572
Ken Dyckcc56c542011-01-15 18:38:59 +00001573/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1574CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1575 return CharUnits::fromQuantity(BitSize / getCharWidth());
1576}
1577
Ken Dyckb0fcc592011-02-11 01:54:29 +00001578/// toBits - Convert a size in characters to a size in characters.
1579int64_t ASTContext::toBits(CharUnits CharSize) const {
1580 return CharSize.getQuantity() * getCharWidth();
1581}
1582
Ken Dyck8c89d592009-12-22 14:23:30 +00001583/// getTypeSizeInChars - Return the size of the specified type, in characters.
1584/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001585CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001586 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001587}
Jay Foad39c79802011-01-12 09:06:06 +00001588CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001589 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001590}
1591
Ken Dycka6046ab2010-01-26 17:25:18 +00001592/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001593/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001594CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001595 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001596}
Jay Foad39c79802011-01-12 09:06:06 +00001597CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001598 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001599}
1600
Chris Lattnera3402cd2009-01-27 18:08:34 +00001601/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1602/// type for the current target in bits. This can be different than the ABI
1603/// alignment in cases where it is beneficial for performance to overalign
1604/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001605unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001606 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001607
1608 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001609 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001610 T = CT->getElementType().getTypePtr();
1611 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001612 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1613 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001614 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1615
Chris Lattnera3402cd2009-01-27 18:08:34 +00001616 return ABIAlign;
1617}
1618
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001619/// DeepCollectObjCIvars -
1620/// This routine first collects all declared, but not synthesized, ivars in
1621/// super class and then collects all ivars, including those synthesized for
1622/// current class. This routine is used for implementation of current class
1623/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001624///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001625void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1626 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001627 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001628 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1629 DeepCollectObjCIvars(SuperClass, false, Ivars);
1630 if (!leafClass) {
1631 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1632 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001633 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001634 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001635 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001636 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001637 Iv= Iv->getNextIvar())
1638 Ivars.push_back(Iv);
1639 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001640}
1641
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001642/// CollectInheritedProtocols - Collect all protocols in current class and
1643/// those inherited by it.
1644void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001645 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001646 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001647 // We can use protocol_iterator here instead of
1648 // all_referenced_protocol_iterator since we are walking all categories.
1649 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1650 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001651 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001652 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001653 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001654 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001655 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001656 CollectInheritedProtocols(*P, Protocols);
1657 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001658 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001659
1660 // Categories of this Interface.
1661 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1662 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1663 CollectInheritedProtocols(CDeclChain, Protocols);
1664 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1665 while (SD) {
1666 CollectInheritedProtocols(SD, Protocols);
1667 SD = SD->getSuperClass();
1668 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001669 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001670 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001671 PE = OC->protocol_end(); P != PE; ++P) {
1672 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001673 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001674 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1675 PE = Proto->protocol_end(); P != PE; ++P)
1676 CollectInheritedProtocols(*P, Protocols);
1677 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001678 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001679 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1680 PE = OP->protocol_end(); P != PE; ++P) {
1681 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001682 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001683 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1684 PE = Proto->protocol_end(); P != PE; ++P)
1685 CollectInheritedProtocols(*P, Protocols);
1686 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001687 }
1688}
1689
Jay Foad39c79802011-01-12 09:06:06 +00001690unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001691 unsigned count = 0;
1692 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001693 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1694 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001695 count += CDecl->ivar_size();
1696
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001697 // Count ivar defined in this class's implementation. This
1698 // includes synthesized ivars.
1699 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001700 count += ImplDecl->ivar_size();
1701
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001702 return count;
1703}
1704
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001705bool ASTContext::isSentinelNullExpr(const Expr *E) {
1706 if (!E)
1707 return false;
1708
1709 // nullptr_t is always treated as null.
1710 if (E->getType()->isNullPtrType()) return true;
1711
1712 if (E->getType()->isAnyPointerType() &&
1713 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1714 Expr::NPC_ValueDependentIsNull))
1715 return true;
1716
1717 // Unfortunately, __null has type 'int'.
1718 if (isa<GNUNullExpr>(E)) return true;
1719
1720 return false;
1721}
1722
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001723/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1724ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1725 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1726 I = ObjCImpls.find(D);
1727 if (I != ObjCImpls.end())
1728 return cast<ObjCImplementationDecl>(I->second);
1729 return 0;
1730}
1731/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1732ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1733 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1734 I = ObjCImpls.find(D);
1735 if (I != ObjCImpls.end())
1736 return cast<ObjCCategoryImplDecl>(I->second);
1737 return 0;
1738}
1739
1740/// \brief Set the implementation of ObjCInterfaceDecl.
1741void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1742 ObjCImplementationDecl *ImplD) {
1743 assert(IFaceD && ImplD && "Passed null params");
1744 ObjCImpls[IFaceD] = ImplD;
1745}
1746/// \brief Set the implementation of ObjCCategoryDecl.
1747void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1748 ObjCCategoryImplDecl *ImplD) {
1749 assert(CatD && ImplD && "Passed null params");
1750 ObjCImpls[CatD] = ImplD;
1751}
1752
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001753ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1754 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1755 return ID;
1756 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1757 return CD->getClassInterface();
1758 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1759 return IMD->getClassInterface();
1760
1761 return 0;
1762}
1763
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001764/// \brief Get the copy initialization expression of VarDecl,or NULL if
1765/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001766Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001767 assert(VD && "Passed null params");
1768 assert(VD->hasAttr<BlocksAttr>() &&
1769 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001770 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001771 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001772 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1773}
1774
1775/// \brief Set the copy inialization expression of a block var decl.
1776void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1777 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001778 assert(VD->hasAttr<BlocksAttr>() &&
1779 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001780 BlockVarCopyInits[VD] = Init;
1781}
1782
John McCallbcd03502009-12-07 02:54:59 +00001783TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001784 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001785 if (!DataSize)
1786 DataSize = TypeLoc::getFullDataSizeForType(T);
1787 else
1788 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001789 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001790
John McCallbcd03502009-12-07 02:54:59 +00001791 TypeSourceInfo *TInfo =
1792 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1793 new (TInfo) TypeSourceInfo(T);
1794 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001795}
1796
John McCallbcd03502009-12-07 02:54:59 +00001797TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001798 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001799 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001800 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001801 return DI;
1802}
1803
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001804const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001805ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001806 return getObjCLayout(D, 0);
1807}
1808
1809const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001810ASTContext::getASTObjCImplementationLayout(
1811 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001812 return getObjCLayout(D->getClassInterface(), D);
1813}
1814
Chris Lattner983a8bb2007-07-13 22:13:22 +00001815//===----------------------------------------------------------------------===//
1816// Type creation/memoization methods
1817//===----------------------------------------------------------------------===//
1818
Jay Foad39c79802011-01-12 09:06:06 +00001819QualType
John McCall33ddac02011-01-19 10:06:00 +00001820ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1821 unsigned fastQuals = quals.getFastQualifiers();
1822 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001823
1824 // Check if we've already instantiated this type.
1825 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001826 ExtQuals::Profile(ID, baseType, quals);
1827 void *insertPos = 0;
1828 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1829 assert(eq->getQualifiers() == quals);
1830 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001831 }
1832
John McCall33ddac02011-01-19 10:06:00 +00001833 // If the base type is not canonical, make the appropriate canonical type.
1834 QualType canon;
1835 if (!baseType->isCanonicalUnqualified()) {
1836 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001837 canonSplit.Quals.addConsistentQualifiers(quals);
1838 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001839
1840 // Re-find the insert position.
1841 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1842 }
1843
1844 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1845 ExtQualNodes.InsertNode(eq, insertPos);
1846 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001847}
1848
Jay Foad39c79802011-01-12 09:06:06 +00001849QualType
1850ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001851 QualType CanT = getCanonicalType(T);
1852 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001853 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001854
John McCall8ccfcb52009-09-24 19:53:00 +00001855 // If we are composing extended qualifiers together, merge together
1856 // into one ExtQuals node.
1857 QualifierCollector Quals;
1858 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001859
John McCall8ccfcb52009-09-24 19:53:00 +00001860 // If this type already has an address space specified, it cannot get
1861 // another one.
1862 assert(!Quals.hasAddressSpace() &&
1863 "Type cannot be in multiple addr spaces!");
1864 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001865
John McCall8ccfcb52009-09-24 19:53:00 +00001866 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001867}
1868
Chris Lattnerd60183d2009-02-18 22:53:11 +00001869QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001870 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001871 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001872 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001873 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001874
John McCall53fa7142010-12-24 02:08:15 +00001875 if (const PointerType *ptr = T->getAs<PointerType>()) {
1876 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001877 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001878 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1879 return getPointerType(ResultType);
1880 }
1881 }
Mike Stump11289f42009-09-09 15:08:12 +00001882
John McCall8ccfcb52009-09-24 19:53:00 +00001883 // If we are composing extended qualifiers together, merge together
1884 // into one ExtQuals node.
1885 QualifierCollector Quals;
1886 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001887
John McCall8ccfcb52009-09-24 19:53:00 +00001888 // If this type already has an ObjCGC specified, it cannot get
1889 // another one.
1890 assert(!Quals.hasObjCGCAttr() &&
1891 "Type cannot have multiple ObjCGCs!");
1892 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001893
John McCall8ccfcb52009-09-24 19:53:00 +00001894 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001895}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001896
John McCall4f5019e2010-12-19 02:44:49 +00001897const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1898 FunctionType::ExtInfo Info) {
1899 if (T->getExtInfo() == Info)
1900 return T;
1901
1902 QualType Result;
1903 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1904 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1905 } else {
1906 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1907 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1908 EPI.ExtInfo = Info;
1909 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1910 FPT->getNumArgs(), EPI);
1911 }
1912
1913 return cast<FunctionType>(Result.getTypePtr());
1914}
1915
Chris Lattnerc6395932007-06-22 20:56:16 +00001916/// getComplexType - Return the uniqued reference to the type for a complex
1917/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001918QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001919 // Unique pointers, to guarantee there is only one pointer of a particular
1920 // structure.
1921 llvm::FoldingSetNodeID ID;
1922 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001923
Chris Lattnerc6395932007-06-22 20:56:16 +00001924 void *InsertPos = 0;
1925 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1926 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001927
Chris Lattnerc6395932007-06-22 20:56:16 +00001928 // If the pointee type isn't canonical, this won't be a canonical type either,
1929 // so fill in the canonical type field.
1930 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001931 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001932 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001933
Chris Lattnerc6395932007-06-22 20:56:16 +00001934 // Get the new insert position for the node we care about.
1935 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001936 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001937 }
John McCall90d1c2d2009-09-24 23:30:46 +00001938 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001939 Types.push_back(New);
1940 ComplexTypes.InsertNode(New, InsertPos);
1941 return QualType(New, 0);
1942}
1943
Chris Lattner970e54e2006-11-12 00:37:36 +00001944/// getPointerType - Return the uniqued reference to the type for a pointer to
1945/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001946QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001947 // Unique pointers, to guarantee there is only one pointer of a particular
1948 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001949 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001950 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001951
Chris Lattner67521df2007-01-27 01:29:36 +00001952 void *InsertPos = 0;
1953 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001954 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001955
Chris Lattner7ccecb92006-11-12 08:50:50 +00001956 // If the pointee type isn't canonical, this won't be a canonical type either,
1957 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001958 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001959 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001960 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001961
Chris Lattner67521df2007-01-27 01:29:36 +00001962 // Get the new insert position for the node we care about.
1963 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001964 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001965 }
John McCall90d1c2d2009-09-24 23:30:46 +00001966 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001967 Types.push_back(New);
1968 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001969 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001970}
1971
Mike Stump11289f42009-09-09 15:08:12 +00001972/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001973/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001974QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001975 assert(T->isFunctionType() && "block of function types only");
1976 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001977 // structure.
1978 llvm::FoldingSetNodeID ID;
1979 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001980
Steve Naroffec33ed92008-08-27 16:04:49 +00001981 void *InsertPos = 0;
1982 if (BlockPointerType *PT =
1983 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1984 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001985
1986 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001987 // type either so fill in the canonical type field.
1988 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001989 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001990 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001991
Steve Naroffec33ed92008-08-27 16:04:49 +00001992 // Get the new insert position for the node we care about.
1993 BlockPointerType *NewIP =
1994 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001995 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001996 }
John McCall90d1c2d2009-09-24 23:30:46 +00001997 BlockPointerType *New
1998 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001999 Types.push_back(New);
2000 BlockPointerTypes.InsertNode(New, InsertPos);
2001 return QualType(New, 0);
2002}
2003
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002004/// getLValueReferenceType - Return the uniqued reference to the type for an
2005/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002006QualType
2007ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002008 assert(getCanonicalType(T) != OverloadTy &&
2009 "Unresolved overloaded function type");
2010
Bill Wendling3708c182007-05-27 10:15:43 +00002011 // Unique pointers, to guarantee there is only one pointer of a particular
2012 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002013 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002014 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002015
2016 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002017 if (LValueReferenceType *RT =
2018 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002019 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002020
John McCallfc93cf92009-10-22 22:37:11 +00002021 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2022
Bill Wendling3708c182007-05-27 10:15:43 +00002023 // If the referencee type isn't canonical, this won't be a canonical type
2024 // either, so fill in the canonical type field.
2025 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002026 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2027 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2028 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002029
Bill Wendling3708c182007-05-27 10:15:43 +00002030 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002031 LValueReferenceType *NewIP =
2032 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002033 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002034 }
2035
John McCall90d1c2d2009-09-24 23:30:46 +00002036 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002037 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2038 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002039 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002040 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002041
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002042 return QualType(New, 0);
2043}
2044
2045/// getRValueReferenceType - Return the uniqued reference to the type for an
2046/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002047QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002048 // Unique pointers, to guarantee there is only one pointer of a particular
2049 // structure.
2050 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002051 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002052
2053 void *InsertPos = 0;
2054 if (RValueReferenceType *RT =
2055 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2056 return QualType(RT, 0);
2057
John McCallfc93cf92009-10-22 22:37:11 +00002058 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2059
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002060 // If the referencee type isn't canonical, this won't be a canonical type
2061 // either, so fill in the canonical type field.
2062 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002063 if (InnerRef || !T.isCanonical()) {
2064 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2065 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002066
2067 // Get the new insert position for the node we care about.
2068 RValueReferenceType *NewIP =
2069 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002070 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002071 }
2072
John McCall90d1c2d2009-09-24 23:30:46 +00002073 RValueReferenceType *New
2074 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002075 Types.push_back(New);
2076 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002077 return QualType(New, 0);
2078}
2079
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002080/// getMemberPointerType - Return the uniqued reference to the type for a
2081/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002082QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002083 // Unique pointers, to guarantee there is only one pointer of a particular
2084 // structure.
2085 llvm::FoldingSetNodeID ID;
2086 MemberPointerType::Profile(ID, T, Cls);
2087
2088 void *InsertPos = 0;
2089 if (MemberPointerType *PT =
2090 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2091 return QualType(PT, 0);
2092
2093 // If the pointee or class type isn't canonical, this won't be a canonical
2094 // type either, so fill in the canonical type field.
2095 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002096 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002097 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2098
2099 // Get the new insert position for the node we care about.
2100 MemberPointerType *NewIP =
2101 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002102 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002103 }
John McCall90d1c2d2009-09-24 23:30:46 +00002104 MemberPointerType *New
2105 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002106 Types.push_back(New);
2107 MemberPointerTypes.InsertNode(New, InsertPos);
2108 return QualType(New, 0);
2109}
2110
Mike Stump11289f42009-09-09 15:08:12 +00002111/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002112/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002113QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002114 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002115 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002116 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002117 assert((EltTy->isDependentType() ||
2118 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002119 "Constant array of VLAs is illegal!");
2120
Chris Lattnere2df3f92009-05-13 04:12:56 +00002121 // Convert the array size into a canonical width matching the pointer size for
2122 // the target.
2123 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002124 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002125 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002126
Chris Lattner23b7eb62007-06-15 23:05:46 +00002127 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002128 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002129
Chris Lattner36f8e652007-01-27 08:31:04 +00002130 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002131 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002132 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002133 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002134
John McCall33ddac02011-01-19 10:06:00 +00002135 // If the element type isn't canonical or has qualifiers, this won't
2136 // be a canonical type either, so fill in the canonical type field.
2137 QualType Canon;
2138 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2139 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002140 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002141 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002142 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002143
Chris Lattner36f8e652007-01-27 08:31:04 +00002144 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002145 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002146 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002147 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002148 }
Mike Stump11289f42009-09-09 15:08:12 +00002149
John McCall90d1c2d2009-09-24 23:30:46 +00002150 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002151 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002152 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002153 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002154 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002155}
2156
John McCall06549462011-01-18 08:40:38 +00002157/// getVariableArrayDecayedType - Turns the given type, which may be
2158/// variably-modified, into the corresponding type with all the known
2159/// sizes replaced with [*].
2160QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2161 // Vastly most common case.
2162 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002163
John McCall06549462011-01-18 08:40:38 +00002164 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002165
John McCall06549462011-01-18 08:40:38 +00002166 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002167 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002168 switch (ty->getTypeClass()) {
2169#define TYPE(Class, Base)
2170#define ABSTRACT_TYPE(Class, Base)
2171#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2172#include "clang/AST/TypeNodes.def"
2173 llvm_unreachable("didn't desugar past all non-canonical types?");
2174
2175 // These types should never be variably-modified.
2176 case Type::Builtin:
2177 case Type::Complex:
2178 case Type::Vector:
2179 case Type::ExtVector:
2180 case Type::DependentSizedExtVector:
2181 case Type::ObjCObject:
2182 case Type::ObjCInterface:
2183 case Type::ObjCObjectPointer:
2184 case Type::Record:
2185 case Type::Enum:
2186 case Type::UnresolvedUsing:
2187 case Type::TypeOfExpr:
2188 case Type::TypeOf:
2189 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002190 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002191 case Type::DependentName:
2192 case Type::InjectedClassName:
2193 case Type::TemplateSpecialization:
2194 case Type::DependentTemplateSpecialization:
2195 case Type::TemplateTypeParm:
2196 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002197 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002198 case Type::PackExpansion:
2199 llvm_unreachable("type should never be variably-modified");
2200
2201 // These types can be variably-modified but should never need to
2202 // further decay.
2203 case Type::FunctionNoProto:
2204 case Type::FunctionProto:
2205 case Type::BlockPointer:
2206 case Type::MemberPointer:
2207 return type;
2208
2209 // These types can be variably-modified. All these modifications
2210 // preserve structure except as noted by comments.
2211 // TODO: if we ever care about optimizing VLAs, there are no-op
2212 // optimizations available here.
2213 case Type::Pointer:
2214 result = getPointerType(getVariableArrayDecayedType(
2215 cast<PointerType>(ty)->getPointeeType()));
2216 break;
2217
2218 case Type::LValueReference: {
2219 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2220 result = getLValueReferenceType(
2221 getVariableArrayDecayedType(lv->getPointeeType()),
2222 lv->isSpelledAsLValue());
2223 break;
2224 }
2225
2226 case Type::RValueReference: {
2227 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2228 result = getRValueReferenceType(
2229 getVariableArrayDecayedType(lv->getPointeeType()));
2230 break;
2231 }
2232
Eli Friedman0dfb8892011-10-06 23:00:33 +00002233 case Type::Atomic: {
2234 const AtomicType *at = cast<AtomicType>(ty);
2235 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2236 break;
2237 }
2238
John McCall06549462011-01-18 08:40:38 +00002239 case Type::ConstantArray: {
2240 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2241 result = getConstantArrayType(
2242 getVariableArrayDecayedType(cat->getElementType()),
2243 cat->getSize(),
2244 cat->getSizeModifier(),
2245 cat->getIndexTypeCVRQualifiers());
2246 break;
2247 }
2248
2249 case Type::DependentSizedArray: {
2250 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2251 result = getDependentSizedArrayType(
2252 getVariableArrayDecayedType(dat->getElementType()),
2253 dat->getSizeExpr(),
2254 dat->getSizeModifier(),
2255 dat->getIndexTypeCVRQualifiers(),
2256 dat->getBracketsRange());
2257 break;
2258 }
2259
2260 // Turn incomplete types into [*] types.
2261 case Type::IncompleteArray: {
2262 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2263 result = getVariableArrayType(
2264 getVariableArrayDecayedType(iat->getElementType()),
2265 /*size*/ 0,
2266 ArrayType::Normal,
2267 iat->getIndexTypeCVRQualifiers(),
2268 SourceRange());
2269 break;
2270 }
2271
2272 // Turn VLA types into [*] types.
2273 case Type::VariableArray: {
2274 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2275 result = getVariableArrayType(
2276 getVariableArrayDecayedType(vat->getElementType()),
2277 /*size*/ 0,
2278 ArrayType::Star,
2279 vat->getIndexTypeCVRQualifiers(),
2280 vat->getBracketsRange());
2281 break;
2282 }
2283 }
2284
2285 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002286 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002287}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002288
Steve Naroffcadebd02007-08-30 18:14:25 +00002289/// getVariableArrayType - Returns a non-unique reference to the type for a
2290/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002291QualType ASTContext::getVariableArrayType(QualType EltTy,
2292 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002293 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002294 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002295 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002296 // Since we don't unique expressions, it isn't possible to unique VLA's
2297 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002298 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002299
John McCall33ddac02011-01-19 10:06:00 +00002300 // Be sure to pull qualifiers off the element type.
2301 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2302 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002303 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002304 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002305 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002306 }
2307
John McCall90d1c2d2009-09-24 23:30:46 +00002308 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002309 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002310
2311 VariableArrayTypes.push_back(New);
2312 Types.push_back(New);
2313 return QualType(New, 0);
2314}
2315
Douglas Gregor4619e432008-12-05 23:32:09 +00002316/// getDependentSizedArrayType - Returns a non-unique reference to
2317/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002318/// type.
John McCall33ddac02011-01-19 10:06:00 +00002319QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2320 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002321 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002322 unsigned elementTypeQuals,
2323 SourceRange brackets) const {
2324 assert((!numElements || numElements->isTypeDependent() ||
2325 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002326 "Size must be type- or value-dependent!");
2327
John McCall33ddac02011-01-19 10:06:00 +00002328 // Dependently-sized array types that do not have a specified number
2329 // of elements will have their sizes deduced from a dependent
2330 // initializer. We do no canonicalization here at all, which is okay
2331 // because they can't be used in most locations.
2332 if (!numElements) {
2333 DependentSizedArrayType *newType
2334 = new (*this, TypeAlignment)
2335 DependentSizedArrayType(*this, elementType, QualType(),
2336 numElements, ASM, elementTypeQuals,
2337 brackets);
2338 Types.push_back(newType);
2339 return QualType(newType, 0);
2340 }
2341
2342 // Otherwise, we actually build a new type every time, but we
2343 // also build a canonical type.
2344
2345 SplitQualType canonElementType = getCanonicalType(elementType).split();
2346
2347 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002348 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002349 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002350 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002351 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002352
John McCall33ddac02011-01-19 10:06:00 +00002353 // Look for an existing type with these properties.
2354 DependentSizedArrayType *canonTy =
2355 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002356
John McCall33ddac02011-01-19 10:06:00 +00002357 // If we don't have one, build one.
2358 if (!canonTy) {
2359 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002360 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002361 QualType(), numElements, ASM, elementTypeQuals,
2362 brackets);
2363 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2364 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002365 }
2366
John McCall33ddac02011-01-19 10:06:00 +00002367 // Apply qualifiers from the element type to the array.
2368 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002369 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002370
John McCall33ddac02011-01-19 10:06:00 +00002371 // If we didn't need extra canonicalization for the element type,
2372 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002373 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002374 return canon;
2375
2376 // Otherwise, we need to build a type which follows the spelling
2377 // of the element type.
2378 DependentSizedArrayType *sugaredType
2379 = new (*this, TypeAlignment)
2380 DependentSizedArrayType(*this, elementType, canon, numElements,
2381 ASM, elementTypeQuals, brackets);
2382 Types.push_back(sugaredType);
2383 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002384}
2385
John McCall33ddac02011-01-19 10:06:00 +00002386QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002387 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002388 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002389 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002390 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002391
John McCall33ddac02011-01-19 10:06:00 +00002392 void *insertPos = 0;
2393 if (IncompleteArrayType *iat =
2394 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2395 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002396
2397 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002398 // either, so fill in the canonical type field. We also have to pull
2399 // qualifiers off the element type.
2400 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002401
John McCall33ddac02011-01-19 10:06:00 +00002402 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2403 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002404 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002405 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002406 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002407
2408 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002409 IncompleteArrayType *existing =
2410 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2411 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002412 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002413
John McCall33ddac02011-01-19 10:06:00 +00002414 IncompleteArrayType *newType = new (*this, TypeAlignment)
2415 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002416
John McCall33ddac02011-01-19 10:06:00 +00002417 IncompleteArrayTypes.InsertNode(newType, insertPos);
2418 Types.push_back(newType);
2419 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002420}
2421
Steve Naroff91fcddb2007-07-18 18:00:27 +00002422/// getVectorType - Return the unique reference to a vector type of
2423/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002424QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002425 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002426 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002427
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002428 // Check if we've already instantiated a vector of this type.
2429 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002430 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002431
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002432 void *InsertPos = 0;
2433 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2434 return QualType(VTP, 0);
2435
2436 // If the element type isn't canonical, this won't be a canonical type either,
2437 // so fill in the canonical type field.
2438 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002439 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002440 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002441
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002442 // Get the new insert position for the node we care about.
2443 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002444 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002445 }
John McCall90d1c2d2009-09-24 23:30:46 +00002446 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002447 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002448 VectorTypes.InsertNode(New, InsertPos);
2449 Types.push_back(New);
2450 return QualType(New, 0);
2451}
2452
Nate Begemance4d7fc2008-04-18 23:10:10 +00002453/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002454/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002455QualType
2456ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002457 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002458
Steve Naroff91fcddb2007-07-18 18:00:27 +00002459 // Check if we've already instantiated a vector of this type.
2460 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002461 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002462 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002463 void *InsertPos = 0;
2464 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2465 return QualType(VTP, 0);
2466
2467 // If the element type isn't canonical, this won't be a canonical type either,
2468 // so fill in the canonical type field.
2469 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002470 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002471 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002472
Steve Naroff91fcddb2007-07-18 18:00:27 +00002473 // Get the new insert position for the node we care about.
2474 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002475 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002476 }
John McCall90d1c2d2009-09-24 23:30:46 +00002477 ExtVectorType *New = new (*this, TypeAlignment)
2478 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002479 VectorTypes.InsertNode(New, InsertPos);
2480 Types.push_back(New);
2481 return QualType(New, 0);
2482}
2483
Jay Foad39c79802011-01-12 09:06:06 +00002484QualType
2485ASTContext::getDependentSizedExtVectorType(QualType vecType,
2486 Expr *SizeExpr,
2487 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002488 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002489 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002490 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002491
Douglas Gregor352169a2009-07-31 03:54:25 +00002492 void *InsertPos = 0;
2493 DependentSizedExtVectorType *Canon
2494 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2495 DependentSizedExtVectorType *New;
2496 if (Canon) {
2497 // We already have a canonical version of this array type; use it as
2498 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002499 New = new (*this, TypeAlignment)
2500 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2501 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002502 } else {
2503 QualType CanonVecTy = getCanonicalType(vecType);
2504 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002505 New = new (*this, TypeAlignment)
2506 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2507 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002508
2509 DependentSizedExtVectorType *CanonCheck
2510 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2511 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2512 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002513 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2514 } else {
2515 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2516 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002517 New = new (*this, TypeAlignment)
2518 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002519 }
2520 }
Mike Stump11289f42009-09-09 15:08:12 +00002521
Douglas Gregor758a8692009-06-17 21:51:59 +00002522 Types.push_back(New);
2523 return QualType(New, 0);
2524}
2525
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002526/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002527///
Jay Foad39c79802011-01-12 09:06:06 +00002528QualType
2529ASTContext::getFunctionNoProtoType(QualType ResultTy,
2530 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002531 const CallingConv DefaultCC = Info.getCC();
2532 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2533 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002534 // Unique functions, to guarantee there is only one function of a particular
2535 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002536 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002537 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002538
Chris Lattner47955de2007-01-27 08:37:20 +00002539 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002540 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002541 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002542 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002543
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002544 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002545 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002546 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002547 Canonical =
2548 getFunctionNoProtoType(getCanonicalType(ResultTy),
2549 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002550
Chris Lattner47955de2007-01-27 08:37:20 +00002551 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002552 FunctionNoProtoType *NewIP =
2553 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002554 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002555 }
Mike Stump11289f42009-09-09 15:08:12 +00002556
Roman Divacky65b88cd2011-03-01 17:40:53 +00002557 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002558 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002559 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002560 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002561 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002562 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002563}
2564
2565/// getFunctionType - Return a normal function type with a typed argument
2566/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002567QualType
2568ASTContext::getFunctionType(QualType ResultTy,
2569 const QualType *ArgArray, unsigned NumArgs,
2570 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002571 // Unique functions, to guarantee there is only one function of a particular
2572 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002573 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002574 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002575
2576 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002577 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002578 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002579 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002580
2581 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002582 bool isCanonical =
2583 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2584 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002585 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002586 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002587 isCanonical = false;
2588
Roman Divacky65b88cd2011-03-01 17:40:53 +00002589 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2590 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2591 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002592
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002593 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002594 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002595 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002596 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002597 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002598 CanonicalArgs.reserve(NumArgs);
2599 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002600 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002601
John McCalldb40c7f2010-12-14 08:05:40 +00002602 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002603 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002604 CanonicalEPI.ExceptionSpecType = EST_None;
2605 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002606 CanonicalEPI.ExtInfo
2607 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2608
Chris Lattner76a00cf2008-04-06 22:59:24 +00002609 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002610 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002611 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002612
Chris Lattnerfd4de792007-01-27 01:15:32 +00002613 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002614 FunctionProtoType *NewIP =
2615 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002616 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002617 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002618
John McCall31168b02011-06-15 23:02:42 +00002619 // FunctionProtoType objects are allocated with extra bytes after
2620 // them for three variable size arrays at the end:
2621 // - parameter types
2622 // - exception types
2623 // - consumed-arguments flags
2624 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002625 // expression, or information used to resolve the exception
2626 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002627 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002628 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002629 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002630 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002631 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002632 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002633 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002634 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002635 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2636 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002637 }
John McCall31168b02011-06-15 23:02:42 +00002638 if (EPI.ConsumedArguments)
2639 Size += NumArgs * sizeof(bool);
2640
John McCalldb40c7f2010-12-14 08:05:40 +00002641 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002642 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2643 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002644 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002645 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002646 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002647 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002648}
Chris Lattneref51c202006-11-10 07:17:23 +00002649
John McCalle78aac42010-03-10 03:28:59 +00002650#ifndef NDEBUG
2651static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2652 if (!isa<CXXRecordDecl>(D)) return false;
2653 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2654 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2655 return true;
2656 if (RD->getDescribedClassTemplate() &&
2657 !isa<ClassTemplateSpecializationDecl>(RD))
2658 return true;
2659 return false;
2660}
2661#endif
2662
2663/// getInjectedClassNameType - Return the unique reference to the
2664/// injected class name type for the specified templated declaration.
2665QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002666 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002667 assert(NeedsInjectedClassNameType(Decl));
2668 if (Decl->TypeForDecl) {
2669 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002670 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002671 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2672 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2673 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2674 } else {
John McCall424cec92011-01-19 06:33:43 +00002675 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002676 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002677 Decl->TypeForDecl = newType;
2678 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002679 }
2680 return QualType(Decl->TypeForDecl, 0);
2681}
2682
Douglas Gregor83a586e2008-04-13 21:07:44 +00002683/// getTypeDeclType - Return the unique reference to the type for the
2684/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002685QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002686 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002687 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002688
Richard Smithdda56e42011-04-15 14:24:37 +00002689 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002690 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002691
John McCall96f0b5f2010-03-10 06:48:02 +00002692 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2693 "Template type parameter types are always available.");
2694
John McCall81e38502010-02-16 03:57:14 +00002695 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002696 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002697 "struct/union has previous declaration");
2698 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002699 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002700 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002701 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002702 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002703 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002704 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002705 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002706 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2707 Decl->TypeForDecl = newType;
2708 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002709 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002710 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002711
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002712 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002713}
2714
Chris Lattner32d920b2007-01-26 02:01:53 +00002715/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002716/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002717QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002718ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2719 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002720 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002721
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002722 if (Canonical.isNull())
2723 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002724 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002725 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002726 Decl->TypeForDecl = newType;
2727 Types.push_back(newType);
2728 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002729}
2730
Jay Foad39c79802011-01-12 09:06:06 +00002731QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002732 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2733
Douglas Gregorec9fd132012-01-14 16:38:05 +00002734 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002735 if (PrevDecl->TypeForDecl)
2736 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2737
John McCall424cec92011-01-19 06:33:43 +00002738 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2739 Decl->TypeForDecl = newType;
2740 Types.push_back(newType);
2741 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002742}
2743
Jay Foad39c79802011-01-12 09:06:06 +00002744QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002745 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2746
Douglas Gregorec9fd132012-01-14 16:38:05 +00002747 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002748 if (PrevDecl->TypeForDecl)
2749 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2750
John McCall424cec92011-01-19 06:33:43 +00002751 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2752 Decl->TypeForDecl = newType;
2753 Types.push_back(newType);
2754 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002755}
2756
John McCall81904512011-01-06 01:58:22 +00002757QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2758 QualType modifiedType,
2759 QualType equivalentType) {
2760 llvm::FoldingSetNodeID id;
2761 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2762
2763 void *insertPos = 0;
2764 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2765 if (type) return QualType(type, 0);
2766
2767 QualType canon = getCanonicalType(equivalentType);
2768 type = new (*this, TypeAlignment)
2769 AttributedType(canon, attrKind, modifiedType, equivalentType);
2770
2771 Types.push_back(type);
2772 AttributedTypes.InsertNode(type, insertPos);
2773
2774 return QualType(type, 0);
2775}
2776
2777
John McCallcebee162009-10-18 09:09:24 +00002778/// \brief Retrieve a substitution-result type.
2779QualType
2780ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002781 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002782 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002783 && "replacement types must always be canonical");
2784
2785 llvm::FoldingSetNodeID ID;
2786 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2787 void *InsertPos = 0;
2788 SubstTemplateTypeParmType *SubstParm
2789 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2790
2791 if (!SubstParm) {
2792 SubstParm = new (*this, TypeAlignment)
2793 SubstTemplateTypeParmType(Parm, Replacement);
2794 Types.push_back(SubstParm);
2795 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2796 }
2797
2798 return QualType(SubstParm, 0);
2799}
2800
Douglas Gregorada4b792011-01-14 02:55:32 +00002801/// \brief Retrieve a
2802QualType ASTContext::getSubstTemplateTypeParmPackType(
2803 const TemplateTypeParmType *Parm,
2804 const TemplateArgument &ArgPack) {
2805#ifndef NDEBUG
2806 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2807 PEnd = ArgPack.pack_end();
2808 P != PEnd; ++P) {
2809 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2810 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2811 }
2812#endif
2813
2814 llvm::FoldingSetNodeID ID;
2815 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2816 void *InsertPos = 0;
2817 if (SubstTemplateTypeParmPackType *SubstParm
2818 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2819 return QualType(SubstParm, 0);
2820
2821 QualType Canon;
2822 if (!Parm->isCanonicalUnqualified()) {
2823 Canon = getCanonicalType(QualType(Parm, 0));
2824 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2825 ArgPack);
2826 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2827 }
2828
2829 SubstTemplateTypeParmPackType *SubstParm
2830 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2831 ArgPack);
2832 Types.push_back(SubstParm);
2833 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2834 return QualType(SubstParm, 0);
2835}
2836
Douglas Gregoreff93e02009-02-05 23:33:38 +00002837/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002838/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002839/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002840QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002841 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002842 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002843 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002844 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002845 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002846 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002847 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2848
2849 if (TypeParm)
2850 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002851
Chandler Carruth08836322011-05-01 00:51:33 +00002852 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002853 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002854 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002855
2856 TemplateTypeParmType *TypeCheck
2857 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2858 assert(!TypeCheck && "Template type parameter canonical type broken");
2859 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002860 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002861 TypeParm = new (*this, TypeAlignment)
2862 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002863
2864 Types.push_back(TypeParm);
2865 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2866
2867 return QualType(TypeParm, 0);
2868}
2869
John McCalle78aac42010-03-10 03:28:59 +00002870TypeSourceInfo *
2871ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2872 SourceLocation NameLoc,
2873 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002874 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002875 assert(!Name.getAsDependentTemplateName() &&
2876 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002877 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002878
2879 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2880 TemplateSpecializationTypeLoc TL
2881 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002882 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002883 TL.setTemplateNameLoc(NameLoc);
2884 TL.setLAngleLoc(Args.getLAngleLoc());
2885 TL.setRAngleLoc(Args.getRAngleLoc());
2886 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2887 TL.setArgLocInfo(i, Args[i].getLocInfo());
2888 return DI;
2889}
2890
Mike Stump11289f42009-09-09 15:08:12 +00002891QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002892ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002893 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002894 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002895 assert(!Template.getAsDependentTemplateName() &&
2896 "No dependent template names here!");
2897
John McCall6b51f282009-11-23 01:53:49 +00002898 unsigned NumArgs = Args.size();
2899
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002900 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002901 ArgVec.reserve(NumArgs);
2902 for (unsigned i = 0; i != NumArgs; ++i)
2903 ArgVec.push_back(Args[i].getArgument());
2904
John McCall2408e322010-04-27 00:57:59 +00002905 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002906 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002907}
2908
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002909#ifndef NDEBUG
2910static bool hasAnyPackExpansions(const TemplateArgument *Args,
2911 unsigned NumArgs) {
2912 for (unsigned I = 0; I != NumArgs; ++I)
2913 if (Args[I].isPackExpansion())
2914 return true;
2915
2916 return true;
2917}
2918#endif
2919
John McCall0ad16662009-10-29 08:12:44 +00002920QualType
2921ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002922 const TemplateArgument *Args,
2923 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002924 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002925 assert(!Template.getAsDependentTemplateName() &&
2926 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002927 // Look through qualified template names.
2928 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2929 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002930
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002931 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002932 Template.getAsTemplateDecl() &&
2933 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002934 QualType CanonType;
2935 if (!Underlying.isNull())
2936 CanonType = getCanonicalType(Underlying);
2937 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002938 // We can get here with an alias template when the specialization contains
2939 // a pack expansion that does not match up with a parameter pack.
2940 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2941 "Caller must compute aliased type");
2942 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002943 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2944 NumArgs);
2945 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002946
Douglas Gregora8e02e72009-07-28 23:00:59 +00002947 // Allocate the (non-canonical) template specialization type, but don't
2948 // try to unique it: these types typically have location information that
2949 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002950 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2951 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002952 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002953 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002954 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002955 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2956 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002957
Douglas Gregor8bf42052009-02-09 18:46:07 +00002958 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002959 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002960}
2961
Mike Stump11289f42009-09-09 15:08:12 +00002962QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002963ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2964 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002965 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002966 assert(!Template.getAsDependentTemplateName() &&
2967 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002968
Douglas Gregore29139c2011-03-03 17:04:51 +00002969 // Look through qualified template names.
2970 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2971 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002972
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002973 // Build the canonical template specialization type.
2974 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002975 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002976 CanonArgs.reserve(NumArgs);
2977 for (unsigned I = 0; I != NumArgs; ++I)
2978 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2979
2980 // Determine whether this canonical template specialization type already
2981 // exists.
2982 llvm::FoldingSetNodeID ID;
2983 TemplateSpecializationType::Profile(ID, CanonTemplate,
2984 CanonArgs.data(), NumArgs, *this);
2985
2986 void *InsertPos = 0;
2987 TemplateSpecializationType *Spec
2988 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2989
2990 if (!Spec) {
2991 // Allocate a new canonical template specialization type.
2992 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2993 sizeof(TemplateArgument) * NumArgs),
2994 TypeAlignment);
2995 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2996 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002997 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002998 Types.push_back(Spec);
2999 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3000 }
3001
3002 assert(Spec->isDependentType() &&
3003 "Non-dependent template-id type must have a canonical type");
3004 return QualType(Spec, 0);
3005}
3006
3007QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003008ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3009 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003010 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003011 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003012 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003013
3014 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003015 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003016 if (T)
3017 return QualType(T, 0);
3018
Douglas Gregorc42075a2010-02-04 18:10:26 +00003019 QualType Canon = NamedType;
3020 if (!Canon.isCanonical()) {
3021 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003022 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3023 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003024 (void)CheckT;
3025 }
3026
Abramo Bagnara6150c882010-05-11 21:36:43 +00003027 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003028 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003029 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003030 return QualType(T, 0);
3031}
3032
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003033QualType
Jay Foad39c79802011-01-12 09:06:06 +00003034ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003035 llvm::FoldingSetNodeID ID;
3036 ParenType::Profile(ID, InnerType);
3037
3038 void *InsertPos = 0;
3039 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3040 if (T)
3041 return QualType(T, 0);
3042
3043 QualType Canon = InnerType;
3044 if (!Canon.isCanonical()) {
3045 Canon = getCanonicalType(InnerType);
3046 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3047 assert(!CheckT && "Paren canonical type broken");
3048 (void)CheckT;
3049 }
3050
3051 T = new (*this) ParenType(InnerType, Canon);
3052 Types.push_back(T);
3053 ParenTypes.InsertNode(T, InsertPos);
3054 return QualType(T, 0);
3055}
3056
Douglas Gregor02085352010-03-31 20:19:30 +00003057QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3058 NestedNameSpecifier *NNS,
3059 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003060 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003061 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3062
3063 if (Canon.isNull()) {
3064 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003065 ElaboratedTypeKeyword CanonKeyword = Keyword;
3066 if (Keyword == ETK_None)
3067 CanonKeyword = ETK_Typename;
3068
3069 if (CanonNNS != NNS || CanonKeyword != Keyword)
3070 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003071 }
3072
3073 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003074 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003075
3076 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003077 DependentNameType *T
3078 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003079 if (T)
3080 return QualType(T, 0);
3081
Douglas Gregor02085352010-03-31 20:19:30 +00003082 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003083 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003084 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003085 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003086}
3087
Mike Stump11289f42009-09-09 15:08:12 +00003088QualType
John McCallc392f372010-06-11 00:33:02 +00003089ASTContext::getDependentTemplateSpecializationType(
3090 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003091 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003092 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003093 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003094 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003095 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003096 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3097 ArgCopy.push_back(Args[I].getArgument());
3098 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3099 ArgCopy.size(),
3100 ArgCopy.data());
3101}
3102
3103QualType
3104ASTContext::getDependentTemplateSpecializationType(
3105 ElaboratedTypeKeyword Keyword,
3106 NestedNameSpecifier *NNS,
3107 const IdentifierInfo *Name,
3108 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003109 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003110 assert((!NNS || NNS->isDependent()) &&
3111 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003112
Douglas Gregorc42075a2010-02-04 18:10:26 +00003113 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003114 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3115 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003116
3117 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003118 DependentTemplateSpecializationType *T
3119 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003120 if (T)
3121 return QualType(T, 0);
3122
John McCallc392f372010-06-11 00:33:02 +00003123 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003124
John McCallc392f372010-06-11 00:33:02 +00003125 ElaboratedTypeKeyword CanonKeyword = Keyword;
3126 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3127
3128 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003129 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003130 for (unsigned I = 0; I != NumArgs; ++I) {
3131 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3132 if (!CanonArgs[I].structurallyEquals(Args[I]))
3133 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003134 }
3135
John McCallc392f372010-06-11 00:33:02 +00003136 QualType Canon;
3137 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3138 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3139 Name, NumArgs,
3140 CanonArgs.data());
3141
3142 // Find the insert position again.
3143 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3144 }
3145
3146 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3147 sizeof(TemplateArgument) * NumArgs),
3148 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003149 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003150 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003151 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003152 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003153 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003154}
3155
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003156QualType ASTContext::getPackExpansionType(QualType Pattern,
3157 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003158 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003159 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003160
3161 assert(Pattern->containsUnexpandedParameterPack() &&
3162 "Pack expansions must expand one or more parameter packs");
3163 void *InsertPos = 0;
3164 PackExpansionType *T
3165 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3166 if (T)
3167 return QualType(T, 0);
3168
3169 QualType Canon;
3170 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003171 Canon = getCanonicalType(Pattern);
3172 // The canonical type might not contain an unexpanded parameter pack, if it
3173 // contains an alias template specialization which ignores one of its
3174 // parameters.
3175 if (Canon->containsUnexpandedParameterPack()) {
3176 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003177
Richard Smith68eea502012-07-16 00:20:35 +00003178 // Find the insert position again, in case we inserted an element into
3179 // PackExpansionTypes and invalidated our insert position.
3180 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3181 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003182 }
3183
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003184 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003185 Types.push_back(T);
3186 PackExpansionTypes.InsertNode(T, InsertPos);
3187 return QualType(T, 0);
3188}
3189
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003190/// CmpProtocolNames - Comparison predicate for sorting protocols
3191/// alphabetically.
3192static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3193 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003194 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003195}
3196
John McCall8b07ec22010-05-15 11:32:37 +00003197static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003198 unsigned NumProtocols) {
3199 if (NumProtocols == 0) return true;
3200
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003201 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3202 return false;
3203
John McCallfc93cf92009-10-22 22:37:11 +00003204 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003205 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3206 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003207 return false;
3208 return true;
3209}
3210
3211static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003212 unsigned &NumProtocols) {
3213 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003214
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003215 // Sort protocols, keyed by name.
3216 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3217
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003218 // Canonicalize.
3219 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3220 Protocols[I] = Protocols[I]->getCanonicalDecl();
3221
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003222 // Remove duplicates.
3223 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3224 NumProtocols = ProtocolsEnd-Protocols;
3225}
3226
John McCall8b07ec22010-05-15 11:32:37 +00003227QualType ASTContext::getObjCObjectType(QualType BaseType,
3228 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003229 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003230 // If the base type is an interface and there aren't any protocols
3231 // to add, then the interface type will do just fine.
3232 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3233 return BaseType;
3234
3235 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003236 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003237 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003238 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003239 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3240 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003241
John McCall8b07ec22010-05-15 11:32:37 +00003242 // Build the canonical type, which has the canonical base type and
3243 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003244 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003245 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3246 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3247 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003248 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003249 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003250 unsigned UniqueCount = NumProtocols;
3251
John McCallfc93cf92009-10-22 22:37:11 +00003252 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003253 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3254 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003255 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003256 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3257 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003258 }
3259
3260 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003261 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3262 }
3263
3264 unsigned Size = sizeof(ObjCObjectTypeImpl);
3265 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3266 void *Mem = Allocate(Size, TypeAlignment);
3267 ObjCObjectTypeImpl *T =
3268 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3269
3270 Types.push_back(T);
3271 ObjCObjectTypes.InsertNode(T, InsertPos);
3272 return QualType(T, 0);
3273}
3274
3275/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3276/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003277QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003278 llvm::FoldingSetNodeID ID;
3279 ObjCObjectPointerType::Profile(ID, ObjectT);
3280
3281 void *InsertPos = 0;
3282 if (ObjCObjectPointerType *QT =
3283 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3284 return QualType(QT, 0);
3285
3286 // Find the canonical object type.
3287 QualType Canonical;
3288 if (!ObjectT.isCanonical()) {
3289 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3290
3291 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003292 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3293 }
3294
Douglas Gregorf85bee62010-02-08 22:59:26 +00003295 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003296 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3297 ObjCObjectPointerType *QType =
3298 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003299
Steve Narofffb4330f2009-06-17 22:40:22 +00003300 Types.push_back(QType);
3301 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003302 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003303}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003304
Douglas Gregor1c283312010-08-11 12:19:30 +00003305/// getObjCInterfaceType - Return the unique reference to the type for the
3306/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003307QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3308 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003309 if (Decl->TypeForDecl)
3310 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003311
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003312 if (PrevDecl) {
3313 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3314 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3315 return QualType(PrevDecl->TypeForDecl, 0);
3316 }
3317
Douglas Gregor7671e532011-12-16 16:34:57 +00003318 // Prefer the definition, if there is one.
3319 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3320 Decl = Def;
3321
Douglas Gregor1c283312010-08-11 12:19:30 +00003322 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3323 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3324 Decl->TypeForDecl = T;
3325 Types.push_back(T);
3326 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003327}
3328
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003329/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3330/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003331/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003332/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003333/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003334QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003335 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003336 if (tofExpr->isTypeDependent()) {
3337 llvm::FoldingSetNodeID ID;
3338 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003339
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003340 void *InsertPos = 0;
3341 DependentTypeOfExprType *Canon
3342 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3343 if (Canon) {
3344 // We already have a "canonical" version of an identical, dependent
3345 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003346 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003347 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003348 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003349 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003350 Canon
3351 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003352 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3353 toe = Canon;
3354 }
3355 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003356 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003357 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003358 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003359 Types.push_back(toe);
3360 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003361}
3362
Steve Naroffa773cd52007-08-01 18:02:17 +00003363/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3364/// TypeOfType AST's. The only motivation to unique these nodes would be
3365/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003366/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003367/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003368QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003369 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003370 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003371 Types.push_back(tot);
3372 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003373}
3374
Anders Carlssonad6bd352009-06-24 21:24:56 +00003375
Anders Carlsson81df7b82009-06-24 19:06:50 +00003376/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3377/// DecltypeType AST's. The only motivation to unique these nodes would be
3378/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003379/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003380/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003381QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003382 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003383
3384 // C++0x [temp.type]p2:
3385 // If an expression e involves a template parameter, decltype(e) denotes a
3386 // unique dependent type. Two such decltype-specifiers refer to the same
3387 // type only if their expressions are equivalent (14.5.6.1).
3388 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003389 llvm::FoldingSetNodeID ID;
3390 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003391
Douglas Gregora21f6c32009-07-30 23:36:40 +00003392 void *InsertPos = 0;
3393 DependentDecltypeType *Canon
3394 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3395 if (Canon) {
3396 // We already have a "canonical" version of an equivalent, dependent
3397 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003398 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003399 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003400 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003401 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003402 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003403 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3404 dt = Canon;
3405 }
3406 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003407 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3408 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003409 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003410 Types.push_back(dt);
3411 return QualType(dt, 0);
3412}
3413
Alexis Hunte852b102011-05-24 22:41:36 +00003414/// getUnaryTransformationType - We don't unique these, since the memory
3415/// savings are minimal and these are rare.
3416QualType ASTContext::getUnaryTransformType(QualType BaseType,
3417 QualType UnderlyingType,
3418 UnaryTransformType::UTTKind Kind)
3419 const {
3420 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003421 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3422 Kind,
3423 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003424 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003425 Types.push_back(Ty);
3426 return QualType(Ty, 0);
3427}
3428
Richard Smithb2bc2e62011-02-21 20:05:19 +00003429/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003430QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003431 void *InsertPos = 0;
3432 if (!DeducedType.isNull()) {
3433 // Look in the folding set for an existing type.
3434 llvm::FoldingSetNodeID ID;
3435 AutoType::Profile(ID, DeducedType);
3436 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3437 return QualType(AT, 0);
3438 }
3439
3440 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3441 Types.push_back(AT);
3442 if (InsertPos)
3443 AutoTypes.InsertNode(AT, InsertPos);
3444 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003445}
3446
Eli Friedman0dfb8892011-10-06 23:00:33 +00003447/// getAtomicType - Return the uniqued reference to the atomic type for
3448/// the given value type.
3449QualType ASTContext::getAtomicType(QualType T) const {
3450 // Unique pointers, to guarantee there is only one pointer of a particular
3451 // structure.
3452 llvm::FoldingSetNodeID ID;
3453 AtomicType::Profile(ID, T);
3454
3455 void *InsertPos = 0;
3456 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3457 return QualType(AT, 0);
3458
3459 // If the atomic value type isn't canonical, this won't be a canonical type
3460 // either, so fill in the canonical type field.
3461 QualType Canonical;
3462 if (!T.isCanonical()) {
3463 Canonical = getAtomicType(getCanonicalType(T));
3464
3465 // Get the new insert position for the node we care about.
3466 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3467 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3468 }
3469 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3470 Types.push_back(New);
3471 AtomicTypes.InsertNode(New, InsertPos);
3472 return QualType(New, 0);
3473}
3474
Richard Smith02e85f32011-04-14 22:09:26 +00003475/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3476QualType ASTContext::getAutoDeductType() const {
3477 if (AutoDeductTy.isNull())
3478 AutoDeductTy = getAutoType(QualType());
3479 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3480 return AutoDeductTy;
3481}
3482
3483/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3484QualType ASTContext::getAutoRRefDeductType() const {
3485 if (AutoRRefDeductTy.isNull())
3486 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3487 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3488 return AutoRRefDeductTy;
3489}
3490
Chris Lattnerfb072462007-01-23 05:45:31 +00003491/// getTagDeclType - Return the unique reference to the type for the
3492/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003493QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003494 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003495 // FIXME: What is the design on getTagDeclType when it requires casting
3496 // away const? mutable?
3497 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003498}
3499
Mike Stump11289f42009-09-09 15:08:12 +00003500/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3501/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3502/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003503CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003504 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003505}
Chris Lattnerfb072462007-01-23 05:45:31 +00003506
Hans Wennborg27541db2011-10-27 08:29:09 +00003507/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3508CanQualType ASTContext::getIntMaxType() const {
3509 return getFromTargetType(Target->getIntMaxType());
3510}
3511
3512/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3513CanQualType ASTContext::getUIntMaxType() const {
3514 return getFromTargetType(Target->getUIntMaxType());
3515}
3516
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003517/// getSignedWCharType - Return the type of "signed wchar_t".
3518/// Used when in C++, as a GCC extension.
3519QualType ASTContext::getSignedWCharType() const {
3520 // FIXME: derive from "Target" ?
3521 return WCharTy;
3522}
3523
3524/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3525/// Used when in C++, as a GCC extension.
3526QualType ASTContext::getUnsignedWCharType() const {
3527 // FIXME: derive from "Target" ?
3528 return UnsignedIntTy;
3529}
3530
Hans Wennborg27541db2011-10-27 08:29:09 +00003531/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003532/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3533QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003534 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003535}
3536
Chris Lattnera21ad802008-04-02 05:18:44 +00003537//===----------------------------------------------------------------------===//
3538// Type Operators
3539//===----------------------------------------------------------------------===//
3540
Jay Foad39c79802011-01-12 09:06:06 +00003541CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003542 // Push qualifiers into arrays, and then discard any remaining
3543 // qualifiers.
3544 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003545 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003546 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003547 QualType Result;
3548 if (isa<ArrayType>(Ty)) {
3549 Result = getArrayDecayedType(QualType(Ty,0));
3550 } else if (isa<FunctionType>(Ty)) {
3551 Result = getPointerType(QualType(Ty, 0));
3552 } else {
3553 Result = QualType(Ty, 0);
3554 }
3555
3556 return CanQualType::CreateUnsafe(Result);
3557}
3558
John McCall6c9dd522011-01-18 07:41:22 +00003559QualType ASTContext::getUnqualifiedArrayType(QualType type,
3560 Qualifiers &quals) {
3561 SplitQualType splitType = type.getSplitUnqualifiedType();
3562
3563 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3564 // the unqualified desugared type and then drops it on the floor.
3565 // We then have to strip that sugar back off with
3566 // getUnqualifiedDesugaredType(), which is silly.
3567 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003568 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003569
3570 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003571 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003572 quals = splitType.Quals;
3573 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003574 }
3575
John McCall6c9dd522011-01-18 07:41:22 +00003576 // Otherwise, recurse on the array's element type.
3577 QualType elementType = AT->getElementType();
3578 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3579
3580 // If that didn't change the element type, AT has no qualifiers, so we
3581 // can just use the results in splitType.
3582 if (elementType == unqualElementType) {
3583 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003584 quals = splitType.Quals;
3585 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003586 }
3587
3588 // Otherwise, add in the qualifiers from the outermost type, then
3589 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003590 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003591
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003592 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003593 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003594 CAT->getSizeModifier(), 0);
3595 }
3596
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003597 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003598 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003599 }
3600
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003601 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003602 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003603 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003604 VAT->getSizeModifier(),
3605 VAT->getIndexTypeCVRQualifiers(),
3606 VAT->getBracketsRange());
3607 }
3608
3609 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003610 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003611 DSAT->getSizeModifier(), 0,
3612 SourceRange());
3613}
3614
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003615/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3616/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3617/// they point to and return true. If T1 and T2 aren't pointer types
3618/// or pointer-to-member types, or if they are not similar at this
3619/// level, returns false and leaves T1 and T2 unchanged. Top-level
3620/// qualifiers on T1 and T2 are ignored. This function will typically
3621/// be called in a loop that successively "unwraps" pointer and
3622/// pointer-to-member types to compare them at each level.
3623bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3624 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3625 *T2PtrType = T2->getAs<PointerType>();
3626 if (T1PtrType && T2PtrType) {
3627 T1 = T1PtrType->getPointeeType();
3628 T2 = T2PtrType->getPointeeType();
3629 return true;
3630 }
3631
3632 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3633 *T2MPType = T2->getAs<MemberPointerType>();
3634 if (T1MPType && T2MPType &&
3635 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3636 QualType(T2MPType->getClass(), 0))) {
3637 T1 = T1MPType->getPointeeType();
3638 T2 = T2MPType->getPointeeType();
3639 return true;
3640 }
3641
David Blaikiebbafb8a2012-03-11 07:00:24 +00003642 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003643 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3644 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3645 if (T1OPType && T2OPType) {
3646 T1 = T1OPType->getPointeeType();
3647 T2 = T2OPType->getPointeeType();
3648 return true;
3649 }
3650 }
3651
3652 // FIXME: Block pointers, too?
3653
3654 return false;
3655}
3656
Jay Foad39c79802011-01-12 09:06:06 +00003657DeclarationNameInfo
3658ASTContext::getNameForTemplate(TemplateName Name,
3659 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003660 switch (Name.getKind()) {
3661 case TemplateName::QualifiedTemplate:
3662 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003663 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003664 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3665 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003666
John McCalld9dfe3a2011-06-30 08:33:18 +00003667 case TemplateName::OverloadedTemplate: {
3668 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3669 // DNInfo work in progress: CHECKME: what about DNLoc?
3670 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3671 }
3672
3673 case TemplateName::DependentTemplate: {
3674 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003675 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003676 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003677 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3678 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003679 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003680 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3681 // DNInfo work in progress: FIXME: source locations?
3682 DeclarationNameLoc DNLoc;
3683 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3684 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3685 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003686 }
3687 }
3688
John McCalld9dfe3a2011-06-30 08:33:18 +00003689 case TemplateName::SubstTemplateTemplateParm: {
3690 SubstTemplateTemplateParmStorage *subst
3691 = Name.getAsSubstTemplateTemplateParm();
3692 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3693 NameLoc);
3694 }
3695
3696 case TemplateName::SubstTemplateTemplateParmPack: {
3697 SubstTemplateTemplateParmPackStorage *subst
3698 = Name.getAsSubstTemplateTemplateParmPack();
3699 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3700 NameLoc);
3701 }
3702 }
3703
3704 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003705}
3706
Jay Foad39c79802011-01-12 09:06:06 +00003707TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003708 switch (Name.getKind()) {
3709 case TemplateName::QualifiedTemplate:
3710 case TemplateName::Template: {
3711 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003712 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003713 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003714 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3715
3716 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003717 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003718 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003719
John McCalld9dfe3a2011-06-30 08:33:18 +00003720 case TemplateName::OverloadedTemplate:
3721 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003722
John McCalld9dfe3a2011-06-30 08:33:18 +00003723 case TemplateName::DependentTemplate: {
3724 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3725 assert(DTN && "Non-dependent template names must refer to template decls.");
3726 return DTN->CanonicalTemplateName;
3727 }
3728
3729 case TemplateName::SubstTemplateTemplateParm: {
3730 SubstTemplateTemplateParmStorage *subst
3731 = Name.getAsSubstTemplateTemplateParm();
3732 return getCanonicalTemplateName(subst->getReplacement());
3733 }
3734
3735 case TemplateName::SubstTemplateTemplateParmPack: {
3736 SubstTemplateTemplateParmPackStorage *subst
3737 = Name.getAsSubstTemplateTemplateParmPack();
3738 TemplateTemplateParmDecl *canonParameter
3739 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3740 TemplateArgument canonArgPack
3741 = getCanonicalTemplateArgument(subst->getArgumentPack());
3742 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3743 }
3744 }
3745
3746 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003747}
3748
Douglas Gregoradee3e32009-11-11 23:06:43 +00003749bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3750 X = getCanonicalTemplateName(X);
3751 Y = getCanonicalTemplateName(Y);
3752 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3753}
3754
Mike Stump11289f42009-09-09 15:08:12 +00003755TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003756ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003757 switch (Arg.getKind()) {
3758 case TemplateArgument::Null:
3759 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003760
Douglas Gregora8e02e72009-07-28 23:00:59 +00003761 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003762 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003763
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003764 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00003765 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3766 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003767 }
Mike Stump11289f42009-09-09 15:08:12 +00003768
Eli Friedmanb826a002012-09-26 02:36:12 +00003769 case TemplateArgument::NullPtr:
3770 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3771 /*isNullPtr*/true);
3772
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003773 case TemplateArgument::Template:
3774 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003775
3776 case TemplateArgument::TemplateExpansion:
3777 return TemplateArgument(getCanonicalTemplateName(
3778 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003779 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003780
Douglas Gregora8e02e72009-07-28 23:00:59 +00003781 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003782 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003783
Douglas Gregora8e02e72009-07-28 23:00:59 +00003784 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003785 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003786
Douglas Gregora8e02e72009-07-28 23:00:59 +00003787 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003788 if (Arg.pack_size() == 0)
3789 return Arg;
3790
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003791 TemplateArgument *CanonArgs
3792 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003793 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003794 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003795 AEnd = Arg.pack_end();
3796 A != AEnd; (void)++A, ++Idx)
3797 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003798
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003799 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003800 }
3801 }
3802
3803 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003804 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003805}
3806
Douglas Gregor333489b2009-03-27 23:10:48 +00003807NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003808ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003809 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003810 return 0;
3811
3812 switch (NNS->getKind()) {
3813 case NestedNameSpecifier::Identifier:
3814 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003815 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003816 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3817 NNS->getAsIdentifier());
3818
3819 case NestedNameSpecifier::Namespace:
3820 // A namespace is canonical; build a nested-name-specifier with
3821 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003822 return NestedNameSpecifier::Create(*this, 0,
3823 NNS->getAsNamespace()->getOriginalNamespace());
3824
3825 case NestedNameSpecifier::NamespaceAlias:
3826 // A namespace is canonical; build a nested-name-specifier with
3827 // this namespace and no prefix.
3828 return NestedNameSpecifier::Create(*this, 0,
3829 NNS->getAsNamespaceAlias()->getNamespace()
3830 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003831
3832 case NestedNameSpecifier::TypeSpec:
3833 case NestedNameSpecifier::TypeSpecWithTemplate: {
3834 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003835
3836 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3837 // break it apart into its prefix and identifier, then reconsititute those
3838 // as the canonical nested-name-specifier. This is required to canonicalize
3839 // a dependent nested-name-specifier involving typedefs of dependent-name
3840 // types, e.g.,
3841 // typedef typename T::type T1;
3842 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003843 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3844 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003845 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003846
Eli Friedman5358a0a2012-03-03 04:09:56 +00003847 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3848 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3849 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003850 return NestedNameSpecifier::Create(*this, 0, false,
3851 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003852 }
3853
3854 case NestedNameSpecifier::Global:
3855 // The global specifier is canonical and unique.
3856 return NNS;
3857 }
3858
David Blaikie8a40f702012-01-17 06:56:22 +00003859 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003860}
3861
Chris Lattner7adf0762008-08-04 07:31:14 +00003862
Jay Foad39c79802011-01-12 09:06:06 +00003863const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003864 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003865 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003866 // Handle the common positive case fast.
3867 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3868 return AT;
3869 }
Mike Stump11289f42009-09-09 15:08:12 +00003870
John McCall8ccfcb52009-09-24 19:53:00 +00003871 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003872 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003873 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003874
John McCall8ccfcb52009-09-24 19:53:00 +00003875 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003876 // implements C99 6.7.3p8: "If the specification of an array type includes
3877 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003878
Chris Lattner7adf0762008-08-04 07:31:14 +00003879 // If we get here, we either have type qualifiers on the type, or we have
3880 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003881 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003882
John McCall33ddac02011-01-19 10:06:00 +00003883 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003884 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003885
Chris Lattner7adf0762008-08-04 07:31:14 +00003886 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003887 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003888 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003889 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003890
Chris Lattner7adf0762008-08-04 07:31:14 +00003891 // Otherwise, we have an array and we have qualifiers on it. Push the
3892 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003893 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003894
Chris Lattner7adf0762008-08-04 07:31:14 +00003895 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3896 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3897 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003898 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003899 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3900 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3901 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003902 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003903
Mike Stump11289f42009-09-09 15:08:12 +00003904 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003905 = dyn_cast<DependentSizedArrayType>(ATy))
3906 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003907 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003908 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003909 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003910 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003911 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003912
Chris Lattner7adf0762008-08-04 07:31:14 +00003913 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003914 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003915 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003916 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003917 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003918 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003919}
3920
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003921QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003922 // C99 6.7.5.3p7:
3923 // A declaration of a parameter as "array of type" shall be
3924 // adjusted to "qualified pointer to type", where the type
3925 // qualifiers (if any) are those specified within the [ and ] of
3926 // the array type derivation.
3927 if (T->isArrayType())
3928 return getArrayDecayedType(T);
3929
3930 // C99 6.7.5.3p8:
3931 // A declaration of a parameter as "function returning type"
3932 // shall be adjusted to "pointer to function returning type", as
3933 // in 6.3.2.1.
3934 if (T->isFunctionType())
3935 return getPointerType(T);
3936
3937 return T;
3938}
3939
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003940QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003941 T = getVariableArrayDecayedType(T);
3942 T = getAdjustedParameterType(T);
3943 return T.getUnqualifiedType();
3944}
3945
Chris Lattnera21ad802008-04-02 05:18:44 +00003946/// getArrayDecayedType - Return the properly qualified result of decaying the
3947/// specified array type to a pointer. This operation is non-trivial when
3948/// handling typedefs etc. The canonical type of "T" must be an array type,
3949/// this returns a pointer to a properly qualified element of the array.
3950///
3951/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003952QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003953 // Get the element type with 'getAsArrayType' so that we don't lose any
3954 // typedefs in the element type of the array. This also handles propagation
3955 // of type qualifiers from the array type into the element type if present
3956 // (C99 6.7.3p8).
3957 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3958 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003959
Chris Lattner7adf0762008-08-04 07:31:14 +00003960 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003961
3962 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003963 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003964}
3965
John McCall33ddac02011-01-19 10:06:00 +00003966QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3967 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003968}
3969
John McCall33ddac02011-01-19 10:06:00 +00003970QualType ASTContext::getBaseElementType(QualType type) const {
3971 Qualifiers qs;
3972 while (true) {
3973 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003974 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003975 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003976
John McCall33ddac02011-01-19 10:06:00 +00003977 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003978 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003979 }
Mike Stump11289f42009-09-09 15:08:12 +00003980
John McCall33ddac02011-01-19 10:06:00 +00003981 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003982}
3983
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003984/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003985uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003986ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3987 uint64_t ElementCount = 1;
3988 do {
3989 ElementCount *= CA->getSize().getZExtValue();
3990 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3991 } while (CA);
3992 return ElementCount;
3993}
3994
Steve Naroff0af91202007-04-27 21:51:21 +00003995/// getFloatingRank - Return a relative rank for floating point types.
3996/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003997static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003998 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003999 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004000
John McCall9dd450b2009-09-21 23:43:11 +00004001 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4002 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004003 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004004 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004005 case BuiltinType::Float: return FloatRank;
4006 case BuiltinType::Double: return DoubleRank;
4007 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004008 }
4009}
4010
Mike Stump11289f42009-09-09 15:08:12 +00004011/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4012/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004013/// 'typeDomain' is a real floating point or complex type.
4014/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004015QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4016 QualType Domain) const {
4017 FloatingRank EltRank = getFloatingRank(Size);
4018 if (Domain->isComplexType()) {
4019 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004020 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004021 case FloatRank: return FloatComplexTy;
4022 case DoubleRank: return DoubleComplexTy;
4023 case LongDoubleRank: return LongDoubleComplexTy;
4024 }
Steve Naroff0af91202007-04-27 21:51:21 +00004025 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004026
4027 assert(Domain->isRealFloatingType() && "Unknown domain!");
4028 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004029 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004030 case FloatRank: return FloatTy;
4031 case DoubleRank: return DoubleTy;
4032 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004033 }
David Blaikief47fa302012-01-17 02:30:50 +00004034 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004035}
4036
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004037/// getFloatingTypeOrder - Compare the rank of the two specified floating
4038/// point types, ignoring the domain of the type (i.e. 'double' ==
4039/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004040/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004041int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004042 FloatingRank LHSR = getFloatingRank(LHS);
4043 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004044
Chris Lattnerb90739d2008-04-06 23:38:49 +00004045 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004046 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004047 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004048 return 1;
4049 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004050}
4051
Chris Lattner76a00cf2008-04-06 22:59:24 +00004052/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4053/// routine will assert if passed a built-in type that isn't an integer or enum,
4054/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004055unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004056 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004057
Chris Lattner76a00cf2008-04-06 22:59:24 +00004058 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004059 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004060 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004061 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004062 case BuiltinType::Char_S:
4063 case BuiltinType::Char_U:
4064 case BuiltinType::SChar:
4065 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004066 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004067 case BuiltinType::Short:
4068 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004069 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004070 case BuiltinType::Int:
4071 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004072 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004073 case BuiltinType::Long:
4074 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004075 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004076 case BuiltinType::LongLong:
4077 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004078 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004079 case BuiltinType::Int128:
4080 case BuiltinType::UInt128:
4081 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004082 }
4083}
4084
Eli Friedman629ffb92009-08-20 04:21:42 +00004085/// \brief Whether this is a promotable bitfield reference according
4086/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4087///
4088/// \returns the type this bit-field will promote to, or NULL if no
4089/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004090QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004091 if (E->isTypeDependent() || E->isValueDependent())
4092 return QualType();
4093
Eli Friedman629ffb92009-08-20 04:21:42 +00004094 FieldDecl *Field = E->getBitField();
4095 if (!Field)
4096 return QualType();
4097
4098 QualType FT = Field->getType();
4099
Richard Smithcaf33902011-10-10 18:28:20 +00004100 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004101 uint64_t IntSize = getTypeSize(IntTy);
4102 // GCC extension compatibility: if the bit-field size is less than or equal
4103 // to the size of int, it gets promoted no matter what its type is.
4104 // For instance, unsigned long bf : 4 gets promoted to signed int.
4105 if (BitWidth < IntSize)
4106 return IntTy;
4107
4108 if (BitWidth == IntSize)
4109 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4110
4111 // Types bigger than int are not subject to promotions, and therefore act
4112 // like the base type.
4113 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4114 // is ridiculous.
4115 return QualType();
4116}
4117
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004118/// getPromotedIntegerType - Returns the type that Promotable will
4119/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4120/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004121QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004122 assert(!Promotable.isNull());
4123 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004124 if (const EnumType *ET = Promotable->getAs<EnumType>())
4125 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004126
4127 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4128 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4129 // (3.9.1) can be converted to a prvalue of the first of the following
4130 // types that can represent all the values of its underlying type:
4131 // int, unsigned int, long int, unsigned long int, long long int, or
4132 // unsigned long long int [...]
4133 // FIXME: Is there some better way to compute this?
4134 if (BT->getKind() == BuiltinType::WChar_S ||
4135 BT->getKind() == BuiltinType::WChar_U ||
4136 BT->getKind() == BuiltinType::Char16 ||
4137 BT->getKind() == BuiltinType::Char32) {
4138 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4139 uint64_t FromSize = getTypeSize(BT);
4140 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4141 LongLongTy, UnsignedLongLongTy };
4142 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4143 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4144 if (FromSize < ToSize ||
4145 (FromSize == ToSize &&
4146 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4147 return PromoteTypes[Idx];
4148 }
4149 llvm_unreachable("char type should fit into long long");
4150 }
4151 }
4152
4153 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004154 if (Promotable->isSignedIntegerType())
4155 return IntTy;
4156 uint64_t PromotableSize = getTypeSize(Promotable);
4157 uint64_t IntSize = getTypeSize(IntTy);
4158 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4159 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4160}
4161
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004162/// \brief Recurses in pointer/array types until it finds an objc retainable
4163/// type and returns its ownership.
4164Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4165 while (!T.isNull()) {
4166 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4167 return T.getObjCLifetime();
4168 if (T->isArrayType())
4169 T = getBaseElementType(T);
4170 else if (const PointerType *PT = T->getAs<PointerType>())
4171 T = PT->getPointeeType();
4172 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004173 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004174 else
4175 break;
4176 }
4177
4178 return Qualifiers::OCL_None;
4179}
4180
Mike Stump11289f42009-09-09 15:08:12 +00004181/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004182/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004183/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004184int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004185 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4186 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004187 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004188
Chris Lattner76a00cf2008-04-06 22:59:24 +00004189 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4190 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004191
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004192 unsigned LHSRank = getIntegerRank(LHSC);
4193 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004194
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004195 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4196 if (LHSRank == RHSRank) return 0;
4197 return LHSRank > RHSRank ? 1 : -1;
4198 }
Mike Stump11289f42009-09-09 15:08:12 +00004199
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004200 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4201 if (LHSUnsigned) {
4202 // If the unsigned [LHS] type is larger, return it.
4203 if (LHSRank >= RHSRank)
4204 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004205
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004206 // If the signed type can represent all values of the unsigned type, it
4207 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004208 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004209 return -1;
4210 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004211
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004212 // If the unsigned [RHS] type is larger, return it.
4213 if (RHSRank >= LHSRank)
4214 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004215
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004216 // If the signed type can represent all values of the unsigned type, it
4217 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004218 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004219 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004220}
Anders Carlsson98f07902007-08-17 05:31:46 +00004221
Anders Carlsson6d417272009-11-14 21:45:58 +00004222static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004223CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4224 DeclContext *DC, IdentifierInfo *Id) {
4225 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004226 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004227 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004228 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004229 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004230}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004231
Mike Stump11289f42009-09-09 15:08:12 +00004232// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004233QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004234 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004235 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004236 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004237 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004238 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004239
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004240 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004241
Anders Carlsson98f07902007-08-17 05:31:46 +00004242 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004243 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004244 // int flags;
4245 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004246 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004247 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004248 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004249 FieldTypes[3] = LongTy;
4250
Anders Carlsson98f07902007-08-17 05:31:46 +00004251 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004252 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004253 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004254 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004255 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004256 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004257 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004258 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004259 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004260 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004261 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004262 }
4263
Douglas Gregord5058122010-02-11 01:19:42 +00004264 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004265 }
Mike Stump11289f42009-09-09 15:08:12 +00004266
Anders Carlsson98f07902007-08-17 05:31:46 +00004267 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004268}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004269
Douglas Gregor512b0772009-04-23 22:29:11 +00004270void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004271 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004272 assert(Rec && "Invalid CFConstantStringType");
4273 CFConstantStringTypeDecl = Rec->getDecl();
4274}
4275
Jay Foad39c79802011-01-12 09:06:06 +00004276QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004277 if (BlockDescriptorType)
4278 return getTagDeclType(BlockDescriptorType);
4279
4280 RecordDecl *T;
4281 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004282 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004283 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004284 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004285
4286 QualType FieldTypes[] = {
4287 UnsignedLongTy,
4288 UnsignedLongTy,
4289 };
4290
4291 const char *FieldNames[] = {
4292 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004293 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004294 };
4295
4296 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004297 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004298 SourceLocation(),
4299 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004300 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004301 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004302 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004303 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004304 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004305 T->addDecl(Field);
4306 }
4307
Douglas Gregord5058122010-02-11 01:19:42 +00004308 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004309
4310 BlockDescriptorType = T;
4311
4312 return getTagDeclType(BlockDescriptorType);
4313}
4314
Jay Foad39c79802011-01-12 09:06:06 +00004315QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004316 if (BlockDescriptorExtendedType)
4317 return getTagDeclType(BlockDescriptorExtendedType);
4318
4319 RecordDecl *T;
4320 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004321 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004322 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004323 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004324
4325 QualType FieldTypes[] = {
4326 UnsignedLongTy,
4327 UnsignedLongTy,
4328 getPointerType(VoidPtrTy),
4329 getPointerType(VoidPtrTy)
4330 };
4331
4332 const char *FieldNames[] = {
4333 "reserved",
4334 "Size",
4335 "CopyFuncPtr",
4336 "DestroyFuncPtr"
4337 };
4338
4339 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004340 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004341 SourceLocation(),
4342 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004343 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004344 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004345 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004346 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004347 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004348 T->addDecl(Field);
4349 }
4350
Douglas Gregord5058122010-02-11 01:19:42 +00004351 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004352
4353 BlockDescriptorExtendedType = T;
4354
4355 return getTagDeclType(BlockDescriptorExtendedType);
4356}
4357
Jay Foad39c79802011-01-12 09:06:06 +00004358bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004359 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004360 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004361 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004362 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4363 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004364 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004365
4366 }
4367 }
Mike Stump94967902009-10-21 18:16:27 +00004368 return false;
4369}
4370
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004371bool ASTContext::getByrefLifetime(QualType Ty,
4372 Qualifiers::ObjCLifetime &LifeTime,
4373 bool &HasByrefExtendedLayout) const {
4374
4375 if (!getLangOpts().ObjC1 ||
4376 getLangOpts().getGC() != LangOptions::NonGC)
4377 return false;
4378
4379 HasByrefExtendedLayout = false;
4380 if (Ty->isAggregateType()) {
4381 HasByrefExtendedLayout = true;
4382 LifeTime = Qualifiers::OCL_None;
4383 }
4384 else if (getLangOpts().ObjCAutoRefCount)
4385 LifeTime = Ty.getObjCLifetime();
4386 // MRR.
4387 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4388 LifeTime = Qualifiers::OCL_ExplicitNone;
4389 else
4390 LifeTime = Qualifiers::OCL_None;
4391 return true;
4392}
4393
Jay Foad39c79802011-01-12 09:06:06 +00004394QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004395ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004396 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004397 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004398 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004399 // unsigned int __flags;
4400 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004401 // void *__copy_helper; // as needed
4402 // void *__destroy_help // as needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004403 // void *__byref_variable_layout; // Extended layout info. for byref variable as needed
Mike Stump94967902009-10-21 18:16:27 +00004404 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004405 // } *
4406
Mike Stump94967902009-10-21 18:16:27 +00004407 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004408 bool HasByrefExtendedLayout;
4409 Qualifiers::ObjCLifetime Lifetime;
Mike Stump94967902009-10-21 18:16:27 +00004410
4411 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004412 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004413 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4414 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004415 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004416 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004417 T->startDefinition();
4418 QualType Int32Ty = IntTy;
4419 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4420 QualType FieldTypes[] = {
4421 getPointerType(VoidPtrTy),
4422 getPointerType(getTagDeclType(T)),
4423 Int32Ty,
4424 Int32Ty,
4425 getPointerType(VoidPtrTy),
4426 getPointerType(VoidPtrTy),
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004427 getPointerType(VoidPtrTy),
Mike Stump94967902009-10-21 18:16:27 +00004428 Ty
4429 };
4430
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004431 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004432 "__isa",
4433 "__forwarding",
4434 "__flags",
4435 "__size",
4436 "__copy_helper",
4437 "__destroy_helper",
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004438 "__byref_variable_layout",
Mike Stump94967902009-10-21 18:16:27 +00004439 DeclName,
4440 };
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004441 bool ByrefKnownLifetime = getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout);
4442 for (size_t i = 0; i < 8; ++i) {
Mike Stump94967902009-10-21 18:16:27 +00004443 if (!HasCopyAndDispose && i >=4 && i <= 5)
4444 continue;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004445 if ((!ByrefKnownLifetime || !HasByrefExtendedLayout) && i == 6)
4446 continue;
Mike Stump94967902009-10-21 18:16:27 +00004447 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004448 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004449 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004450 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004451 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004452 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004453 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004454 T->addDecl(Field);
4455 }
4456
Douglas Gregord5058122010-02-11 01:19:42 +00004457 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004458
4459 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004460}
4461
Douglas Gregorbab8a962011-09-08 01:46:34 +00004462TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4463 if (!ObjCInstanceTypeDecl)
4464 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4465 getTranslationUnitDecl(),
4466 SourceLocation(),
4467 SourceLocation(),
4468 &Idents.get("instancetype"),
4469 getTrivialTypeSourceInfo(getObjCIdType()));
4470 return ObjCInstanceTypeDecl;
4471}
4472
Anders Carlsson18acd442007-10-29 06:33:42 +00004473// This returns true if a type has been typedefed to BOOL:
4474// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004475static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004476 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004477 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4478 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004479
Anders Carlssond8499822007-10-29 05:01:08 +00004480 return false;
4481}
4482
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004483/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004484/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004485CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004486 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4487 return CharUnits::Zero();
4488
Ken Dyck40775002010-01-11 17:06:35 +00004489 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004490
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004491 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004492 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004493 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004494 // Treat arrays as pointers, since that's how they're passed in.
4495 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004496 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004497 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004498}
4499
4500static inline
4501std::string charUnitsToString(const CharUnits &CU) {
4502 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004503}
4504
John McCall351762c2011-02-07 10:33:21 +00004505/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004506/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004507std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4508 std::string S;
4509
David Chisnall950a9512009-11-17 19:33:30 +00004510 const BlockDecl *Decl = Expr->getBlockDecl();
4511 QualType BlockTy =
4512 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4513 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004514 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004515 // Compute size of all parameters.
4516 // Start with computing size of a pointer in number of bytes.
4517 // FIXME: There might(should) be a better way of doing this computation!
4518 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004519 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4520 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004521 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004522 E = Decl->param_end(); PI != E; ++PI) {
4523 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004524 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004525 if (sz.isZero())
4526 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004527 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004528 ParmOffset += sz;
4529 }
4530 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004531 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004532 // Block pointer and offset.
4533 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004534
4535 // Argument types.
4536 ParmOffset = PtrSize;
4537 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4538 Decl->param_end(); PI != E; ++PI) {
4539 ParmVarDecl *PVDecl = *PI;
4540 QualType PType = PVDecl->getOriginalType();
4541 if (const ArrayType *AT =
4542 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4543 // Use array's original type only if it has known number of
4544 // elements.
4545 if (!isa<ConstantArrayType>(AT))
4546 PType = PVDecl->getType();
4547 } else if (PType->isFunctionType())
4548 PType = PVDecl->getType();
4549 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004550 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004551 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004552 }
John McCall351762c2011-02-07 10:33:21 +00004553
4554 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004555}
4556
Douglas Gregora9d84932011-05-27 01:19:52 +00004557bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004558 std::string& S) {
4559 // Encode result type.
4560 getObjCEncodingForType(Decl->getResultType(), S);
4561 CharUnits ParmOffset;
4562 // Compute size of all parameters.
4563 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4564 E = Decl->param_end(); PI != E; ++PI) {
4565 QualType PType = (*PI)->getType();
4566 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004567 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004568 continue;
4569
David Chisnall50e4eba2010-12-30 14:05:53 +00004570 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004571 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004572 ParmOffset += sz;
4573 }
4574 S += charUnitsToString(ParmOffset);
4575 ParmOffset = CharUnits::Zero();
4576
4577 // Argument types.
4578 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4579 E = Decl->param_end(); PI != E; ++PI) {
4580 ParmVarDecl *PVDecl = *PI;
4581 QualType PType = PVDecl->getOriginalType();
4582 if (const ArrayType *AT =
4583 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4584 // Use array's original type only if it has known number of
4585 // elements.
4586 if (!isa<ConstantArrayType>(AT))
4587 PType = PVDecl->getType();
4588 } else if (PType->isFunctionType())
4589 PType = PVDecl->getType();
4590 getObjCEncodingForType(PType, S);
4591 S += charUnitsToString(ParmOffset);
4592 ParmOffset += getObjCEncodingTypeSize(PType);
4593 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004594
4595 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004596}
4597
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004598/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4599/// method parameter or return type. If Extended, include class names and
4600/// block object types.
4601void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4602 QualType T, std::string& S,
4603 bool Extended) const {
4604 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4605 getObjCEncodingForTypeQualifier(QT, S);
4606 // Encode parameter type.
4607 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4608 true /*OutermostType*/,
4609 false /*EncodingProperty*/,
4610 false /*StructField*/,
4611 Extended /*EncodeBlockParameters*/,
4612 Extended /*EncodeClassNames*/);
4613}
4614
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004615/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004616/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004617bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004618 std::string& S,
4619 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004620 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004621 // Encode return type.
4622 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4623 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004624 // Compute size of all parameters.
4625 // Start with computing size of a pointer in number of bytes.
4626 // FIXME: There might(should) be a better way of doing this computation!
4627 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004628 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004629 // The first two arguments (self and _cmd) are pointers; account for
4630 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004631 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004632 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004633 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004634 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004635 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004636 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004637 continue;
4638
Ken Dyck40775002010-01-11 17:06:35 +00004639 assert (sz.isPositive() &&
4640 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004641 ParmOffset += sz;
4642 }
Ken Dyck40775002010-01-11 17:06:35 +00004643 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004644 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004645 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004646
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004647 // Argument types.
4648 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004649 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004650 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004651 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004652 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004653 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004654 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4655 // Use array's original type only if it has known number of
4656 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004657 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004658 PType = PVDecl->getType();
4659 } else if (PType->isFunctionType())
4660 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004661 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4662 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004663 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004664 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004665 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004666
4667 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004668}
4669
Daniel Dunbar4932b362008-08-28 04:38:10 +00004670/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004671/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004672/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4673/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004674/// Property attributes are stored as a comma-delimited C string. The simple
4675/// attributes readonly and bycopy are encoded as single characters. The
4676/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4677/// encoded as single characters, followed by an identifier. Property types
4678/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004679/// these attributes are defined by the following enumeration:
4680/// @code
4681/// enum PropertyAttributes {
4682/// kPropertyReadOnly = 'R', // property is read-only.
4683/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4684/// kPropertyByref = '&', // property is a reference to the value last assigned
4685/// kPropertyDynamic = 'D', // property is dynamic
4686/// kPropertyGetter = 'G', // followed by getter selector name
4687/// kPropertySetter = 'S', // followed by setter selector name
4688/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004689/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004690/// kPropertyWeak = 'W' // 'weak' property
4691/// kPropertyStrong = 'P' // property GC'able
4692/// kPropertyNonAtomic = 'N' // property non-atomic
4693/// };
4694/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004695void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004696 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004697 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004698 // Collect information from the property implementation decl(s).
4699 bool Dynamic = false;
4700 ObjCPropertyImplDecl *SynthesizePID = 0;
4701
4702 // FIXME: Duplicated code due to poor abstraction.
4703 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004704 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004705 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4706 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004707 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004708 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004709 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004710 if (PID->getPropertyDecl() == PD) {
4711 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4712 Dynamic = true;
4713 } else {
4714 SynthesizePID = PID;
4715 }
4716 }
4717 }
4718 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004719 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004720 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004721 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004722 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004723 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004724 if (PID->getPropertyDecl() == PD) {
4725 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4726 Dynamic = true;
4727 } else {
4728 SynthesizePID = PID;
4729 }
4730 }
Mike Stump11289f42009-09-09 15:08:12 +00004731 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004732 }
4733 }
4734
4735 // FIXME: This is not very efficient.
4736 S = "T";
4737
4738 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004739 // GCC has some special rules regarding encoding of properties which
4740 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004741 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004742 true /* outermost type */,
4743 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004744
4745 if (PD->isReadOnly()) {
4746 S += ",R";
4747 } else {
4748 switch (PD->getSetterKind()) {
4749 case ObjCPropertyDecl::Assign: break;
4750 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004751 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004752 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004753 }
4754 }
4755
4756 // It really isn't clear at all what this means, since properties
4757 // are "dynamic by default".
4758 if (Dynamic)
4759 S += ",D";
4760
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004761 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4762 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004763
Daniel Dunbar4932b362008-08-28 04:38:10 +00004764 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4765 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004766 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004767 }
4768
4769 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4770 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004771 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004772 }
4773
4774 if (SynthesizePID) {
4775 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4776 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004777 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004778 }
4779
4780 // FIXME: OBJCGC: weak & strong
4781}
4782
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004783/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004784/// Another legacy compatibility encoding: 32-bit longs are encoded as
4785/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004786/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4787///
4788void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004789 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004790 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004791 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004792 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004793 else
Jay Foad39c79802011-01-12 09:06:06 +00004794 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004795 PointeeTy = IntTy;
4796 }
4797 }
4798}
4799
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004800void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004801 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004802 // We follow the behavior of gcc, expanding structures which are
4803 // directly pointed to, and expanding embedded structures. Note that
4804 // these rules are sufficient to prevent recursive encoding of the
4805 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004806 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004807 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004808}
4809
David Chisnallb190a2c2010-06-04 01:10:52 +00004810static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4811 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004812 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004813 case BuiltinType::Void: return 'v';
4814 case BuiltinType::Bool: return 'B';
4815 case BuiltinType::Char_U:
4816 case BuiltinType::UChar: return 'C';
4817 case BuiltinType::UShort: return 'S';
4818 case BuiltinType::UInt: return 'I';
4819 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004820 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004821 case BuiltinType::UInt128: return 'T';
4822 case BuiltinType::ULongLong: return 'Q';
4823 case BuiltinType::Char_S:
4824 case BuiltinType::SChar: return 'c';
4825 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004826 case BuiltinType::WChar_S:
4827 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004828 case BuiltinType::Int: return 'i';
4829 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004830 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004831 case BuiltinType::LongLong: return 'q';
4832 case BuiltinType::Int128: return 't';
4833 case BuiltinType::Float: return 'f';
4834 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004835 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004836 }
4837}
4838
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004839static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4840 EnumDecl *Enum = ET->getDecl();
4841
4842 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4843 if (!Enum->isFixed())
4844 return 'i';
4845
4846 // The encoding of a fixed enum type matches its fixed underlying type.
4847 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4848}
4849
Jay Foad39c79802011-01-12 09:06:06 +00004850static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004851 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004852 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004853 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004854 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4855 // The GNU runtime requires more information; bitfields are encoded as b,
4856 // then the offset (in bits) of the first element, then the type of the
4857 // bitfield, then the size in bits. For example, in this structure:
4858 //
4859 // struct
4860 // {
4861 // int integer;
4862 // int flags:2;
4863 // };
4864 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4865 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4866 // information is not especially sensible, but we're stuck with it for
4867 // compatibility with GCC, although providing it breaks anything that
4868 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004869 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004870 const RecordDecl *RD = FD->getParent();
4871 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004872 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004873 if (const EnumType *ET = T->getAs<EnumType>())
4874 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004875 else
Jay Foad39c79802011-01-12 09:06:06 +00004876 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004877 }
Richard Smithcaf33902011-10-10 18:28:20 +00004878 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004879}
4880
Daniel Dunbar07d07852009-10-18 21:17:35 +00004881// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004882void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4883 bool ExpandPointedToStructures,
4884 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004885 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004886 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004887 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004888 bool StructField,
4889 bool EncodeBlockParameters,
4890 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004891 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004892 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004893 return EncodeBitField(this, S, T, FD);
4894 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004895 return;
4896 }
Mike Stump11289f42009-09-09 15:08:12 +00004897
John McCall9dd450b2009-09-21 23:43:11 +00004898 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004899 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004900 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004901 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004902 return;
4903 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004904
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004905 // encoding for pointer or r3eference types.
4906 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004907 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004908 if (PT->isObjCSelType()) {
4909 S += ':';
4910 return;
4911 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004912 PointeeTy = PT->getPointeeType();
4913 }
4914 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4915 PointeeTy = RT->getPointeeType();
4916 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004917 bool isReadOnly = false;
4918 // For historical/compatibility reasons, the read-only qualifier of the
4919 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4920 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004921 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004922 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004923 if (OutermostType && T.isConstQualified()) {
4924 isReadOnly = true;
4925 S += 'r';
4926 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004927 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004928 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004929 while (P->getAs<PointerType>())
4930 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004931 if (P.isConstQualified()) {
4932 isReadOnly = true;
4933 S += 'r';
4934 }
4935 }
4936 if (isReadOnly) {
4937 // Another legacy compatibility encoding. Some ObjC qualifier and type
4938 // combinations need to be rearranged.
4939 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004940 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004941 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004942 }
Mike Stump11289f42009-09-09 15:08:12 +00004943
Anders Carlssond8499822007-10-29 05:01:08 +00004944 if (PointeeTy->isCharType()) {
4945 // char pointer types should be encoded as '*' unless it is a
4946 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004947 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004948 S += '*';
4949 return;
4950 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004951 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004952 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4953 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4954 S += '#';
4955 return;
4956 }
4957 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4958 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4959 S += '@';
4960 return;
4961 }
4962 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004963 }
Anders Carlssond8499822007-10-29 05:01:08 +00004964 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004965 getLegacyIntegralTypeEncoding(PointeeTy);
4966
Mike Stump11289f42009-09-09 15:08:12 +00004967 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004968 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004969 return;
4970 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004971
Chris Lattnere7cabb92009-07-13 00:10:46 +00004972 if (const ArrayType *AT =
4973 // Ignore type qualifiers etc.
4974 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004975 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004976 // Incomplete arrays are encoded as a pointer to the array element.
4977 S += '^';
4978
Mike Stump11289f42009-09-09 15:08:12 +00004979 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004980 false, ExpandStructures, FD);
4981 } else {
4982 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004983
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004984 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4985 if (getTypeSize(CAT->getElementType()) == 0)
4986 S += '0';
4987 else
4988 S += llvm::utostr(CAT->getSize().getZExtValue());
4989 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004990 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004991 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4992 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004993 S += '0';
4994 }
Mike Stump11289f42009-09-09 15:08:12 +00004995
4996 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004997 false, ExpandStructures, FD);
4998 S += ']';
4999 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005000 return;
5001 }
Mike Stump11289f42009-09-09 15:08:12 +00005002
John McCall9dd450b2009-09-21 23:43:11 +00005003 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00005004 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005005 return;
5006 }
Mike Stump11289f42009-09-09 15:08:12 +00005007
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005008 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005009 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005010 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005011 // Anonymous structures print as '?'
5012 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5013 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005014 if (ClassTemplateSpecializationDecl *Spec
5015 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5016 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5017 std::string TemplateArgsStr
5018 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005019 TemplateArgs.data(),
5020 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005021 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005022
5023 S += TemplateArgsStr;
5024 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005025 } else {
5026 S += '?';
5027 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005028 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005029 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005030 if (!RDecl->isUnion()) {
5031 getObjCEncodingForStructureImpl(RDecl, S, FD);
5032 } else {
5033 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5034 FieldEnd = RDecl->field_end();
5035 Field != FieldEnd; ++Field) {
5036 if (FD) {
5037 S += '"';
5038 S += Field->getNameAsString();
5039 S += '"';
5040 }
Mike Stump11289f42009-09-09 15:08:12 +00005041
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005042 // Special case bit-fields.
5043 if (Field->isBitField()) {
5044 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005045 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005046 } else {
5047 QualType qt = Field->getType();
5048 getLegacyIntegralTypeEncoding(qt);
5049 getObjCEncodingForTypeImpl(qt, S, false, true,
5050 FD, /*OutermostType*/false,
5051 /*EncodingProperty*/false,
5052 /*StructField*/true);
5053 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005054 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005055 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005056 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005057 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005058 return;
5059 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005060
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005061 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005062 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005063 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005064 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005065 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005066 return;
5067 }
Mike Stump11289f42009-09-09 15:08:12 +00005068
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005069 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00005070 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005071 if (EncodeBlockParameters) {
5072 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
5073
5074 S += '<';
5075 // Block return type
5076 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5077 ExpandPointedToStructures, ExpandStructures,
5078 FD,
5079 false /* OutermostType */,
5080 EncodingProperty,
5081 false /* StructField */,
5082 EncodeBlockParameters,
5083 EncodeClassNames);
5084 // Block self
5085 S += "@?";
5086 // Block parameters
5087 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5088 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5089 E = FPT->arg_type_end(); I && (I != E); ++I) {
5090 getObjCEncodingForTypeImpl(*I, S,
5091 ExpandPointedToStructures,
5092 ExpandStructures,
5093 FD,
5094 false /* OutermostType */,
5095 EncodingProperty,
5096 false /* StructField */,
5097 EncodeBlockParameters,
5098 EncodeClassNames);
5099 }
5100 }
5101 S += '>';
5102 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005103 return;
5104 }
Mike Stump11289f42009-09-09 15:08:12 +00005105
John McCall8b07ec22010-05-15 11:32:37 +00005106 // Ignore protocol qualifiers when mangling at this level.
5107 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
5108 T = OT->getBaseType();
5109
John McCall8ccfcb52009-09-24 19:53:00 +00005110 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005111 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005112 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005113 S += '{';
5114 const IdentifierInfo *II = OI->getIdentifier();
5115 S += II->getName();
5116 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005117 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005118 DeepCollectObjCIvars(OI, true, Ivars);
5119 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005120 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005121 if (Field->isBitField())
5122 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005123 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005124 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005125 }
5126 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005127 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005128 }
Mike Stump11289f42009-09-09 15:08:12 +00005129
John McCall9dd450b2009-09-21 23:43:11 +00005130 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005131 if (OPT->isObjCIdType()) {
5132 S += '@';
5133 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005134 }
Mike Stump11289f42009-09-09 15:08:12 +00005135
Steve Narofff0c86112009-10-28 22:03:49 +00005136 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5137 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5138 // Since this is a binary compatibility issue, need to consult with runtime
5139 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005140 S += '#';
5141 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005142 }
Mike Stump11289f42009-09-09 15:08:12 +00005143
Chris Lattnere7cabb92009-07-13 00:10:46 +00005144 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005145 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005146 ExpandPointedToStructures,
5147 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005148 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005149 // Note that we do extended encoding of protocol qualifer list
5150 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005151 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005152 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5153 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005154 S += '<';
5155 S += (*I)->getNameAsString();
5156 S += '>';
5157 }
5158 S += '"';
5159 }
5160 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005161 }
Mike Stump11289f42009-09-09 15:08:12 +00005162
Chris Lattnere7cabb92009-07-13 00:10:46 +00005163 QualType PointeeTy = OPT->getPointeeType();
5164 if (!EncodingProperty &&
5165 isa<TypedefType>(PointeeTy.getTypePtr())) {
5166 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005167 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005168 // {...};
5169 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005170 getObjCEncodingForTypeImpl(PointeeTy, S,
5171 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00005172 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005173 return;
5174 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005175
5176 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005177 if (OPT->getInterfaceDecl() &&
5178 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005179 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005180 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005181 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5182 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005183 S += '<';
5184 S += (*I)->getNameAsString();
5185 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005186 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005187 S += '"';
5188 }
5189 return;
5190 }
Mike Stump11289f42009-09-09 15:08:12 +00005191
John McCalla9e6e8d2010-05-17 23:56:34 +00005192 // gcc just blithely ignores member pointers.
5193 // TODO: maybe there should be a mangling for these
5194 if (T->getAs<MemberPointerType>())
5195 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005196
5197 if (T->isVectorType()) {
5198 // This matches gcc's encoding, even though technically it is
5199 // insufficient.
5200 // FIXME. We should do a better job than gcc.
5201 return;
5202 }
5203
David Blaikie83d382b2011-09-23 05:06:16 +00005204 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00005205}
5206
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005207void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5208 std::string &S,
5209 const FieldDecl *FD,
5210 bool includeVBases) const {
5211 assert(RDecl && "Expected non-null RecordDecl");
5212 assert(!RDecl->isUnion() && "Should not be called for unions");
5213 if (!RDecl->getDefinition())
5214 return;
5215
5216 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5217 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5218 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5219
5220 if (CXXRec) {
5221 for (CXXRecordDecl::base_class_iterator
5222 BI = CXXRec->bases_begin(),
5223 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5224 if (!BI->isVirtual()) {
5225 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005226 if (base->isEmpty())
5227 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005228 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005229 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5230 std::make_pair(offs, base));
5231 }
5232 }
5233 }
5234
5235 unsigned i = 0;
5236 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5237 FieldEnd = RDecl->field_end();
5238 Field != FieldEnd; ++Field, ++i) {
5239 uint64_t offs = layout.getFieldOffset(i);
5240 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005241 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005242 }
5243
5244 if (CXXRec && includeVBases) {
5245 for (CXXRecordDecl::base_class_iterator
5246 BI = CXXRec->vbases_begin(),
5247 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5248 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005249 if (base->isEmpty())
5250 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005251 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005252 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5253 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5254 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005255 }
5256 }
5257
5258 CharUnits size;
5259 if (CXXRec) {
5260 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5261 } else {
5262 size = layout.getSize();
5263 }
5264
5265 uint64_t CurOffs = 0;
5266 std::multimap<uint64_t, NamedDecl *>::iterator
5267 CurLayObj = FieldOrBaseOffsets.begin();
5268
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005269 if (CXXRec && CXXRec->isDynamicClass() &&
5270 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005271 if (FD) {
5272 S += "\"_vptr$";
5273 std::string recname = CXXRec->getNameAsString();
5274 if (recname.empty()) recname = "?";
5275 S += recname;
5276 S += '"';
5277 }
5278 S += "^^?";
5279 CurOffs += getTypeSize(VoidPtrTy);
5280 }
5281
5282 if (!RDecl->hasFlexibleArrayMember()) {
5283 // Mark the end of the structure.
5284 uint64_t offs = toBits(size);
5285 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5286 std::make_pair(offs, (NamedDecl*)0));
5287 }
5288
5289 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5290 assert(CurOffs <= CurLayObj->first);
5291
5292 if (CurOffs < CurLayObj->first) {
5293 uint64_t padding = CurLayObj->first - CurOffs;
5294 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5295 // packing/alignment of members is different that normal, in which case
5296 // the encoding will be out-of-sync with the real layout.
5297 // If the runtime switches to just consider the size of types without
5298 // taking into account alignment, we could make padding explicit in the
5299 // encoding (e.g. using arrays of chars). The encoding strings would be
5300 // longer then though.
5301 CurOffs += padding;
5302 }
5303
5304 NamedDecl *dcl = CurLayObj->second;
5305 if (dcl == 0)
5306 break; // reached end of structure.
5307
5308 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5309 // We expand the bases without their virtual bases since those are going
5310 // in the initial structure. Note that this differs from gcc which
5311 // expands virtual bases each time one is encountered in the hierarchy,
5312 // making the encoding type bigger than it really is.
5313 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005314 assert(!base->isEmpty());
5315 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005316 } else {
5317 FieldDecl *field = cast<FieldDecl>(dcl);
5318 if (FD) {
5319 S += '"';
5320 S += field->getNameAsString();
5321 S += '"';
5322 }
5323
5324 if (field->isBitField()) {
5325 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005326 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005327 } else {
5328 QualType qt = field->getType();
5329 getLegacyIntegralTypeEncoding(qt);
5330 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5331 /*OutermostType*/false,
5332 /*EncodingProperty*/false,
5333 /*StructField*/true);
5334 CurOffs += getTypeSize(field->getType());
5335 }
5336 }
5337 }
5338}
5339
Mike Stump11289f42009-09-09 15:08:12 +00005340void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005341 std::string& S) const {
5342 if (QT & Decl::OBJC_TQ_In)
5343 S += 'n';
5344 if (QT & Decl::OBJC_TQ_Inout)
5345 S += 'N';
5346 if (QT & Decl::OBJC_TQ_Out)
5347 S += 'o';
5348 if (QT & Decl::OBJC_TQ_Bycopy)
5349 S += 'O';
5350 if (QT & Decl::OBJC_TQ_Byref)
5351 S += 'R';
5352 if (QT & Decl::OBJC_TQ_Oneway)
5353 S += 'V';
5354}
5355
Douglas Gregor3ea72692011-08-12 05:46:01 +00005356TypedefDecl *ASTContext::getObjCIdDecl() const {
5357 if (!ObjCIdDecl) {
5358 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5359 T = getObjCObjectPointerType(T);
5360 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5361 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5362 getTranslationUnitDecl(),
5363 SourceLocation(), SourceLocation(),
5364 &Idents.get("id"), IdInfo);
5365 }
5366
5367 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005368}
5369
Douglas Gregor52e02802011-08-12 06:17:30 +00005370TypedefDecl *ASTContext::getObjCSelDecl() const {
5371 if (!ObjCSelDecl) {
5372 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5373 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5374 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5375 getTranslationUnitDecl(),
5376 SourceLocation(), SourceLocation(),
5377 &Idents.get("SEL"), SelInfo);
5378 }
5379 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005380}
5381
Douglas Gregor0a586182011-08-12 05:59:41 +00005382TypedefDecl *ASTContext::getObjCClassDecl() const {
5383 if (!ObjCClassDecl) {
5384 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5385 T = getObjCObjectPointerType(T);
5386 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5387 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5388 getTranslationUnitDecl(),
5389 SourceLocation(), SourceLocation(),
5390 &Idents.get("Class"), ClassInfo);
5391 }
5392
5393 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005394}
5395
Douglas Gregord53ae832012-01-17 18:09:05 +00005396ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5397 if (!ObjCProtocolClassDecl) {
5398 ObjCProtocolClassDecl
5399 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5400 SourceLocation(),
5401 &Idents.get("Protocol"),
5402 /*PrevDecl=*/0,
5403 SourceLocation(), true);
5404 }
5405
5406 return ObjCProtocolClassDecl;
5407}
5408
Meador Inge5d3fb222012-06-16 03:34:49 +00005409//===----------------------------------------------------------------------===//
5410// __builtin_va_list Construction Functions
5411//===----------------------------------------------------------------------===//
5412
5413static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5414 // typedef char* __builtin_va_list;
5415 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5416 TypeSourceInfo *TInfo
5417 = Context->getTrivialTypeSourceInfo(CharPtrType);
5418
5419 TypedefDecl *VaListTypeDecl
5420 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5421 Context->getTranslationUnitDecl(),
5422 SourceLocation(), SourceLocation(),
5423 &Context->Idents.get("__builtin_va_list"),
5424 TInfo);
5425 return VaListTypeDecl;
5426}
5427
5428static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5429 // typedef void* __builtin_va_list;
5430 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5431 TypeSourceInfo *TInfo
5432 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5433
5434 TypedefDecl *VaListTypeDecl
5435 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5436 Context->getTranslationUnitDecl(),
5437 SourceLocation(), SourceLocation(),
5438 &Context->Idents.get("__builtin_va_list"),
5439 TInfo);
5440 return VaListTypeDecl;
5441}
5442
5443static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5444 // typedef struct __va_list_tag {
5445 RecordDecl *VaListTagDecl;
5446
5447 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5448 Context->getTranslationUnitDecl(),
5449 &Context->Idents.get("__va_list_tag"));
5450 VaListTagDecl->startDefinition();
5451
5452 const size_t NumFields = 5;
5453 QualType FieldTypes[NumFields];
5454 const char *FieldNames[NumFields];
5455
5456 // unsigned char gpr;
5457 FieldTypes[0] = Context->UnsignedCharTy;
5458 FieldNames[0] = "gpr";
5459
5460 // unsigned char fpr;
5461 FieldTypes[1] = Context->UnsignedCharTy;
5462 FieldNames[1] = "fpr";
5463
5464 // unsigned short reserved;
5465 FieldTypes[2] = Context->UnsignedShortTy;
5466 FieldNames[2] = "reserved";
5467
5468 // void* overflow_arg_area;
5469 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5470 FieldNames[3] = "overflow_arg_area";
5471
5472 // void* reg_save_area;
5473 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5474 FieldNames[4] = "reg_save_area";
5475
5476 // Create fields
5477 for (unsigned i = 0; i < NumFields; ++i) {
5478 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5479 SourceLocation(),
5480 SourceLocation(),
5481 &Context->Idents.get(FieldNames[i]),
5482 FieldTypes[i], /*TInfo=*/0,
5483 /*BitWidth=*/0,
5484 /*Mutable=*/false,
5485 ICIS_NoInit);
5486 Field->setAccess(AS_public);
5487 VaListTagDecl->addDecl(Field);
5488 }
5489 VaListTagDecl->completeDefinition();
5490 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005491 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005492
5493 // } __va_list_tag;
5494 TypedefDecl *VaListTagTypedefDecl
5495 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5496 Context->getTranslationUnitDecl(),
5497 SourceLocation(), SourceLocation(),
5498 &Context->Idents.get("__va_list_tag"),
5499 Context->getTrivialTypeSourceInfo(VaListTagType));
5500 QualType VaListTagTypedefType =
5501 Context->getTypedefType(VaListTagTypedefDecl);
5502
5503 // typedef __va_list_tag __builtin_va_list[1];
5504 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5505 QualType VaListTagArrayType
5506 = Context->getConstantArrayType(VaListTagTypedefType,
5507 Size, ArrayType::Normal, 0);
5508 TypeSourceInfo *TInfo
5509 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5510 TypedefDecl *VaListTypedefDecl
5511 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5512 Context->getTranslationUnitDecl(),
5513 SourceLocation(), SourceLocation(),
5514 &Context->Idents.get("__builtin_va_list"),
5515 TInfo);
5516
5517 return VaListTypedefDecl;
5518}
5519
5520static TypedefDecl *
5521CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5522 // typedef struct __va_list_tag {
5523 RecordDecl *VaListTagDecl;
5524 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5525 Context->getTranslationUnitDecl(),
5526 &Context->Idents.get("__va_list_tag"));
5527 VaListTagDecl->startDefinition();
5528
5529 const size_t NumFields = 4;
5530 QualType FieldTypes[NumFields];
5531 const char *FieldNames[NumFields];
5532
5533 // unsigned gp_offset;
5534 FieldTypes[0] = Context->UnsignedIntTy;
5535 FieldNames[0] = "gp_offset";
5536
5537 // unsigned fp_offset;
5538 FieldTypes[1] = Context->UnsignedIntTy;
5539 FieldNames[1] = "fp_offset";
5540
5541 // void* overflow_arg_area;
5542 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5543 FieldNames[2] = "overflow_arg_area";
5544
5545 // void* reg_save_area;
5546 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5547 FieldNames[3] = "reg_save_area";
5548
5549 // Create fields
5550 for (unsigned i = 0; i < NumFields; ++i) {
5551 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5552 VaListTagDecl,
5553 SourceLocation(),
5554 SourceLocation(),
5555 &Context->Idents.get(FieldNames[i]),
5556 FieldTypes[i], /*TInfo=*/0,
5557 /*BitWidth=*/0,
5558 /*Mutable=*/false,
5559 ICIS_NoInit);
5560 Field->setAccess(AS_public);
5561 VaListTagDecl->addDecl(Field);
5562 }
5563 VaListTagDecl->completeDefinition();
5564 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005565 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005566
5567 // } __va_list_tag;
5568 TypedefDecl *VaListTagTypedefDecl
5569 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5570 Context->getTranslationUnitDecl(),
5571 SourceLocation(), SourceLocation(),
5572 &Context->Idents.get("__va_list_tag"),
5573 Context->getTrivialTypeSourceInfo(VaListTagType));
5574 QualType VaListTagTypedefType =
5575 Context->getTypedefType(VaListTagTypedefDecl);
5576
5577 // typedef __va_list_tag __builtin_va_list[1];
5578 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5579 QualType VaListTagArrayType
5580 = Context->getConstantArrayType(VaListTagTypedefType,
5581 Size, ArrayType::Normal,0);
5582 TypeSourceInfo *TInfo
5583 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5584 TypedefDecl *VaListTypedefDecl
5585 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5586 Context->getTranslationUnitDecl(),
5587 SourceLocation(), SourceLocation(),
5588 &Context->Idents.get("__builtin_va_list"),
5589 TInfo);
5590
5591 return VaListTypedefDecl;
5592}
5593
5594static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5595 // typedef int __builtin_va_list[4];
5596 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5597 QualType IntArrayType
5598 = Context->getConstantArrayType(Context->IntTy,
5599 Size, ArrayType::Normal, 0);
5600 TypedefDecl *VaListTypedefDecl
5601 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5602 Context->getTranslationUnitDecl(),
5603 SourceLocation(), SourceLocation(),
5604 &Context->Idents.get("__builtin_va_list"),
5605 Context->getTrivialTypeSourceInfo(IntArrayType));
5606
5607 return VaListTypedefDecl;
5608}
5609
Logan Chien57086ce2012-10-10 06:56:20 +00005610static TypedefDecl *
5611CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5612 RecordDecl *VaListDecl;
5613 if (Context->getLangOpts().CPlusPlus) {
5614 // namespace std { struct __va_list {
5615 NamespaceDecl *NS;
5616 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5617 Context->getTranslationUnitDecl(),
5618 /*Inline*/false, SourceLocation(),
5619 SourceLocation(), &Context->Idents.get("std"),
5620 /*PrevDecl*/0);
5621
5622 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5623 Context->getTranslationUnitDecl(),
5624 SourceLocation(), SourceLocation(),
5625 &Context->Idents.get("__va_list"));
5626
5627 VaListDecl->setDeclContext(NS);
5628
5629 } else {
5630 // struct __va_list {
5631 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5632 Context->getTranslationUnitDecl(),
5633 &Context->Idents.get("__va_list"));
5634 }
5635
5636 VaListDecl->startDefinition();
5637
5638 // void * __ap;
5639 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5640 VaListDecl,
5641 SourceLocation(),
5642 SourceLocation(),
5643 &Context->Idents.get("__ap"),
5644 Context->getPointerType(Context->VoidTy),
5645 /*TInfo=*/0,
5646 /*BitWidth=*/0,
5647 /*Mutable=*/false,
5648 ICIS_NoInit);
5649 Field->setAccess(AS_public);
5650 VaListDecl->addDecl(Field);
5651
5652 // };
5653 VaListDecl->completeDefinition();
5654
5655 // typedef struct __va_list __builtin_va_list;
5656 TypeSourceInfo *TInfo
5657 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5658
5659 TypedefDecl *VaListTypeDecl
5660 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5661 Context->getTranslationUnitDecl(),
5662 SourceLocation(), SourceLocation(),
5663 &Context->Idents.get("__builtin_va_list"),
5664 TInfo);
5665
5666 return VaListTypeDecl;
5667}
5668
Meador Inge5d3fb222012-06-16 03:34:49 +00005669static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5670 TargetInfo::BuiltinVaListKind Kind) {
5671 switch (Kind) {
5672 case TargetInfo::CharPtrBuiltinVaList:
5673 return CreateCharPtrBuiltinVaListDecl(Context);
5674 case TargetInfo::VoidPtrBuiltinVaList:
5675 return CreateVoidPtrBuiltinVaListDecl(Context);
5676 case TargetInfo::PowerABIBuiltinVaList:
5677 return CreatePowerABIBuiltinVaListDecl(Context);
5678 case TargetInfo::X86_64ABIBuiltinVaList:
5679 return CreateX86_64ABIBuiltinVaListDecl(Context);
5680 case TargetInfo::PNaClABIBuiltinVaList:
5681 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00005682 case TargetInfo::AAPCSABIBuiltinVaList:
5683 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00005684 }
5685
5686 llvm_unreachable("Unhandled __builtin_va_list type kind");
5687}
5688
5689TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5690 if (!BuiltinVaListDecl)
5691 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5692
5693 return BuiltinVaListDecl;
5694}
5695
Meador Ingecfb60902012-07-01 15:57:25 +00005696QualType ASTContext::getVaListTagType() const {
5697 // Force the creation of VaListTagTy by building the __builtin_va_list
5698 // declaration.
5699 if (VaListTagTy.isNull())
5700 (void) getBuiltinVaListDecl();
5701
5702 return VaListTagTy;
5703}
5704
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005705void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005706 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005707 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005708
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005709 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005710}
5711
John McCalld28ae272009-12-02 08:04:21 +00005712/// \brief Retrieve the template name that corresponds to a non-empty
5713/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005714TemplateName
5715ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5716 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005717 unsigned size = End - Begin;
5718 assert(size > 1 && "set is not overloaded!");
5719
5720 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5721 size * sizeof(FunctionTemplateDecl*));
5722 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5723
5724 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005725 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005726 NamedDecl *D = *I;
5727 assert(isa<FunctionTemplateDecl>(D) ||
5728 (isa<UsingShadowDecl>(D) &&
5729 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5730 *Storage++ = D;
5731 }
5732
5733 return TemplateName(OT);
5734}
5735
Douglas Gregordc572a32009-03-30 22:58:21 +00005736/// \brief Retrieve the template name that represents a qualified
5737/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005738TemplateName
5739ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5740 bool TemplateKeyword,
5741 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005742 assert(NNS && "Missing nested-name-specifier in qualified template name");
5743
Douglas Gregorc42075a2010-02-04 18:10:26 +00005744 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005745 llvm::FoldingSetNodeID ID;
5746 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5747
5748 void *InsertPos = 0;
5749 QualifiedTemplateName *QTN =
5750 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5751 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00005752 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5753 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00005754 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5755 }
5756
5757 return TemplateName(QTN);
5758}
5759
5760/// \brief Retrieve the template name that represents a dependent
5761/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005762TemplateName
5763ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5764 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005765 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005766 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005767
5768 llvm::FoldingSetNodeID ID;
5769 DependentTemplateName::Profile(ID, NNS, Name);
5770
5771 void *InsertPos = 0;
5772 DependentTemplateName *QTN =
5773 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5774
5775 if (QTN)
5776 return TemplateName(QTN);
5777
5778 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5779 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005780 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5781 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00005782 } else {
5783 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00005784 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5785 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005786 DependentTemplateName *CheckQTN =
5787 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5788 assert(!CheckQTN && "Dependent type name canonicalization broken");
5789 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005790 }
5791
5792 DependentTemplateNames.InsertNode(QTN, InsertPos);
5793 return TemplateName(QTN);
5794}
5795
Douglas Gregor71395fa2009-11-04 00:56:37 +00005796/// \brief Retrieve the template name that represents a dependent
5797/// template name such as \c MetaFun::template operator+.
5798TemplateName
5799ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005800 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005801 assert((!NNS || NNS->isDependent()) &&
5802 "Nested name specifier must be dependent");
5803
5804 llvm::FoldingSetNodeID ID;
5805 DependentTemplateName::Profile(ID, NNS, Operator);
5806
5807 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005808 DependentTemplateName *QTN
5809 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005810
5811 if (QTN)
5812 return TemplateName(QTN);
5813
5814 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5815 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005816 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5817 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005818 } else {
5819 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00005820 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5821 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005822
5823 DependentTemplateName *CheckQTN
5824 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5825 assert(!CheckQTN && "Dependent template name canonicalization broken");
5826 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005827 }
5828
5829 DependentTemplateNames.InsertNode(QTN, InsertPos);
5830 return TemplateName(QTN);
5831}
5832
Douglas Gregor5590be02011-01-15 06:45:20 +00005833TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005834ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5835 TemplateName replacement) const {
5836 llvm::FoldingSetNodeID ID;
5837 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5838
5839 void *insertPos = 0;
5840 SubstTemplateTemplateParmStorage *subst
5841 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5842
5843 if (!subst) {
5844 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5845 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5846 }
5847
5848 return TemplateName(subst);
5849}
5850
5851TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005852ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5853 const TemplateArgument &ArgPack) const {
5854 ASTContext &Self = const_cast<ASTContext &>(*this);
5855 llvm::FoldingSetNodeID ID;
5856 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5857
5858 void *InsertPos = 0;
5859 SubstTemplateTemplateParmPackStorage *Subst
5860 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5861
5862 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005863 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005864 ArgPack.pack_size(),
5865 ArgPack.pack_begin());
5866 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5867 }
5868
5869 return TemplateName(Subst);
5870}
5871
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005872/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005873/// TargetInfo, produce the corresponding type. The unsigned @p Type
5874/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005875CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005876 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005877 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005878 case TargetInfo::SignedShort: return ShortTy;
5879 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5880 case TargetInfo::SignedInt: return IntTy;
5881 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5882 case TargetInfo::SignedLong: return LongTy;
5883 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5884 case TargetInfo::SignedLongLong: return LongLongTy;
5885 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5886 }
5887
David Blaikie83d382b2011-09-23 05:06:16 +00005888 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005889}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005890
5891//===----------------------------------------------------------------------===//
5892// Type Predicates.
5893//===----------------------------------------------------------------------===//
5894
Fariborz Jahanian96207692009-02-18 21:49:28 +00005895/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5896/// garbage collection attribute.
5897///
John McCall553d45a2011-01-12 00:34:59 +00005898Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005899 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005900 return Qualifiers::GCNone;
5901
David Blaikiebbafb8a2012-03-11 07:00:24 +00005902 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005903 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5904
5905 // Default behaviour under objective-C's gc is for ObjC pointers
5906 // (or pointers to them) be treated as though they were declared
5907 // as __strong.
5908 if (GCAttrs == Qualifiers::GCNone) {
5909 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5910 return Qualifiers::Strong;
5911 else if (Ty->isPointerType())
5912 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5913 } else {
5914 // It's not valid to set GC attributes on anything that isn't a
5915 // pointer.
5916#ifndef NDEBUG
5917 QualType CT = Ty->getCanonicalTypeInternal();
5918 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5919 CT = AT->getElementType();
5920 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5921#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005922 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005923 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005924}
5925
Chris Lattner49af6a42008-04-07 06:51:04 +00005926//===----------------------------------------------------------------------===//
5927// Type Compatibility Testing
5928//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005929
Mike Stump11289f42009-09-09 15:08:12 +00005930/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005931/// compatible.
5932static bool areCompatVectorTypes(const VectorType *LHS,
5933 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005934 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005935 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005936 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005937}
5938
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005939bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5940 QualType SecondVec) {
5941 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5942 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5943
5944 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5945 return true;
5946
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005947 // Treat Neon vector types and most AltiVec vector types as if they are the
5948 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005949 const VectorType *First = FirstVec->getAs<VectorType>();
5950 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005951 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005952 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005953 First->getVectorKind() != VectorType::AltiVecPixel &&
5954 First->getVectorKind() != VectorType::AltiVecBool &&
5955 Second->getVectorKind() != VectorType::AltiVecPixel &&
5956 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005957 return true;
5958
5959 return false;
5960}
5961
Steve Naroff8e6aee52009-07-23 01:01:38 +00005962//===----------------------------------------------------------------------===//
5963// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5964//===----------------------------------------------------------------------===//
5965
5966/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5967/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005968bool
5969ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5970 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005971 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005972 return true;
5973 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5974 E = rProto->protocol_end(); PI != E; ++PI)
5975 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5976 return true;
5977 return false;
5978}
5979
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00005980/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00005981/// return true if lhs's protocols conform to rhs's protocol; false
5982/// otherwise.
5983bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5984 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5985 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5986 return false;
5987}
5988
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00005989/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
5990/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005991bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5992 QualType rhs) {
5993 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5994 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5995 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5996
5997 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5998 E = lhsQID->qual_end(); I != E; ++I) {
5999 bool match = false;
6000 ObjCProtocolDecl *lhsProto = *I;
6001 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6002 E = rhsOPT->qual_end(); J != E; ++J) {
6003 ObjCProtocolDecl *rhsProto = *J;
6004 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6005 match = true;
6006 break;
6007 }
6008 }
6009 if (!match)
6010 return false;
6011 }
6012 return true;
6013}
6014
Steve Naroff8e6aee52009-07-23 01:01:38 +00006015/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6016/// ObjCQualifiedIDType.
6017bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6018 bool compare) {
6019 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006020 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006021 lhs->isObjCIdType() || lhs->isObjCClassType())
6022 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006023 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006024 rhs->isObjCIdType() || rhs->isObjCClassType())
6025 return true;
6026
6027 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006028 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006029
Steve Naroff8e6aee52009-07-23 01:01:38 +00006030 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006031
Steve Naroff8e6aee52009-07-23 01:01:38 +00006032 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006033 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006034 // make sure we check the class hierarchy.
6035 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6036 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6037 E = lhsQID->qual_end(); I != E; ++I) {
6038 // when comparing an id<P> on lhs with a static type on rhs,
6039 // see if static class implements all of id's protocols, directly or
6040 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006041 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006042 return false;
6043 }
6044 }
6045 // If there are no qualifiers and no interface, we have an 'id'.
6046 return true;
6047 }
Mike Stump11289f42009-09-09 15:08:12 +00006048 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006049 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6050 E = lhsQID->qual_end(); I != E; ++I) {
6051 ObjCProtocolDecl *lhsProto = *I;
6052 bool match = false;
6053
6054 // when comparing an id<P> on lhs with a static type on rhs,
6055 // see if static class implements all of id's protocols, directly or
6056 // through its super class and categories.
6057 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6058 E = rhsOPT->qual_end(); J != E; ++J) {
6059 ObjCProtocolDecl *rhsProto = *J;
6060 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6061 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6062 match = true;
6063 break;
6064 }
6065 }
Mike Stump11289f42009-09-09 15:08:12 +00006066 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006067 // make sure we check the class hierarchy.
6068 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6069 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6070 E = lhsQID->qual_end(); I != E; ++I) {
6071 // when comparing an id<P> on lhs with a static type on rhs,
6072 // see if static class implements all of id's protocols, directly or
6073 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006074 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006075 match = true;
6076 break;
6077 }
6078 }
6079 }
6080 if (!match)
6081 return false;
6082 }
Mike Stump11289f42009-09-09 15:08:12 +00006083
Steve Naroff8e6aee52009-07-23 01:01:38 +00006084 return true;
6085 }
Mike Stump11289f42009-09-09 15:08:12 +00006086
Steve Naroff8e6aee52009-07-23 01:01:38 +00006087 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6088 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6089
Mike Stump11289f42009-09-09 15:08:12 +00006090 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006091 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006092 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006093 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6094 E = lhsOPT->qual_end(); I != E; ++I) {
6095 ObjCProtocolDecl *lhsProto = *I;
6096 bool match = false;
6097
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006098 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006099 // see if static class implements all of id's protocols, directly or
6100 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006101 // First, lhs protocols in the qualifier list must be found, direct
6102 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006103 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6104 E = rhsQID->qual_end(); J != E; ++J) {
6105 ObjCProtocolDecl *rhsProto = *J;
6106 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6107 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6108 match = true;
6109 break;
6110 }
6111 }
6112 if (!match)
6113 return false;
6114 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006115
6116 // Static class's protocols, or its super class or category protocols
6117 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6118 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6119 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6120 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6121 // This is rather dubious but matches gcc's behavior. If lhs has
6122 // no type qualifier and its class has no static protocol(s)
6123 // assume that it is mismatch.
6124 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6125 return false;
6126 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6127 LHSInheritedProtocols.begin(),
6128 E = LHSInheritedProtocols.end(); I != E; ++I) {
6129 bool match = false;
6130 ObjCProtocolDecl *lhsProto = (*I);
6131 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6132 E = rhsQID->qual_end(); J != E; ++J) {
6133 ObjCProtocolDecl *rhsProto = *J;
6134 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6135 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6136 match = true;
6137 break;
6138 }
6139 }
6140 if (!match)
6141 return false;
6142 }
6143 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006144 return true;
6145 }
6146 return false;
6147}
6148
Eli Friedman47f77112008-08-22 00:56:42 +00006149/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006150/// compatible for assignment from RHS to LHS. This handles validation of any
6151/// protocol qualifiers on the LHS or RHS.
6152///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006153bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6154 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006155 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6156 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6157
Steve Naroff1329fa02009-07-15 18:40:39 +00006158 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006159 if (LHS->isObjCUnqualifiedIdOrClass() ||
6160 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006161 return true;
6162
John McCall8b07ec22010-05-15 11:32:37 +00006163 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006164 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6165 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006166 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006167
6168 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6169 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6170 QualType(RHSOPT,0));
6171
John McCall8b07ec22010-05-15 11:32:37 +00006172 // If we have 2 user-defined types, fall into that path.
6173 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006174 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006175
Steve Naroff8e6aee52009-07-23 01:01:38 +00006176 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006177}
6178
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006179/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006180/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006181/// arguments in block literals. When passed as arguments, passing 'A*' where
6182/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6183/// not OK. For the return type, the opposite is not OK.
6184bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6185 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006186 const ObjCObjectPointerType *RHSOPT,
6187 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006188 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006189 return true;
6190
6191 if (LHSOPT->isObjCBuiltinType()) {
6192 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6193 }
6194
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006195 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006196 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6197 QualType(RHSOPT,0),
6198 false);
6199
6200 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6201 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6202 if (LHS && RHS) { // We have 2 user-defined types.
6203 if (LHS != RHS) {
6204 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006205 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006206 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006207 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006208 }
6209 else
6210 return true;
6211 }
6212 return false;
6213}
6214
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006215/// getIntersectionOfProtocols - This routine finds the intersection of set
6216/// of protocols inherited from two distinct objective-c pointer objects.
6217/// It is used to build composite qualifier list of the composite type of
6218/// the conditional expression involving two objective-c pointer objects.
6219static
6220void getIntersectionOfProtocols(ASTContext &Context,
6221 const ObjCObjectPointerType *LHSOPT,
6222 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006223 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006224
John McCall8b07ec22010-05-15 11:32:37 +00006225 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6226 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6227 assert(LHS->getInterface() && "LHS must have an interface base");
6228 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006229
6230 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6231 unsigned LHSNumProtocols = LHS->getNumProtocols();
6232 if (LHSNumProtocols > 0)
6233 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6234 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006235 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006236 Context.CollectInheritedProtocols(LHS->getInterface(),
6237 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006238 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6239 LHSInheritedProtocols.end());
6240 }
6241
6242 unsigned RHSNumProtocols = RHS->getNumProtocols();
6243 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006244 ObjCProtocolDecl **RHSProtocols =
6245 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006246 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6247 if (InheritedProtocolSet.count(RHSProtocols[i]))
6248 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006249 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006250 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006251 Context.CollectInheritedProtocols(RHS->getInterface(),
6252 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006253 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6254 RHSInheritedProtocols.begin(),
6255 E = RHSInheritedProtocols.end(); I != E; ++I)
6256 if (InheritedProtocolSet.count((*I)))
6257 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006258 }
6259}
6260
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006261/// areCommonBaseCompatible - Returns common base class of the two classes if
6262/// one found. Note that this is O'2 algorithm. But it will be called as the
6263/// last type comparison in a ?-exp of ObjC pointer types before a
6264/// warning is issued. So, its invokation is extremely rare.
6265QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006266 const ObjCObjectPointerType *Lptr,
6267 const ObjCObjectPointerType *Rptr) {
6268 const ObjCObjectType *LHS = Lptr->getObjectType();
6269 const ObjCObjectType *RHS = Rptr->getObjectType();
6270 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6271 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006272 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006273 return QualType();
6274
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006275 do {
John McCall8b07ec22010-05-15 11:32:37 +00006276 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006277 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006278 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006279 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6280
6281 QualType Result = QualType(LHS, 0);
6282 if (!Protocols.empty())
6283 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6284 Result = getObjCObjectPointerType(Result);
6285 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006286 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006287 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006288
6289 return QualType();
6290}
6291
John McCall8b07ec22010-05-15 11:32:37 +00006292bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6293 const ObjCObjectType *RHS) {
6294 assert(LHS->getInterface() && "LHS is not an interface type");
6295 assert(RHS->getInterface() && "RHS is not an interface type");
6296
Chris Lattner49af6a42008-04-07 06:51:04 +00006297 // Verify that the base decls are compatible: the RHS must be a subclass of
6298 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006299 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006300 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006301
Chris Lattner49af6a42008-04-07 06:51:04 +00006302 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6303 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006304 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006305 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006306
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006307 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6308 // more detailed analysis is required.
6309 if (RHS->getNumProtocols() == 0) {
6310 // OK, if LHS is a superclass of RHS *and*
6311 // this superclass is assignment compatible with LHS.
6312 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006313 bool IsSuperClass =
6314 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6315 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006316 // OK if conversion of LHS to SuperClass results in narrowing of types
6317 // ; i.e., SuperClass may implement at least one of the protocols
6318 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6319 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6320 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006321 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006322 // If super class has no protocols, it is not a match.
6323 if (SuperClassInheritedProtocols.empty())
6324 return false;
6325
6326 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6327 LHSPE = LHS->qual_end();
6328 LHSPI != LHSPE; LHSPI++) {
6329 bool SuperImplementsProtocol = false;
6330 ObjCProtocolDecl *LHSProto = (*LHSPI);
6331
6332 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6333 SuperClassInheritedProtocols.begin(),
6334 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6335 ObjCProtocolDecl *SuperClassProto = (*I);
6336 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6337 SuperImplementsProtocol = true;
6338 break;
6339 }
6340 }
6341 if (!SuperImplementsProtocol)
6342 return false;
6343 }
6344 return true;
6345 }
6346 return false;
6347 }
Mike Stump11289f42009-09-09 15:08:12 +00006348
John McCall8b07ec22010-05-15 11:32:37 +00006349 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6350 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006351 LHSPI != LHSPE; LHSPI++) {
6352 bool RHSImplementsProtocol = false;
6353
6354 // If the RHS doesn't implement the protocol on the left, the types
6355 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006356 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6357 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006358 RHSPI != RHSPE; RHSPI++) {
6359 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006360 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006361 break;
6362 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006363 }
6364 // FIXME: For better diagnostics, consider passing back the protocol name.
6365 if (!RHSImplementsProtocol)
6366 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006367 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006368 // The RHS implements all protocols listed on the LHS.
6369 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006370}
6371
Steve Naroffb7605152009-02-12 17:52:19 +00006372bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6373 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006374 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6375 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006376
Steve Naroff7cae42b2009-07-10 23:34:53 +00006377 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006378 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006379
6380 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6381 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006382}
6383
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006384bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6385 return canAssignObjCInterfaces(
6386 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6387 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6388}
6389
Mike Stump11289f42009-09-09 15:08:12 +00006390/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006391/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006392/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006393/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006394bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6395 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006396 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006397 return hasSameType(LHS, RHS);
6398
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006399 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006400}
6401
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006402bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006403 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006404}
6405
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006406bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6407 return !mergeTypes(LHS, RHS, true).isNull();
6408}
6409
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006410/// mergeTransparentUnionType - if T is a transparent union type and a member
6411/// of T is compatible with SubType, return the merged type, else return
6412/// QualType()
6413QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6414 bool OfBlockPointer,
6415 bool Unqualified) {
6416 if (const RecordType *UT = T->getAsUnionType()) {
6417 RecordDecl *UD = UT->getDecl();
6418 if (UD->hasAttr<TransparentUnionAttr>()) {
6419 for (RecordDecl::field_iterator it = UD->field_begin(),
6420 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006421 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006422 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6423 if (!MT.isNull())
6424 return MT;
6425 }
6426 }
6427 }
6428
6429 return QualType();
6430}
6431
6432/// mergeFunctionArgumentTypes - merge two types which appear as function
6433/// argument types
6434QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6435 bool OfBlockPointer,
6436 bool Unqualified) {
6437 // GNU extension: two types are compatible if they appear as a function
6438 // argument, one of the types is a transparent union type and the other
6439 // type is compatible with a union member
6440 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6441 Unqualified);
6442 if (!lmerge.isNull())
6443 return lmerge;
6444
6445 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6446 Unqualified);
6447 if (!rmerge.isNull())
6448 return rmerge;
6449
6450 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6451}
6452
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006453QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006454 bool OfBlockPointer,
6455 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006456 const FunctionType *lbase = lhs->getAs<FunctionType>();
6457 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006458 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6459 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006460 bool allLTypes = true;
6461 bool allRTypes = true;
6462
6463 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006464 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006465 if (OfBlockPointer) {
6466 QualType RHS = rbase->getResultType();
6467 QualType LHS = lbase->getResultType();
6468 bool UnqualifiedResult = Unqualified;
6469 if (!UnqualifiedResult)
6470 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006471 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006472 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006473 else
John McCall8c6b56f2010-12-15 01:06:38 +00006474 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6475 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006476 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006477
6478 if (Unqualified)
6479 retType = retType.getUnqualifiedType();
6480
6481 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6482 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6483 if (Unqualified) {
6484 LRetType = LRetType.getUnqualifiedType();
6485 RRetType = RRetType.getUnqualifiedType();
6486 }
6487
6488 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006489 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006490 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006491 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006492
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006493 // FIXME: double check this
6494 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6495 // rbase->getRegParmAttr() != 0 &&
6496 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006497 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6498 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006499
Douglas Gregor8c940862010-01-18 17:14:39 +00006500 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006501 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006502 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006503
John McCall8c6b56f2010-12-15 01:06:38 +00006504 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006505 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6506 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006507 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6508 return QualType();
6509
John McCall31168b02011-06-15 23:02:42 +00006510 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6511 return QualType();
6512
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006513 // functypes which return are preferred over those that do not.
6514 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6515 allLTypes = false;
6516 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6517 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006518 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6519 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006520
John McCall31168b02011-06-15 23:02:42 +00006521 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006522
Eli Friedman47f77112008-08-22 00:56:42 +00006523 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006524 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6525 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006526 unsigned lproto_nargs = lproto->getNumArgs();
6527 unsigned rproto_nargs = rproto->getNumArgs();
6528
6529 // Compatible functions must have the same number of arguments
6530 if (lproto_nargs != rproto_nargs)
6531 return QualType();
6532
6533 // Variadic and non-variadic functions aren't compatible
6534 if (lproto->isVariadic() != rproto->isVariadic())
6535 return QualType();
6536
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006537 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6538 return QualType();
6539
Fariborz Jahanian97676972011-09-28 21:52:05 +00006540 if (LangOpts.ObjCAutoRefCount &&
6541 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6542 return QualType();
6543
Eli Friedman47f77112008-08-22 00:56:42 +00006544 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006545 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006546 for (unsigned i = 0; i < lproto_nargs; i++) {
6547 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6548 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006549 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6550 OfBlockPointer,
6551 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006552 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006553
6554 if (Unqualified)
6555 argtype = argtype.getUnqualifiedType();
6556
Eli Friedman47f77112008-08-22 00:56:42 +00006557 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006558 if (Unqualified) {
6559 largtype = largtype.getUnqualifiedType();
6560 rargtype = rargtype.getUnqualifiedType();
6561 }
6562
Chris Lattner465fa322008-10-05 17:34:18 +00006563 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6564 allLTypes = false;
6565 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6566 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006567 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006568
Eli Friedman47f77112008-08-22 00:56:42 +00006569 if (allLTypes) return lhs;
6570 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006571
6572 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6573 EPI.ExtInfo = einfo;
6574 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006575 }
6576
6577 if (lproto) allRTypes = false;
6578 if (rproto) allLTypes = false;
6579
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006580 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006581 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006582 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006583 if (proto->isVariadic()) return QualType();
6584 // Check that the types are compatible with the types that
6585 // would result from default argument promotions (C99 6.7.5.3p15).
6586 // The only types actually affected are promotable integer
6587 // types and floats, which would be passed as a different
6588 // type depending on whether the prototype is visible.
6589 unsigned proto_nargs = proto->getNumArgs();
6590 for (unsigned i = 0; i < proto_nargs; ++i) {
6591 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006592
Eli Friedman448ce402012-08-30 00:44:15 +00006593 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006594 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00006595 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6596 argTy = Enum->getDecl()->getIntegerType();
6597 if (argTy.isNull())
6598 return QualType();
6599 }
Douglas Gregor2973d402010-02-03 19:27:29 +00006600
Eli Friedman47f77112008-08-22 00:56:42 +00006601 if (argTy->isPromotableIntegerType() ||
6602 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6603 return QualType();
6604 }
6605
6606 if (allLTypes) return lhs;
6607 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006608
6609 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6610 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006611 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006612 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006613 }
6614
6615 if (allLTypes) return lhs;
6616 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006617 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006618}
6619
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006620QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006621 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006622 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006623 // C++ [expr]: If an expression initially has the type "reference to T", the
6624 // type is adjusted to "T" prior to any further analysis, the expression
6625 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006626 // expression is an lvalue unless the reference is an rvalue reference and
6627 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006628 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6629 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006630
6631 if (Unqualified) {
6632 LHS = LHS.getUnqualifiedType();
6633 RHS = RHS.getUnqualifiedType();
6634 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006635
Eli Friedman47f77112008-08-22 00:56:42 +00006636 QualType LHSCan = getCanonicalType(LHS),
6637 RHSCan = getCanonicalType(RHS);
6638
6639 // If two types are identical, they are compatible.
6640 if (LHSCan == RHSCan)
6641 return LHS;
6642
John McCall8ccfcb52009-09-24 19:53:00 +00006643 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006644 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6645 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006646 if (LQuals != RQuals) {
6647 // If any of these qualifiers are different, we have a type
6648 // mismatch.
6649 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006650 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6651 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006652 return QualType();
6653
6654 // Exactly one GC qualifier difference is allowed: __strong is
6655 // okay if the other type has no GC qualifier but is an Objective
6656 // C object pointer (i.e. implicitly strong by default). We fix
6657 // this by pretending that the unqualified type was actually
6658 // qualified __strong.
6659 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6660 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6661 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6662
6663 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6664 return QualType();
6665
6666 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6667 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6668 }
6669 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6670 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6671 }
Eli Friedman47f77112008-08-22 00:56:42 +00006672 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006673 }
6674
6675 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006676
Eli Friedmandcca6332009-06-01 01:22:52 +00006677 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6678 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006679
Chris Lattnerfd652912008-01-14 05:45:46 +00006680 // We want to consider the two function types to be the same for these
6681 // comparisons, just force one to the other.
6682 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6683 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006684
6685 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006686 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6687 LHSClass = Type::ConstantArray;
6688 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6689 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006690
John McCall8b07ec22010-05-15 11:32:37 +00006691 // ObjCInterfaces are just specialized ObjCObjects.
6692 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6693 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6694
Nate Begemance4d7fc2008-04-18 23:10:10 +00006695 // Canonicalize ExtVector -> Vector.
6696 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6697 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006698
Chris Lattner95554662008-04-07 05:43:21 +00006699 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006700 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006701 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006702 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006703 // Compatibility is based on the underlying type, not the promotion
6704 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006705 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006706 QualType TINT = ETy->getDecl()->getIntegerType();
6707 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006708 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006709 }
John McCall9dd450b2009-09-21 23:43:11 +00006710 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006711 QualType TINT = ETy->getDecl()->getIntegerType();
6712 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006713 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006714 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006715 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006716 if (OfBlockPointer && !BlockReturnType) {
6717 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6718 return LHS;
6719 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6720 return RHS;
6721 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006722
Eli Friedman47f77112008-08-22 00:56:42 +00006723 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006724 }
Eli Friedman47f77112008-08-22 00:56:42 +00006725
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006726 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006727 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006728#define TYPE(Class, Base)
6729#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006730#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006731#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6732#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6733#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006734 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006735
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006736 case Type::LValueReference:
6737 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006738 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006739 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006740
John McCall8b07ec22010-05-15 11:32:37 +00006741 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006742 case Type::IncompleteArray:
6743 case Type::VariableArray:
6744 case Type::FunctionProto:
6745 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006746 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006747
Chris Lattnerfd652912008-01-14 05:45:46 +00006748 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006749 {
6750 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006751 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6752 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006753 if (Unqualified) {
6754 LHSPointee = LHSPointee.getUnqualifiedType();
6755 RHSPointee = RHSPointee.getUnqualifiedType();
6756 }
6757 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6758 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006759 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006760 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006761 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006762 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006763 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006764 return getPointerType(ResultType);
6765 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006766 case Type::BlockPointer:
6767 {
6768 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006769 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6770 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006771 if (Unqualified) {
6772 LHSPointee = LHSPointee.getUnqualifiedType();
6773 RHSPointee = RHSPointee.getUnqualifiedType();
6774 }
6775 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6776 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006777 if (ResultType.isNull()) return QualType();
6778 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6779 return LHS;
6780 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6781 return RHS;
6782 return getBlockPointerType(ResultType);
6783 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006784 case Type::Atomic:
6785 {
6786 // Merge two pointer types, while trying to preserve typedef info
6787 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6788 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6789 if (Unqualified) {
6790 LHSValue = LHSValue.getUnqualifiedType();
6791 RHSValue = RHSValue.getUnqualifiedType();
6792 }
6793 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6794 Unqualified);
6795 if (ResultType.isNull()) return QualType();
6796 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6797 return LHS;
6798 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6799 return RHS;
6800 return getAtomicType(ResultType);
6801 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006802 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006803 {
6804 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6805 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6806 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6807 return QualType();
6808
6809 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6810 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006811 if (Unqualified) {
6812 LHSElem = LHSElem.getUnqualifiedType();
6813 RHSElem = RHSElem.getUnqualifiedType();
6814 }
6815
6816 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006817 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006818 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6819 return LHS;
6820 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6821 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006822 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6823 ArrayType::ArraySizeModifier(), 0);
6824 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6825 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006826 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6827 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006828 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6829 return LHS;
6830 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6831 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006832 if (LVAT) {
6833 // FIXME: This isn't correct! But tricky to implement because
6834 // the array's size has to be the size of LHS, but the type
6835 // has to be different.
6836 return LHS;
6837 }
6838 if (RVAT) {
6839 // FIXME: This isn't correct! But tricky to implement because
6840 // the array's size has to be the size of RHS, but the type
6841 // has to be different.
6842 return RHS;
6843 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006844 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6845 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006846 return getIncompleteArrayType(ResultType,
6847 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006848 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006849 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006850 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006851 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006852 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006853 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006854 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006855 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006856 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006857 case Type::Complex:
6858 // Distinct complex types are incompatible.
6859 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006860 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006861 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006862 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6863 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006864 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006865 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006866 case Type::ObjCObject: {
6867 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006868 // FIXME: This should be type compatibility, e.g. whether
6869 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006870 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6871 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6872 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006873 return LHS;
6874
Eli Friedman47f77112008-08-22 00:56:42 +00006875 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006876 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006877 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006878 if (OfBlockPointer) {
6879 if (canAssignObjCInterfacesInBlockPointer(
6880 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006881 RHS->getAs<ObjCObjectPointerType>(),
6882 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006883 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006884 return QualType();
6885 }
John McCall9dd450b2009-09-21 23:43:11 +00006886 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6887 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006888 return LHS;
6889
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006890 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006891 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006892 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006893
David Blaikie8a40f702012-01-17 06:56:22 +00006894 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006895}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006896
Fariborz Jahanian97676972011-09-28 21:52:05 +00006897bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6898 const FunctionProtoType *FromFunctionType,
6899 const FunctionProtoType *ToFunctionType) {
6900 if (FromFunctionType->hasAnyConsumedArgs() !=
6901 ToFunctionType->hasAnyConsumedArgs())
6902 return false;
6903 FunctionProtoType::ExtProtoInfo FromEPI =
6904 FromFunctionType->getExtProtoInfo();
6905 FunctionProtoType::ExtProtoInfo ToEPI =
6906 ToFunctionType->getExtProtoInfo();
6907 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6908 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6909 ArgIdx != NumArgs; ++ArgIdx) {
6910 if (FromEPI.ConsumedArguments[ArgIdx] !=
6911 ToEPI.ConsumedArguments[ArgIdx])
6912 return false;
6913 }
6914 return true;
6915}
6916
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006917/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6918/// 'RHS' attributes and returns the merged version; including for function
6919/// return types.
6920QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6921 QualType LHSCan = getCanonicalType(LHS),
6922 RHSCan = getCanonicalType(RHS);
6923 // If two types are identical, they are compatible.
6924 if (LHSCan == RHSCan)
6925 return LHS;
6926 if (RHSCan->isFunctionType()) {
6927 if (!LHSCan->isFunctionType())
6928 return QualType();
6929 QualType OldReturnType =
6930 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6931 QualType NewReturnType =
6932 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6933 QualType ResReturnType =
6934 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6935 if (ResReturnType.isNull())
6936 return QualType();
6937 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6938 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6939 // In either case, use OldReturnType to build the new function type.
6940 const FunctionType *F = LHS->getAs<FunctionType>();
6941 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006942 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6943 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006944 QualType ResultType
6945 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006946 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006947 return ResultType;
6948 }
6949 }
6950 return QualType();
6951 }
6952
6953 // If the qualifiers are different, the types can still be merged.
6954 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6955 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6956 if (LQuals != RQuals) {
6957 // If any of these qualifiers are different, we have a type mismatch.
6958 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6959 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6960 return QualType();
6961
6962 // Exactly one GC qualifier difference is allowed: __strong is
6963 // okay if the other type has no GC qualifier but is an Objective
6964 // C object pointer (i.e. implicitly strong by default). We fix
6965 // this by pretending that the unqualified type was actually
6966 // qualified __strong.
6967 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6968 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6969 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6970
6971 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6972 return QualType();
6973
6974 if (GC_L == Qualifiers::Strong)
6975 return LHS;
6976 if (GC_R == Qualifiers::Strong)
6977 return RHS;
6978 return QualType();
6979 }
6980
6981 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6982 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6983 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6984 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6985 if (ResQT == LHSBaseQT)
6986 return LHS;
6987 if (ResQT == RHSBaseQT)
6988 return RHS;
6989 }
6990 return QualType();
6991}
6992
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006993//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006994// Integer Predicates
6995//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006996
Jay Foad39c79802011-01-12 09:06:06 +00006997unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006998 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006999 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007000 if (T->isBooleanType())
7001 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007002 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007003 return (unsigned)getTypeSize(T);
7004}
7005
Abramo Bagnara13640492012-09-09 10:21:24 +00007006QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007007 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007008
7009 // Turn <4 x signed int> -> <4 x unsigned int>
7010 if (const VectorType *VTy = T->getAs<VectorType>())
7011 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007012 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007013
7014 // For enums, we return the unsigned version of the base type.
7015 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007016 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007017
7018 const BuiltinType *BTy = T->getAs<BuiltinType>();
7019 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007020 switch (BTy->getKind()) {
7021 case BuiltinType::Char_S:
7022 case BuiltinType::SChar:
7023 return UnsignedCharTy;
7024 case BuiltinType::Short:
7025 return UnsignedShortTy;
7026 case BuiltinType::Int:
7027 return UnsignedIntTy;
7028 case BuiltinType::Long:
7029 return UnsignedLongTy;
7030 case BuiltinType::LongLong:
7031 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007032 case BuiltinType::Int128:
7033 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007034 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007035 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007036 }
7037}
7038
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007039ASTMutationListener::~ASTMutationListener() { }
7040
Chris Lattnerecd79c62009-06-14 00:45:47 +00007041
7042//===----------------------------------------------------------------------===//
7043// Builtin Type Computation
7044//===----------------------------------------------------------------------===//
7045
7046/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007047/// pointer over the consumed characters. This returns the resultant type. If
7048/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7049/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7050/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007051///
7052/// RequiresICE is filled in on return to indicate whether the value is required
7053/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007054static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007055 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007056 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007057 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007058 // Modifiers.
7059 int HowLong = 0;
7060 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007061 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007062
Chris Lattnerdc226c22010-10-01 22:42:38 +00007063 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007064 bool Done = false;
7065 while (!Done) {
7066 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007067 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007068 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007069 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007070 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007071 case 'S':
7072 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7073 assert(!Signed && "Can't use 'S' modifier multiple times!");
7074 Signed = true;
7075 break;
7076 case 'U':
7077 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7078 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7079 Unsigned = true;
7080 break;
7081 case 'L':
7082 assert(HowLong <= 2 && "Can't have LLLL modifier");
7083 ++HowLong;
7084 break;
7085 }
7086 }
7087
7088 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007089
Chris Lattnerecd79c62009-06-14 00:45:47 +00007090 // Read the base type.
7091 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007092 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007093 case 'v':
7094 assert(HowLong == 0 && !Signed && !Unsigned &&
7095 "Bad modifiers used with 'v'!");
7096 Type = Context.VoidTy;
7097 break;
7098 case 'f':
7099 assert(HowLong == 0 && !Signed && !Unsigned &&
7100 "Bad modifiers used with 'f'!");
7101 Type = Context.FloatTy;
7102 break;
7103 case 'd':
7104 assert(HowLong < 2 && !Signed && !Unsigned &&
7105 "Bad modifiers used with 'd'!");
7106 if (HowLong)
7107 Type = Context.LongDoubleTy;
7108 else
7109 Type = Context.DoubleTy;
7110 break;
7111 case 's':
7112 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7113 if (Unsigned)
7114 Type = Context.UnsignedShortTy;
7115 else
7116 Type = Context.ShortTy;
7117 break;
7118 case 'i':
7119 if (HowLong == 3)
7120 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7121 else if (HowLong == 2)
7122 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7123 else if (HowLong == 1)
7124 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7125 else
7126 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7127 break;
7128 case 'c':
7129 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7130 if (Signed)
7131 Type = Context.SignedCharTy;
7132 else if (Unsigned)
7133 Type = Context.UnsignedCharTy;
7134 else
7135 Type = Context.CharTy;
7136 break;
7137 case 'b': // boolean
7138 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7139 Type = Context.BoolTy;
7140 break;
7141 case 'z': // size_t.
7142 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7143 Type = Context.getSizeType();
7144 break;
7145 case 'F':
7146 Type = Context.getCFConstantStringType();
7147 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007148 case 'G':
7149 Type = Context.getObjCIdType();
7150 break;
7151 case 'H':
7152 Type = Context.getObjCSelType();
7153 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007154 case 'a':
7155 Type = Context.getBuiltinVaListType();
7156 assert(!Type.isNull() && "builtin va list type not initialized!");
7157 break;
7158 case 'A':
7159 // This is a "reference" to a va_list; however, what exactly
7160 // this means depends on how va_list is defined. There are two
7161 // different kinds of va_list: ones passed by value, and ones
7162 // passed by reference. An example of a by-value va_list is
7163 // x86, where va_list is a char*. An example of by-ref va_list
7164 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7165 // we want this argument to be a char*&; for x86-64, we want
7166 // it to be a __va_list_tag*.
7167 Type = Context.getBuiltinVaListType();
7168 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007169 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007170 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007171 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007172 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007173 break;
7174 case 'V': {
7175 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007176 unsigned NumElements = strtoul(Str, &End, 10);
7177 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007178 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007179
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007180 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7181 RequiresICE, false);
7182 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007183
7184 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007185 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007186 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007187 break;
7188 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007189 case 'E': {
7190 char *End;
7191
7192 unsigned NumElements = strtoul(Str, &End, 10);
7193 assert(End != Str && "Missing vector size");
7194
7195 Str = End;
7196
7197 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7198 false);
7199 Type = Context.getExtVectorType(ElementType, NumElements);
7200 break;
7201 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007202 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007203 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7204 false);
7205 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007206 Type = Context.getComplexType(ElementType);
7207 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007208 }
7209 case 'Y' : {
7210 Type = Context.getPointerDiffType();
7211 break;
7212 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007213 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007214 Type = Context.getFILEType();
7215 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007216 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007217 return QualType();
7218 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007219 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007220 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007221 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007222 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007223 else
7224 Type = Context.getjmp_bufType();
7225
Mike Stump2adb4da2009-07-28 23:47:15 +00007226 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007227 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007228 return QualType();
7229 }
7230 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007231 case 'K':
7232 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7233 Type = Context.getucontext_tType();
7234
7235 if (Type.isNull()) {
7236 Error = ASTContext::GE_Missing_ucontext;
7237 return QualType();
7238 }
7239 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007240 }
Mike Stump11289f42009-09-09 15:08:12 +00007241
Chris Lattnerdc226c22010-10-01 22:42:38 +00007242 // If there are modifiers and if we're allowed to parse them, go for it.
7243 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007244 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007245 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007246 default: Done = true; --Str; break;
7247 case '*':
7248 case '&': {
7249 // Both pointers and references can have their pointee types
7250 // qualified with an address space.
7251 char *End;
7252 unsigned AddrSpace = strtoul(Str, &End, 10);
7253 if (End != Str && AddrSpace != 0) {
7254 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7255 Str = End;
7256 }
7257 if (c == '*')
7258 Type = Context.getPointerType(Type);
7259 else
7260 Type = Context.getLValueReferenceType(Type);
7261 break;
7262 }
7263 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7264 case 'C':
7265 Type = Type.withConst();
7266 break;
7267 case 'D':
7268 Type = Context.getVolatileType(Type);
7269 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007270 case 'R':
7271 Type = Type.withRestrict();
7272 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007273 }
7274 }
Chris Lattner84733392010-10-01 07:13:18 +00007275
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007276 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007277 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007278
Chris Lattnerecd79c62009-06-14 00:45:47 +00007279 return Type;
7280}
7281
7282/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007283QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007284 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007285 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007286 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007287
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007288 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007289
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007290 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007291 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007292 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7293 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007294 if (Error != GE_None)
7295 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007296
7297 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7298
Chris Lattnerecd79c62009-06-14 00:45:47 +00007299 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007300 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007301 if (Error != GE_None)
7302 return QualType();
7303
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007304 // If this argument is required to be an IntegerConstantExpression and the
7305 // caller cares, fill in the bitmask we return.
7306 if (RequiresICE && IntegerConstantArgs)
7307 *IntegerConstantArgs |= 1 << ArgTypes.size();
7308
Chris Lattnerecd79c62009-06-14 00:45:47 +00007309 // Do array -> pointer decay. The builtin should use the decayed type.
7310 if (Ty->isArrayType())
7311 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007312
Chris Lattnerecd79c62009-06-14 00:45:47 +00007313 ArgTypes.push_back(Ty);
7314 }
7315
7316 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7317 "'.' should only occur at end of builtin type list!");
7318
John McCall991eb4b2010-12-21 00:44:39 +00007319 FunctionType::ExtInfo EI;
7320 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7321
7322 bool Variadic = (TypeStr[0] == '.');
7323
7324 // We really shouldn't be making a no-proto type here, especially in C++.
7325 if (ArgTypes.empty() && Variadic)
7326 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007327
John McCalldb40c7f2010-12-14 08:05:40 +00007328 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007329 EPI.ExtInfo = EI;
7330 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007331
7332 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007333}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007334
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007335GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7336 GVALinkage External = GVA_StrongExternal;
7337
7338 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007339 switch (L) {
7340 case NoLinkage:
7341 case InternalLinkage:
7342 case UniqueExternalLinkage:
7343 return GVA_Internal;
7344
7345 case ExternalLinkage:
7346 switch (FD->getTemplateSpecializationKind()) {
7347 case TSK_Undeclared:
7348 case TSK_ExplicitSpecialization:
7349 External = GVA_StrongExternal;
7350 break;
7351
7352 case TSK_ExplicitInstantiationDefinition:
7353 return GVA_ExplicitTemplateInstantiation;
7354
7355 case TSK_ExplicitInstantiationDeclaration:
7356 case TSK_ImplicitInstantiation:
7357 External = GVA_TemplateInstantiation;
7358 break;
7359 }
7360 }
7361
7362 if (!FD->isInlined())
7363 return External;
7364
David Blaikiebbafb8a2012-03-11 07:00:24 +00007365 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007366 // GNU or C99 inline semantics. Determine whether this symbol should be
7367 // externally visible.
7368 if (FD->isInlineDefinitionExternallyVisible())
7369 return External;
7370
7371 // C99 inline semantics, where the symbol is not externally visible.
7372 return GVA_C99Inline;
7373 }
7374
7375 // C++0x [temp.explicit]p9:
7376 // [ Note: The intent is that an inline function that is the subject of
7377 // an explicit instantiation declaration will still be implicitly
7378 // instantiated when used so that the body can be considered for
7379 // inlining, but that no out-of-line copy of the inline function would be
7380 // generated in the translation unit. -- end note ]
7381 if (FD->getTemplateSpecializationKind()
7382 == TSK_ExplicitInstantiationDeclaration)
7383 return GVA_C99Inline;
7384
7385 return GVA_CXXInline;
7386}
7387
7388GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7389 // If this is a static data member, compute the kind of template
7390 // specialization. Otherwise, this variable is not part of a
7391 // template.
7392 TemplateSpecializationKind TSK = TSK_Undeclared;
7393 if (VD->isStaticDataMember())
7394 TSK = VD->getTemplateSpecializationKind();
7395
7396 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007397 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007398 VD->getType()->getLinkage() == UniqueExternalLinkage)
7399 L = UniqueExternalLinkage;
7400
7401 switch (L) {
7402 case NoLinkage:
7403 case InternalLinkage:
7404 case UniqueExternalLinkage:
7405 return GVA_Internal;
7406
7407 case ExternalLinkage:
7408 switch (TSK) {
7409 case TSK_Undeclared:
7410 case TSK_ExplicitSpecialization:
7411 return GVA_StrongExternal;
7412
7413 case TSK_ExplicitInstantiationDeclaration:
7414 llvm_unreachable("Variable should not be instantiated");
7415 // Fall through to treat this like any other instantiation.
7416
7417 case TSK_ExplicitInstantiationDefinition:
7418 return GVA_ExplicitTemplateInstantiation;
7419
7420 case TSK_ImplicitInstantiation:
7421 return GVA_TemplateInstantiation;
7422 }
7423 }
7424
David Blaikie8a40f702012-01-17 06:56:22 +00007425 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007426}
7427
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007428bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007429 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7430 if (!VD->isFileVarDecl())
7431 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007432 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007433 return false;
7434
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007435 // Weak references don't produce any output by themselves.
7436 if (D->hasAttr<WeakRefAttr>())
7437 return false;
7438
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007439 // Aliases and used decls are required.
7440 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7441 return true;
7442
7443 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7444 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007445 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007446 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007447
7448 // Constructors and destructors are required.
7449 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7450 return true;
7451
7452 // The key function for a class is required.
7453 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7454 const CXXRecordDecl *RD = MD->getParent();
7455 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7456 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7457 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7458 return true;
7459 }
7460 }
7461
7462 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7463
7464 // static, static inline, always_inline, and extern inline functions can
7465 // always be deferred. Normal inline functions can be deferred in C99/C++.
7466 // Implicit template instantiations can also be deferred in C++.
7467 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007468 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007469 return false;
7470 return true;
7471 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007472
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007473 const VarDecl *VD = cast<VarDecl>(D);
7474 assert(VD->isFileVarDecl() && "Expected file scoped var");
7475
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007476 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7477 return false;
7478
Richard Smitha0e5e542012-11-12 21:38:00 +00007479 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007480 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007481 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7482 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007483
Richard Smitha0e5e542012-11-12 21:38:00 +00007484 // Variables that have destruction with side-effects are required.
7485 if (VD->getType().isDestructedType())
7486 return true;
7487
7488 // Variables that have initialization with side-effects are required.
7489 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7490 return true;
7491
7492 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007493}
Charles Davis53c59df2010-08-16 03:33:14 +00007494
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007495CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007496 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007497 return ABI->getDefaultMethodCallConv(isVariadic);
7498}
7499
7500CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7501 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7502 return CC_Default;
7503 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007504}
7505
Jay Foad39c79802011-01-12 09:06:06 +00007506bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007507 // Pass through to the C++ ABI object
7508 return ABI->isNearlyEmpty(RD);
7509}
7510
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007511MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007512 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007513 case CXXABI_ARM:
7514 case CXXABI_Itanium:
7515 return createItaniumMangleContext(*this, getDiagnostics());
7516 case CXXABI_Microsoft:
7517 return createMicrosoftMangleContext(*this, getDiagnostics());
7518 }
David Blaikie83d382b2011-09-23 05:06:16 +00007519 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007520}
7521
Charles Davis53c59df2010-08-16 03:33:14 +00007522CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007523
7524size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007525 return ASTRecordLayouts.getMemorySize()
7526 + llvm::capacity_in_bytes(ObjCLayouts)
7527 + llvm::capacity_in_bytes(KeyFunctions)
7528 + llvm::capacity_in_bytes(ObjCImpls)
7529 + llvm::capacity_in_bytes(BlockVarCopyInits)
7530 + llvm::capacity_in_bytes(DeclAttrs)
7531 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7532 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7533 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7534 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7535 + llvm::capacity_in_bytes(OverriddenMethods)
7536 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007537 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007538 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007539}
Ted Kremenek540017e2011-10-06 05:00:56 +00007540
David Blaikie095deba2012-11-14 01:52:05 +00007541void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7542 // FIXME: This mangling should be applied to function local classes too
7543 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7544 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7545 return;
7546
7547 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7548 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7549 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7550}
7551
7552int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7553 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7554 UnnamedMangleNumbers.find(Tag);
7555 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7556}
7557
Douglas Gregor63798542012-02-20 19:44:39 +00007558unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7559 CXXRecordDecl *Lambda = CallOperator->getParent();
7560 return LambdaMangleContexts[Lambda->getDeclContext()]
7561 .getManglingNumber(CallOperator);
7562}
7563
7564
Ted Kremenek540017e2011-10-06 05:00:56 +00007565void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7566 ParamIndices[D] = index;
7567}
7568
7569unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7570 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7571 assert(I != ParamIndices.end() &&
7572 "ParmIndices lacks entry set by ParmVarDecl");
7573 return I->second;
7574}