blob: a58eca6a0a4cfa499f691ddf3f75ddc551b8a3c9 [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
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000377comments::FullComment *ASTContext::getCommentForDecl(
378 const Decl *D,
379 const Preprocessor *PP) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000380 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000381
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000382 const Decl *Canonical = D->getCanonicalDecl();
383 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
384 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000385
386 if (Pos != ParsedComments.end()) {
387 if (Canonical != D &&
388 (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D))) {
389 // case of method being redeclaration of the canonical, not
390 // overriding it; i.e. method in implementation, canonical in
391 // interface. Or, out-of-line cxx-method definition.
392 comments::FullComment *FC = Pos->second;
393 comments::FullComment *CFC =
394 new (*this) comments::FullComment(FC->getBlocks(),
395 FC->getThisDeclInfo(),
396 const_cast<Decl *>(D));
397 return CFC;
398 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000399 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000400 }
401
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000402 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000403
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000404 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000405 if (!RC) {
406 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
407 SmallVector<const NamedDecl*, 8> overridden;
408 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D))
409 addRedeclaredMethods(OMD, overridden);
410 const_cast<ASTContext *>(this)->getOverriddenMethods(dyn_cast<NamedDecl>(D),
411 overridden);
412 for (unsigned i = 0, e = overridden.size(); i < e; i++) {
413 if (comments::FullComment *FC = getCommentForDecl(overridden[i], PP)) {
414 comments::FullComment *CFC =
415 new (*this) comments::FullComment(FC->getBlocks(),
416 FC->getThisDeclInfo(),
417 const_cast<Decl *>(D));
418 return CFC;
419 }
420 }
421 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000422 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000423 }
424
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000425 // If the RawComment was attached to other redeclaration of this Decl, we
426 // should parse the comment in context of that other Decl. This is important
427 // because comments can contain references to parameter names which can be
428 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000429 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000430 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000431
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000432 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000433 ParsedComments[Canonical] = FC;
434 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000435}
436
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000437void
438ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
439 TemplateTemplateParmDecl *Parm) {
440 ID.AddInteger(Parm->getDepth());
441 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000442 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000443
444 TemplateParameterList *Params = Parm->getTemplateParameters();
445 ID.AddInteger(Params->size());
446 for (TemplateParameterList::const_iterator P = Params->begin(),
447 PEnd = Params->end();
448 P != PEnd; ++P) {
449 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
450 ID.AddInteger(0);
451 ID.AddBoolean(TTP->isParameterPack());
452 continue;
453 }
454
455 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
456 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000457 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000458 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000459 if (NTTP->isExpandedParameterPack()) {
460 ID.AddBoolean(true);
461 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000462 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
463 QualType T = NTTP->getExpansionType(I);
464 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
465 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000466 } else
467 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000468 continue;
469 }
470
471 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
472 ID.AddInteger(2);
473 Profile(ID, TTP);
474 }
475}
476
477TemplateTemplateParmDecl *
478ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000479 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000480 // Check if we already have a canonical template template parameter.
481 llvm::FoldingSetNodeID ID;
482 CanonicalTemplateTemplateParm::Profile(ID, TTP);
483 void *InsertPos = 0;
484 CanonicalTemplateTemplateParm *Canonical
485 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
486 if (Canonical)
487 return Canonical->getParam();
488
489 // Build a canonical template parameter list.
490 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000491 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000492 CanonParams.reserve(Params->size());
493 for (TemplateParameterList::const_iterator P = Params->begin(),
494 PEnd = Params->end();
495 P != PEnd; ++P) {
496 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
497 CanonParams.push_back(
498 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000499 SourceLocation(),
500 SourceLocation(),
501 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000502 TTP->getIndex(), 0, false,
503 TTP->isParameterPack()));
504 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000505 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
506 QualType T = getCanonicalType(NTTP->getType());
507 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
508 NonTypeTemplateParmDecl *Param;
509 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000510 SmallVector<QualType, 2> ExpandedTypes;
511 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000512 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
513 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
514 ExpandedTInfos.push_back(
515 getTrivialTypeSourceInfo(ExpandedTypes.back()));
516 }
517
518 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000519 SourceLocation(),
520 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000521 NTTP->getDepth(),
522 NTTP->getPosition(), 0,
523 T,
524 TInfo,
525 ExpandedTypes.data(),
526 ExpandedTypes.size(),
527 ExpandedTInfos.data());
528 } else {
529 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000530 SourceLocation(),
531 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000532 NTTP->getDepth(),
533 NTTP->getPosition(), 0,
534 T,
535 NTTP->isParameterPack(),
536 TInfo);
537 }
538 CanonParams.push_back(Param);
539
540 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000541 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
542 cast<TemplateTemplateParmDecl>(*P)));
543 }
544
545 TemplateTemplateParmDecl *CanonTTP
546 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
547 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000548 TTP->getPosition(),
549 TTP->isParameterPack(),
550 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000551 TemplateParameterList::Create(*this, SourceLocation(),
552 SourceLocation(),
553 CanonParams.data(),
554 CanonParams.size(),
555 SourceLocation()));
556
557 // Get the new insert position for the node we care about.
558 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
559 assert(Canonical == 0 && "Shouldn't be in the map!");
560 (void)Canonical;
561
562 // Create the canonical template template parameter entry.
563 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
564 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
565 return CanonTTP;
566}
567
Charles Davis53c59df2010-08-16 03:33:14 +0000568CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000569 if (!LangOpts.CPlusPlus) return 0;
570
Charles Davis6bcb07a2010-08-19 02:18:14 +0000571 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000572 case CXXABI_ARM:
573 return CreateARMCXXABI(*this);
574 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000575 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000576 case CXXABI_Microsoft:
577 return CreateMicrosoftCXXABI(*this);
578 }
David Blaikie8a40f702012-01-17 06:56:22 +0000579 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000580}
581
Douglas Gregore8bbc122011-09-02 00:18:52 +0000582static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000583 const LangOptions &LOpts) {
584 if (LOpts.FakeAddressSpaceMap) {
585 // The fake address space map must have a distinct entry for each
586 // language-specific address space.
587 static const unsigned FakeAddrSpaceMap[] = {
588 1, // opencl_global
589 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000590 3, // opencl_constant
591 4, // cuda_device
592 5, // cuda_constant
593 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000594 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000595 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000596 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000597 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000598 }
599}
600
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000601ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000602 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000603 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000604 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000605 unsigned size_reserve,
606 bool DelayInitialization)
607 : FunctionProtoTypes(this_()),
608 TemplateSpecializationTypes(this_()),
609 DependentTemplateSpecializationTypes(this_()),
610 SubstTemplateTemplateParmPacks(this_()),
611 GlobalNestedNameSpecifier(0),
612 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000613 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000614 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000615 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000616 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000617 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000618 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
619 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
620 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000621 NullTypeSourceInfo(QualType()),
622 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000623 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000624 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000625 Idents(idents), Selectors(sels),
626 BuiltinInfo(builtins),
627 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000628 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000629 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000630 CommentCommandTraits(BumpAlloc),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000631 LastSDM(0, 0),
632 UniqueBlockByRefTypeID(0)
633{
Mike Stump11289f42009-09-09 15:08:12 +0000634 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000635 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000636
637 if (!DelayInitialization) {
638 assert(t && "No target supplied for ASTContext initialization");
639 InitBuiltinTypes(*t);
640 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000641}
642
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000643ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000644 // Release the DenseMaps associated with DeclContext objects.
645 // FIXME: Is this the ideal solution?
646 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000647
Douglas Gregor5b11d492010-07-25 17:53:33 +0000648 // Call all of the deallocation functions.
649 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
650 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000651
Ted Kremenek076baeb2010-06-08 23:00:58 +0000652 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000653 // because they can contain DenseMaps.
654 for (llvm::DenseMap<const ObjCContainerDecl*,
655 const ASTRecordLayout*>::iterator
656 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
657 // Increment in loop to prevent using deallocated memory.
658 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
659 R->Destroy(*this);
660
Ted Kremenek076baeb2010-06-08 23:00:58 +0000661 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
662 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
663 // Increment in loop to prevent using deallocated memory.
664 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
665 R->Destroy(*this);
666 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000667
668 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
669 AEnd = DeclAttrs.end();
670 A != AEnd; ++A)
671 A->second->~AttrVec();
672}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000673
Douglas Gregor1a809332010-05-23 18:26:36 +0000674void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
675 Deallocations.push_back(std::make_pair(Callback, Data));
676}
677
Mike Stump11289f42009-09-09 15:08:12 +0000678void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000679ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000680 ExternalSource.reset(Source.take());
681}
682
Chris Lattner4eb445d2007-01-26 01:27:23 +0000683void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000684 llvm::errs() << "\n*** AST Context Stats:\n";
685 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000686
Douglas Gregora30d0462009-05-26 14:40:08 +0000687 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000688#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000689#define ABSTRACT_TYPE(Name, Parent)
690#include "clang/AST/TypeNodes.def"
691 0 // Extra
692 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000693
Chris Lattner4eb445d2007-01-26 01:27:23 +0000694 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
695 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000696 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000697 }
698
Douglas Gregora30d0462009-05-26 14:40:08 +0000699 unsigned Idx = 0;
700 unsigned TotalBytes = 0;
701#define TYPE(Name, Parent) \
702 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000703 llvm::errs() << " " << counts[Idx] << " " << #Name \
704 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000705 TotalBytes += counts[Idx] * sizeof(Name##Type); \
706 ++Idx;
707#define ABSTRACT_TYPE(Name, Parent)
708#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000709
Chandler Carruth3c147a72011-07-04 05:32:14 +0000710 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
711
Douglas Gregor7454c562010-07-02 20:37:36 +0000712 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000713 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
714 << NumImplicitDefaultConstructors
715 << " implicit default constructors created\n";
716 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
717 << NumImplicitCopyConstructors
718 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000719 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000720 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
721 << NumImplicitMoveConstructors
722 << " implicit move constructors created\n";
723 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
724 << NumImplicitCopyAssignmentOperators
725 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000726 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000727 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
728 << NumImplicitMoveAssignmentOperators
729 << " implicit move assignment operators created\n";
730 llvm::errs() << NumImplicitDestructorsDeclared << "/"
731 << NumImplicitDestructors
732 << " implicit destructors created\n";
733
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000734 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000735 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000736 ExternalSource->PrintStats();
737 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000738
Douglas Gregor5b11d492010-07-25 17:53:33 +0000739 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000740}
741
Douglas Gregor801c99d2011-08-12 06:49:56 +0000742TypedefDecl *ASTContext::getInt128Decl() const {
743 if (!Int128Decl) {
744 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
745 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
746 getTranslationUnitDecl(),
747 SourceLocation(),
748 SourceLocation(),
749 &Idents.get("__int128_t"),
750 TInfo);
751 }
752
753 return Int128Decl;
754}
755
756TypedefDecl *ASTContext::getUInt128Decl() const {
757 if (!UInt128Decl) {
758 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
759 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
760 getTranslationUnitDecl(),
761 SourceLocation(),
762 SourceLocation(),
763 &Idents.get("__uint128_t"),
764 TInfo);
765 }
766
767 return UInt128Decl;
768}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000769
John McCall48f2d582009-10-23 23:03:21 +0000770void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000771 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000772 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000773 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000774}
775
Douglas Gregore8bbc122011-09-02 00:18:52 +0000776void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
777 assert((!this->Target || this->Target == &Target) &&
778 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000779 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000780
Douglas Gregore8bbc122011-09-02 00:18:52 +0000781 this->Target = &Target;
782
783 ABI.reset(createCXXABI(Target));
784 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
785
Chris Lattner970e54e2006-11-12 00:37:36 +0000786 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000787 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000788
Chris Lattner970e54e2006-11-12 00:37:36 +0000789 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000790 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000791 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000792 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000793 InitBuiltinType(CharTy, BuiltinType::Char_S);
794 else
795 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000796 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000797 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
798 InitBuiltinType(ShortTy, BuiltinType::Short);
799 InitBuiltinType(IntTy, BuiltinType::Int);
800 InitBuiltinType(LongTy, BuiltinType::Long);
801 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000802
Chris Lattner970e54e2006-11-12 00:37:36 +0000803 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000804 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
805 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
806 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
807 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
808 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000809
Chris Lattner970e54e2006-11-12 00:37:36 +0000810 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000811 InitBuiltinType(FloatTy, BuiltinType::Float);
812 InitBuiltinType(DoubleTy, BuiltinType::Double);
813 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000814
Chris Lattnerf122cef2009-04-30 02:43:43 +0000815 // GNU extension, 128-bit integers.
816 InitBuiltinType(Int128Ty, BuiltinType::Int128);
817 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
818
Abramo Bagnara06782942012-09-09 10:13:32 +0000819 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000820 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000821 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
822 else // -fshort-wchar makes wchar_t be unsigned.
823 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnara06782942012-09-09 10:13:32 +0000824 } else // C99 (or C++ using -fno-wchar)
Chris Lattner007cb022009-02-26 23:43:47 +0000825 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000826
James Molloy36365542012-05-04 10:55:22 +0000827 WIntTy = getFromTargetType(Target.getWIntType());
828
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000829 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
830 InitBuiltinType(Char16Ty, BuiltinType::Char16);
831 else // C99
832 Char16Ty = getFromTargetType(Target.getChar16Type());
833
834 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
835 InitBuiltinType(Char32Ty, BuiltinType::Char32);
836 else // C99
837 Char32Ty = getFromTargetType(Target.getChar32Type());
838
Douglas Gregor4619e432008-12-05 23:32:09 +0000839 // Placeholder type for type-dependent expressions whose type is
840 // completely unknown. No code should ever check a type against
841 // DependentTy and users should never see it; however, it is here to
842 // help diagnose failures to properly check for type-dependent
843 // expressions.
844 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000845
John McCall36e7fe32010-10-12 00:20:44 +0000846 // Placeholder type for functions.
847 InitBuiltinType(OverloadTy, BuiltinType::Overload);
848
John McCall0009fcc2011-04-26 20:42:42 +0000849 // Placeholder type for bound members.
850 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
851
John McCall526ab472011-10-25 17:37:35 +0000852 // Placeholder type for pseudo-objects.
853 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
854
John McCall31996342011-04-07 08:22:57 +0000855 // "any" type; useful for debugger-like clients.
856 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
857
John McCall8a6b59a2011-10-17 18:09:15 +0000858 // Placeholder type for unbridged ARC casts.
859 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
860
Eli Friedman34866c72012-08-31 00:14:07 +0000861 // Placeholder type for builtin functions.
862 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
863
Chris Lattner970e54e2006-11-12 00:37:36 +0000864 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000865 FloatComplexTy = getComplexType(FloatTy);
866 DoubleComplexTy = getComplexType(DoubleTy);
867 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000868
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000869 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000870 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
871 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000872 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000873
874 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000875 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
876 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000877
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000878 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000879
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000880 // void * type
881 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000882
883 // nullptr type (C++0x 2.14.7)
884 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000885
886 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
887 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000888
889 // Builtin type used to help define __builtin_va_list.
890 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000891}
892
David Blaikie9c902b52011-09-25 23:23:43 +0000893DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000894 return SourceMgr.getDiagnostics();
895}
896
Douglas Gregor561eceb2010-08-30 16:49:28 +0000897AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
898 AttrVec *&Result = DeclAttrs[D];
899 if (!Result) {
900 void *Mem = Allocate(sizeof(AttrVec));
901 Result = new (Mem) AttrVec;
902 }
903
904 return *Result;
905}
906
907/// \brief Erase the attributes corresponding to the given declaration.
908void ASTContext::eraseDeclAttrs(const Decl *D) {
909 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
910 if (Pos != DeclAttrs.end()) {
911 Pos->second->~AttrVec();
912 DeclAttrs.erase(Pos);
913 }
914}
915
Douglas Gregor86d142a2009-10-08 07:24:58 +0000916MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000917ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000918 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000919 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000920 = InstantiatedFromStaticDataMember.find(Var);
921 if (Pos == InstantiatedFromStaticDataMember.end())
922 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000923
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000924 return Pos->second;
925}
926
Mike Stump11289f42009-09-09 15:08:12 +0000927void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000928ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000929 TemplateSpecializationKind TSK,
930 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000931 assert(Inst->isStaticDataMember() && "Not a static data member");
932 assert(Tmpl->isStaticDataMember() && "Not a static data member");
933 assert(!InstantiatedFromStaticDataMember[Inst] &&
934 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000935 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000936 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000937}
938
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000939FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
940 const FunctionDecl *FD){
941 assert(FD && "Specialization is 0");
942 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000943 = ClassScopeSpecializationPattern.find(FD);
944 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000945 return 0;
946
947 return Pos->second;
948}
949
950void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
951 FunctionDecl *Pattern) {
952 assert(FD && "Specialization is 0");
953 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000954 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000955}
956
John McCalle61f2ba2009-11-18 02:36:19 +0000957NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000958ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000959 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000960 = InstantiatedFromUsingDecl.find(UUD);
961 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000962 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000963
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000964 return Pos->second;
965}
966
967void
John McCallb96ec562009-12-04 22:46:56 +0000968ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
969 assert((isa<UsingDecl>(Pattern) ||
970 isa<UnresolvedUsingValueDecl>(Pattern) ||
971 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
972 "pattern decl is not a using decl");
973 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
974 InstantiatedFromUsingDecl[Inst] = Pattern;
975}
976
977UsingShadowDecl *
978ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
979 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
980 = InstantiatedFromUsingShadowDecl.find(Inst);
981 if (Pos == InstantiatedFromUsingShadowDecl.end())
982 return 0;
983
984 return Pos->second;
985}
986
987void
988ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
989 UsingShadowDecl *Pattern) {
990 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
991 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000992}
993
Anders Carlsson5da84842009-09-01 04:26:58 +0000994FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
995 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
996 = InstantiatedFromUnnamedFieldDecl.find(Field);
997 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
998 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000999
Anders Carlsson5da84842009-09-01 04:26:58 +00001000 return Pos->second;
1001}
1002
1003void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1004 FieldDecl *Tmpl) {
1005 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1006 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1007 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1008 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001009
Anders Carlsson5da84842009-09-01 04:26:58 +00001010 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1011}
1012
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001013bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1014 const FieldDecl *LastFD) const {
1015 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001016 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001017}
1018
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001019bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1020 const FieldDecl *LastFD) const {
1021 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001022 FD->getBitWidthValue(*this) == 0 &&
1023 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001024}
1025
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001026bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1027 const FieldDecl *LastFD) const {
1028 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001029 FD->getBitWidthValue(*this) &&
1030 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001031}
1032
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001033bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001034 const FieldDecl *LastFD) const {
1035 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001036 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001037}
1038
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001039bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001040 const FieldDecl *LastFD) const {
1041 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001042 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001043}
1044
Douglas Gregor832940b2010-03-02 23:58:15 +00001045ASTContext::overridden_cxx_method_iterator
1046ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1047 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001048 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001049 if (Pos == OverriddenMethods.end())
1050 return 0;
1051
1052 return Pos->second.begin();
1053}
1054
1055ASTContext::overridden_cxx_method_iterator
1056ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1057 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001058 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001059 if (Pos == OverriddenMethods.end())
1060 return 0;
1061
1062 return Pos->second.end();
1063}
1064
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001065unsigned
1066ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1067 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001068 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001069 if (Pos == OverriddenMethods.end())
1070 return 0;
1071
1072 return Pos->second.size();
1073}
1074
Douglas Gregor832940b2010-03-02 23:58:15 +00001075void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1076 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001077 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001078 OverriddenMethods[Method].push_back(Overridden);
1079}
1080
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001081void ASTContext::getOverriddenMethods(const NamedDecl *D,
1082 SmallVectorImpl<const NamedDecl *> &Overridden) {
1083 assert(D);
1084
1085 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001086 Overridden.append(CXXMethod->begin_overridden_methods(),
1087 CXXMethod->end_overridden_methods());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001088 return;
1089 }
1090
1091 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1092 if (!Method)
1093 return;
1094
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001095 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1096 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001097 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001098}
1099
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001100void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1101 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1102 assert(!Import->isFromASTFile() && "Non-local import declaration");
1103 if (!FirstLocalImport) {
1104 FirstLocalImport = Import;
1105 LastLocalImport = Import;
1106 return;
1107 }
1108
1109 LastLocalImport->NextLocalImport = Import;
1110 LastLocalImport = Import;
1111}
1112
Chris Lattner53cfe802007-07-18 17:52:12 +00001113//===----------------------------------------------------------------------===//
1114// Type Sizing and Analysis
1115//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001116
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001117/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1118/// scalar floating point type.
1119const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001120 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001121 assert(BT && "Not a floating point type!");
1122 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001123 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001124 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001125 case BuiltinType::Float: return Target->getFloatFormat();
1126 case BuiltinType::Double: return Target->getDoubleFormat();
1127 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001128 }
1129}
1130
Ken Dyck160146e2010-01-27 17:10:57 +00001131/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001132/// specified decl. Note that bitfields do not have a valid alignment, so
1133/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001134/// If @p RefAsPointee, references are treated like their underlying type
1135/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001136CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001137 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001138
John McCall94268702010-10-08 18:24:19 +00001139 bool UseAlignAttrOnly = false;
1140 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1141 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001142
John McCall94268702010-10-08 18:24:19 +00001143 // __attribute__((aligned)) can increase or decrease alignment
1144 // *except* on a struct or struct member, where it only increases
1145 // alignment unless 'packed' is also specified.
1146 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001147 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001148 // ignore that possibility; Sema should diagnose it.
1149 if (isa<FieldDecl>(D)) {
1150 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1151 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1152 } else {
1153 UseAlignAttrOnly = true;
1154 }
1155 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001156 else if (isa<FieldDecl>(D))
1157 UseAlignAttrOnly =
1158 D->hasAttr<PackedAttr>() ||
1159 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001160
John McCall4e819612011-01-20 07:57:12 +00001161 // If we're using the align attribute only, just ignore everything
1162 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001163 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001164 // do nothing
1165
John McCall94268702010-10-08 18:24:19 +00001166 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001167 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001168 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001169 if (RefAsPointee)
1170 T = RT->getPointeeType();
1171 else
1172 T = getPointerType(RT->getPointeeType());
1173 }
1174 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001175 // Adjust alignments of declarations with array type by the
1176 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001177 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001178 const ArrayType *arrayType;
1179 if (MinWidth && (arrayType = getAsArrayType(T))) {
1180 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001181 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001182 else if (isa<ConstantArrayType>(arrayType) &&
1183 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001184 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001185
John McCall33ddac02011-01-19 10:06:00 +00001186 // Walk through any array types while we're at it.
1187 T = getBaseElementType(arrayType);
1188 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001189 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001190 }
John McCall4e819612011-01-20 07:57:12 +00001191
1192 // Fields can be subject to extra alignment constraints, like if
1193 // the field is packed, the struct is packed, or the struct has a
1194 // a max-field-alignment constraint (#pragma pack). So calculate
1195 // the actual alignment of the field within the struct, and then
1196 // (as we're expected to) constrain that by the alignment of the type.
1197 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1198 // So calculate the alignment of the field.
1199 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1200
1201 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001202 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001203
1204 // Use the GCD of that and the offset within the record.
1205 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1206 if (offset > 0) {
1207 // Alignment is always a power of 2, so the GCD will be a power of 2,
1208 // which means we get to do this crazy thing instead of Euclid's.
1209 uint64_t lowBitOfOffset = offset & (~offset + 1);
1210 if (lowBitOfOffset < fieldAlign)
1211 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1212 }
1213
1214 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001215 }
Chris Lattner68061312009-01-24 21:53:27 +00001216 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001217
Ken Dyckcc56c542011-01-15 18:38:59 +00001218 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001219}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001220
John McCallf1249922012-08-21 04:10:00 +00001221// getTypeInfoDataSizeInChars - Return the size of a type, in
1222// chars. If the type is a record, its data size is returned. This is
1223// the size of the memcpy that's performed when assigning this type
1224// using a trivial copy/move assignment operator.
1225std::pair<CharUnits, CharUnits>
1226ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1227 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1228
1229 // In C++, objects can sometimes be allocated into the tail padding
1230 // of a base-class subobject. We decide whether that's possible
1231 // during class layout, so here we can just trust the layout results.
1232 if (getLangOpts().CPlusPlus) {
1233 if (const RecordType *RT = T->getAs<RecordType>()) {
1234 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1235 sizeAndAlign.first = layout.getDataSize();
1236 }
1237 }
1238
1239 return sizeAndAlign;
1240}
1241
John McCall87fe5d52010-05-20 01:18:31 +00001242std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001243ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001244 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001245 return std::make_pair(toCharUnitsFromBits(Info.first),
1246 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001247}
1248
1249std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001250ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001251 return getTypeInfoInChars(T.getTypePtr());
1252}
1253
Daniel Dunbarc6475872012-03-09 04:12:54 +00001254std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1255 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1256 if (it != MemoizedTypeInfo.end())
1257 return it->second;
1258
1259 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1260 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1261 return Info;
1262}
1263
1264/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1265/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001266///
1267/// FIXME: Pointers into different addr spaces could have different sizes and
1268/// alignment requirements: getPointerInfo should take an AddrSpace, this
1269/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001270std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001271ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001272 uint64_t Width=0;
1273 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001274 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001275#define TYPE(Class, Base)
1276#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001277#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001278#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1279#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001280 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001281
Chris Lattner355332d2007-07-13 22:27:08 +00001282 case Type::FunctionNoProto:
1283 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001284 // GCC extension: alignof(function) = 32 bits
1285 Width = 0;
1286 Align = 32;
1287 break;
1288
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001289 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001290 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001291 Width = 0;
1292 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1293 break;
1294
Steve Naroff5c131802007-08-30 01:06:46 +00001295 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001296 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001297
Chris Lattner37e05872008-03-05 18:54:05 +00001298 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001299 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001300 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1301 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001302 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001303 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001304 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001305 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001306 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001307 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001308 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001309 const VectorType *VT = cast<VectorType>(T);
1310 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1311 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001312 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001313 // If the alignment is not a power of 2, round up to the next power of 2.
1314 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001315 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001316 Align = llvm::NextPowerOf2(Align);
1317 Width = llvm::RoundUpToAlignment(Width, Align);
1318 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001319 // Adjust the alignment based on the target max.
1320 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1321 if (TargetVectorAlign && TargetVectorAlign < Align)
1322 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001323 break;
1324 }
Chris Lattner647fb222007-07-18 18:26:58 +00001325
Chris Lattner7570e9c2008-03-08 08:52:55 +00001326 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001327 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001328 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001329 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001330 // GCC extension: alignof(void) = 8 bits.
1331 Width = 0;
1332 Align = 8;
1333 break;
1334
Chris Lattner6a4f7452007-12-19 19:23:28 +00001335 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001336 Width = Target->getBoolWidth();
1337 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001338 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001339 case BuiltinType::Char_S:
1340 case BuiltinType::Char_U:
1341 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001342 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001343 Width = Target->getCharWidth();
1344 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001345 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001346 case BuiltinType::WChar_S:
1347 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001348 Width = Target->getWCharWidth();
1349 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001350 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001351 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001352 Width = Target->getChar16Width();
1353 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001354 break;
1355 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001356 Width = Target->getChar32Width();
1357 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001358 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001359 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001360 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001361 Width = Target->getShortWidth();
1362 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001363 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001364 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001365 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001366 Width = Target->getIntWidth();
1367 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001368 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001369 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001370 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001371 Width = Target->getLongWidth();
1372 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001373 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001374 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001375 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001376 Width = Target->getLongLongWidth();
1377 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001378 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001379 case BuiltinType::Int128:
1380 case BuiltinType::UInt128:
1381 Width = 128;
1382 Align = 128; // int128_t is 128-bit aligned on all targets.
1383 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001384 case BuiltinType::Half:
1385 Width = Target->getHalfWidth();
1386 Align = Target->getHalfAlign();
1387 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001388 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001389 Width = Target->getFloatWidth();
1390 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001391 break;
1392 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001393 Width = Target->getDoubleWidth();
1394 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001395 break;
1396 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001397 Width = Target->getLongDoubleWidth();
1398 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001399 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001400 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001401 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1402 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001403 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001404 case BuiltinType::ObjCId:
1405 case BuiltinType::ObjCClass:
1406 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001407 Width = Target->getPointerWidth(0);
1408 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001409 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001410 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001411 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001412 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001413 Width = Target->getPointerWidth(0);
1414 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001415 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001416 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001417 unsigned AS = getTargetAddressSpace(
1418 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001419 Width = Target->getPointerWidth(AS);
1420 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001421 break;
1422 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001423 case Type::LValueReference:
1424 case Type::RValueReference: {
1425 // alignof and sizeof should never enter this code path here, so we go
1426 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001427 unsigned AS = getTargetAddressSpace(
1428 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001429 Width = Target->getPointerWidth(AS);
1430 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001431 break;
1432 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001433 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001434 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001435 Width = Target->getPointerWidth(AS);
1436 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001437 break;
1438 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001439 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001440 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001441 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001442 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001443 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001444 Align = PtrDiffInfo.second;
1445 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001446 }
Chris Lattner647fb222007-07-18 18:26:58 +00001447 case Type::Complex: {
1448 // Complex types have the same alignment as their elements, but twice the
1449 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001450 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001451 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001452 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001453 Align = EltInfo.second;
1454 break;
1455 }
John McCall8b07ec22010-05-15 11:32:37 +00001456 case Type::ObjCObject:
1457 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001458 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001459 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001460 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001461 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001462 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001463 break;
1464 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001465 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001466 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001467 const TagType *TT = cast<TagType>(T);
1468
1469 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001470 Width = 8;
1471 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001472 break;
1473 }
Mike Stump11289f42009-09-09 15:08:12 +00001474
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001475 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001476 return getTypeInfo(ET->getDecl()->getIntegerType());
1477
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001478 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001479 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001480 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001481 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001482 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001483 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001484
Chris Lattner63d2b362009-10-22 05:17:15 +00001485 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001486 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1487 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001488
Richard Smith30482bc2011-02-20 03:19:35 +00001489 case Type::Auto: {
1490 const AutoType *A = cast<AutoType>(T);
1491 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001492 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001493 }
1494
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001495 case Type::Paren:
1496 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1497
Douglas Gregoref462e62009-04-30 17:32:17 +00001498 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001499 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001500 std::pair<uint64_t, unsigned> Info
1501 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001502 // If the typedef has an aligned attribute on it, it overrides any computed
1503 // alignment we have. This violates the GCC documentation (which says that
1504 // attribute(aligned) can only round up) but matches its implementation.
1505 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1506 Align = AttrAlign;
1507 else
1508 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001509 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001510 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001511 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001512
1513 case Type::TypeOfExpr:
1514 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1515 .getTypePtr());
1516
1517 case Type::TypeOf:
1518 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1519
Anders Carlsson81df7b82009-06-24 19:06:50 +00001520 case Type::Decltype:
1521 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1522 .getTypePtr());
1523
Alexis Hunte852b102011-05-24 22:41:36 +00001524 case Type::UnaryTransform:
1525 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1526
Abramo Bagnara6150c882010-05-11 21:36:43 +00001527 case Type::Elaborated:
1528 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001529
John McCall81904512011-01-06 01:58:22 +00001530 case Type::Attributed:
1531 return getTypeInfo(
1532 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1533
Richard Smith3f1b5d02011-05-05 21:57:07 +00001534 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001535 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001536 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001537 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1538 // A type alias template specialization may refer to a typedef with the
1539 // aligned attribute on it.
1540 if (TST->isTypeAlias())
1541 return getTypeInfo(TST->getAliasedType().getTypePtr());
1542 else
1543 return getTypeInfo(getCanonicalType(T));
1544 }
1545
Eli Friedman0dfb8892011-10-06 23:00:33 +00001546 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001547 std::pair<uint64_t, unsigned> Info
1548 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1549 Width = Info.first;
1550 Align = Info.second;
1551 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1552 llvm::isPowerOf2_64(Width)) {
1553 // We can potentially perform lock-free atomic operations for this
1554 // type; promote the alignment appropriately.
1555 // FIXME: We could potentially promote the width here as well...
1556 // is that worthwhile? (Non-struct atomic types generally have
1557 // power-of-two size anyway, but structs might not. Requires a bit
1558 // of implementation work to make sure we zero out the extra bits.)
1559 Align = static_cast<unsigned>(Width);
1560 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001561 }
1562
Douglas Gregoref462e62009-04-30 17:32:17 +00001563 }
Mike Stump11289f42009-09-09 15:08:12 +00001564
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001565 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001566 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001567}
1568
Ken Dyckcc56c542011-01-15 18:38:59 +00001569/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1570CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1571 return CharUnits::fromQuantity(BitSize / getCharWidth());
1572}
1573
Ken Dyckb0fcc592011-02-11 01:54:29 +00001574/// toBits - Convert a size in characters to a size in characters.
1575int64_t ASTContext::toBits(CharUnits CharSize) const {
1576 return CharSize.getQuantity() * getCharWidth();
1577}
1578
Ken Dyck8c89d592009-12-22 14:23:30 +00001579/// getTypeSizeInChars - Return the size of the specified type, in characters.
1580/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001581CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001582 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001583}
Jay Foad39c79802011-01-12 09:06:06 +00001584CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001585 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001586}
1587
Ken Dycka6046ab2010-01-26 17:25:18 +00001588/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001589/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001590CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001591 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001592}
Jay Foad39c79802011-01-12 09:06:06 +00001593CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001594 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001595}
1596
Chris Lattnera3402cd2009-01-27 18:08:34 +00001597/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1598/// type for the current target in bits. This can be different than the ABI
1599/// alignment in cases where it is beneficial for performance to overalign
1600/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001601unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001602 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001603
1604 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001605 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001606 T = CT->getElementType().getTypePtr();
1607 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001608 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1609 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001610 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1611
Chris Lattnera3402cd2009-01-27 18:08:34 +00001612 return ABIAlign;
1613}
1614
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001615/// DeepCollectObjCIvars -
1616/// This routine first collects all declared, but not synthesized, ivars in
1617/// super class and then collects all ivars, including those synthesized for
1618/// current class. This routine is used for implementation of current class
1619/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001620///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001621void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1622 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001623 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001624 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1625 DeepCollectObjCIvars(SuperClass, false, Ivars);
1626 if (!leafClass) {
1627 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1628 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001629 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001630 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001631 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001632 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001633 Iv= Iv->getNextIvar())
1634 Ivars.push_back(Iv);
1635 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001636}
1637
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001638/// CollectInheritedProtocols - Collect all protocols in current class and
1639/// those inherited by it.
1640void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001641 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001642 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001643 // We can use protocol_iterator here instead of
1644 // all_referenced_protocol_iterator since we are walking all categories.
1645 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1646 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001647 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001648 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001649 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001650 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001651 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001652 CollectInheritedProtocols(*P, Protocols);
1653 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001654 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001655
1656 // Categories of this Interface.
1657 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1658 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1659 CollectInheritedProtocols(CDeclChain, Protocols);
1660 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1661 while (SD) {
1662 CollectInheritedProtocols(SD, Protocols);
1663 SD = SD->getSuperClass();
1664 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001665 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001666 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001667 PE = OC->protocol_end(); P != PE; ++P) {
1668 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001669 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001670 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1671 PE = Proto->protocol_end(); P != PE; ++P)
1672 CollectInheritedProtocols(*P, Protocols);
1673 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001674 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001675 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1676 PE = OP->protocol_end(); P != PE; ++P) {
1677 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001678 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001679 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1680 PE = Proto->protocol_end(); P != PE; ++P)
1681 CollectInheritedProtocols(*P, Protocols);
1682 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001683 }
1684}
1685
Jay Foad39c79802011-01-12 09:06:06 +00001686unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001687 unsigned count = 0;
1688 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001689 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1690 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001691 count += CDecl->ivar_size();
1692
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001693 // Count ivar defined in this class's implementation. This
1694 // includes synthesized ivars.
1695 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001696 count += ImplDecl->ivar_size();
1697
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001698 return count;
1699}
1700
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001701bool ASTContext::isSentinelNullExpr(const Expr *E) {
1702 if (!E)
1703 return false;
1704
1705 // nullptr_t is always treated as null.
1706 if (E->getType()->isNullPtrType()) return true;
1707
1708 if (E->getType()->isAnyPointerType() &&
1709 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1710 Expr::NPC_ValueDependentIsNull))
1711 return true;
1712
1713 // Unfortunately, __null has type 'int'.
1714 if (isa<GNUNullExpr>(E)) return true;
1715
1716 return false;
1717}
1718
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001719/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1720ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1721 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1722 I = ObjCImpls.find(D);
1723 if (I != ObjCImpls.end())
1724 return cast<ObjCImplementationDecl>(I->second);
1725 return 0;
1726}
1727/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1728ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1729 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1730 I = ObjCImpls.find(D);
1731 if (I != ObjCImpls.end())
1732 return cast<ObjCCategoryImplDecl>(I->second);
1733 return 0;
1734}
1735
1736/// \brief Set the implementation of ObjCInterfaceDecl.
1737void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1738 ObjCImplementationDecl *ImplD) {
1739 assert(IFaceD && ImplD && "Passed null params");
1740 ObjCImpls[IFaceD] = ImplD;
1741}
1742/// \brief Set the implementation of ObjCCategoryDecl.
1743void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1744 ObjCCategoryImplDecl *ImplD) {
1745 assert(CatD && ImplD && "Passed null params");
1746 ObjCImpls[CatD] = ImplD;
1747}
1748
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001749ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1750 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1751 return ID;
1752 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1753 return CD->getClassInterface();
1754 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1755 return IMD->getClassInterface();
1756
1757 return 0;
1758}
1759
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001760/// \brief Get the copy initialization expression of VarDecl,or NULL if
1761/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001762Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001763 assert(VD && "Passed null params");
1764 assert(VD->hasAttr<BlocksAttr>() &&
1765 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001766 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001767 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001768 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1769}
1770
1771/// \brief Set the copy inialization expression of a block var decl.
1772void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1773 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001774 assert(VD->hasAttr<BlocksAttr>() &&
1775 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001776 BlockVarCopyInits[VD] = Init;
1777}
1778
John McCallbcd03502009-12-07 02:54:59 +00001779TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001780 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001781 if (!DataSize)
1782 DataSize = TypeLoc::getFullDataSizeForType(T);
1783 else
1784 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001785 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001786
John McCallbcd03502009-12-07 02:54:59 +00001787 TypeSourceInfo *TInfo =
1788 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1789 new (TInfo) TypeSourceInfo(T);
1790 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001791}
1792
John McCallbcd03502009-12-07 02:54:59 +00001793TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001794 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001795 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001796 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001797 return DI;
1798}
1799
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001800const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001801ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001802 return getObjCLayout(D, 0);
1803}
1804
1805const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001806ASTContext::getASTObjCImplementationLayout(
1807 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001808 return getObjCLayout(D->getClassInterface(), D);
1809}
1810
Chris Lattner983a8bb2007-07-13 22:13:22 +00001811//===----------------------------------------------------------------------===//
1812// Type creation/memoization methods
1813//===----------------------------------------------------------------------===//
1814
Jay Foad39c79802011-01-12 09:06:06 +00001815QualType
John McCall33ddac02011-01-19 10:06:00 +00001816ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1817 unsigned fastQuals = quals.getFastQualifiers();
1818 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001819
1820 // Check if we've already instantiated this type.
1821 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001822 ExtQuals::Profile(ID, baseType, quals);
1823 void *insertPos = 0;
1824 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1825 assert(eq->getQualifiers() == quals);
1826 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001827 }
1828
John McCall33ddac02011-01-19 10:06:00 +00001829 // If the base type is not canonical, make the appropriate canonical type.
1830 QualType canon;
1831 if (!baseType->isCanonicalUnqualified()) {
1832 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001833 canonSplit.Quals.addConsistentQualifiers(quals);
1834 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001835
1836 // Re-find the insert position.
1837 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1838 }
1839
1840 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1841 ExtQualNodes.InsertNode(eq, insertPos);
1842 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001843}
1844
Jay Foad39c79802011-01-12 09:06:06 +00001845QualType
1846ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001847 QualType CanT = getCanonicalType(T);
1848 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001849 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001850
John McCall8ccfcb52009-09-24 19:53:00 +00001851 // If we are composing extended qualifiers together, merge together
1852 // into one ExtQuals node.
1853 QualifierCollector Quals;
1854 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001855
John McCall8ccfcb52009-09-24 19:53:00 +00001856 // If this type already has an address space specified, it cannot get
1857 // another one.
1858 assert(!Quals.hasAddressSpace() &&
1859 "Type cannot be in multiple addr spaces!");
1860 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001861
John McCall8ccfcb52009-09-24 19:53:00 +00001862 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001863}
1864
Chris Lattnerd60183d2009-02-18 22:53:11 +00001865QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001866 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001867 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001868 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001869 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001870
John McCall53fa7142010-12-24 02:08:15 +00001871 if (const PointerType *ptr = T->getAs<PointerType>()) {
1872 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001873 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001874 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1875 return getPointerType(ResultType);
1876 }
1877 }
Mike Stump11289f42009-09-09 15:08:12 +00001878
John McCall8ccfcb52009-09-24 19:53:00 +00001879 // If we are composing extended qualifiers together, merge together
1880 // into one ExtQuals node.
1881 QualifierCollector Quals;
1882 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001883
John McCall8ccfcb52009-09-24 19:53:00 +00001884 // If this type already has an ObjCGC specified, it cannot get
1885 // another one.
1886 assert(!Quals.hasObjCGCAttr() &&
1887 "Type cannot have multiple ObjCGCs!");
1888 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001889
John McCall8ccfcb52009-09-24 19:53:00 +00001890 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001891}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001892
John McCall4f5019e2010-12-19 02:44:49 +00001893const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1894 FunctionType::ExtInfo Info) {
1895 if (T->getExtInfo() == Info)
1896 return T;
1897
1898 QualType Result;
1899 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1900 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1901 } else {
1902 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1903 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1904 EPI.ExtInfo = Info;
1905 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1906 FPT->getNumArgs(), EPI);
1907 }
1908
1909 return cast<FunctionType>(Result.getTypePtr());
1910}
1911
Chris Lattnerc6395932007-06-22 20:56:16 +00001912/// getComplexType - Return the uniqued reference to the type for a complex
1913/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001914QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001915 // Unique pointers, to guarantee there is only one pointer of a particular
1916 // structure.
1917 llvm::FoldingSetNodeID ID;
1918 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001919
Chris Lattnerc6395932007-06-22 20:56:16 +00001920 void *InsertPos = 0;
1921 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1922 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001923
Chris Lattnerc6395932007-06-22 20:56:16 +00001924 // If the pointee type isn't canonical, this won't be a canonical type either,
1925 // so fill in the canonical type field.
1926 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001927 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001928 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001929
Chris Lattnerc6395932007-06-22 20:56:16 +00001930 // Get the new insert position for the node we care about.
1931 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001932 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001933 }
John McCall90d1c2d2009-09-24 23:30:46 +00001934 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001935 Types.push_back(New);
1936 ComplexTypes.InsertNode(New, InsertPos);
1937 return QualType(New, 0);
1938}
1939
Chris Lattner970e54e2006-11-12 00:37:36 +00001940/// getPointerType - Return the uniqued reference to the type for a pointer to
1941/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001942QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001943 // Unique pointers, to guarantee there is only one pointer of a particular
1944 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001945 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001946 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001947
Chris Lattner67521df2007-01-27 01:29:36 +00001948 void *InsertPos = 0;
1949 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001950 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001951
Chris Lattner7ccecb92006-11-12 08:50:50 +00001952 // If the pointee type isn't canonical, this won't be a canonical type either,
1953 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001954 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001955 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001956 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001957
Chris Lattner67521df2007-01-27 01:29:36 +00001958 // Get the new insert position for the node we care about.
1959 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001960 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001961 }
John McCall90d1c2d2009-09-24 23:30:46 +00001962 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001963 Types.push_back(New);
1964 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001965 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001966}
1967
Mike Stump11289f42009-09-09 15:08:12 +00001968/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001969/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001970QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001971 assert(T->isFunctionType() && "block of function types only");
1972 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001973 // structure.
1974 llvm::FoldingSetNodeID ID;
1975 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001976
Steve Naroffec33ed92008-08-27 16:04:49 +00001977 void *InsertPos = 0;
1978 if (BlockPointerType *PT =
1979 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1980 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001981
1982 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001983 // type either so fill in the canonical type field.
1984 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001985 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001986 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001987
Steve Naroffec33ed92008-08-27 16:04:49 +00001988 // Get the new insert position for the node we care about.
1989 BlockPointerType *NewIP =
1990 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001991 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001992 }
John McCall90d1c2d2009-09-24 23:30:46 +00001993 BlockPointerType *New
1994 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001995 Types.push_back(New);
1996 BlockPointerTypes.InsertNode(New, InsertPos);
1997 return QualType(New, 0);
1998}
1999
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002000/// getLValueReferenceType - Return the uniqued reference to the type for an
2001/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002002QualType
2003ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002004 assert(getCanonicalType(T) != OverloadTy &&
2005 "Unresolved overloaded function type");
2006
Bill Wendling3708c182007-05-27 10:15:43 +00002007 // Unique pointers, to guarantee there is only one pointer of a particular
2008 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002009 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002010 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002011
2012 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002013 if (LValueReferenceType *RT =
2014 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002015 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002016
John McCallfc93cf92009-10-22 22:37:11 +00002017 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2018
Bill Wendling3708c182007-05-27 10:15:43 +00002019 // If the referencee type isn't canonical, this won't be a canonical type
2020 // either, so fill in the canonical type field.
2021 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002022 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2023 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2024 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002025
Bill Wendling3708c182007-05-27 10:15:43 +00002026 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002027 LValueReferenceType *NewIP =
2028 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002029 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002030 }
2031
John McCall90d1c2d2009-09-24 23:30:46 +00002032 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002033 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2034 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002035 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002036 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002037
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002038 return QualType(New, 0);
2039}
2040
2041/// getRValueReferenceType - Return the uniqued reference to the type for an
2042/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002043QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002044 // Unique pointers, to guarantee there is only one pointer of a particular
2045 // structure.
2046 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002047 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002048
2049 void *InsertPos = 0;
2050 if (RValueReferenceType *RT =
2051 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2052 return QualType(RT, 0);
2053
John McCallfc93cf92009-10-22 22:37:11 +00002054 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2055
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002056 // If the referencee type isn't canonical, this won't be a canonical type
2057 // either, so fill in the canonical type field.
2058 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002059 if (InnerRef || !T.isCanonical()) {
2060 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2061 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002062
2063 // Get the new insert position for the node we care about.
2064 RValueReferenceType *NewIP =
2065 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002066 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002067 }
2068
John McCall90d1c2d2009-09-24 23:30:46 +00002069 RValueReferenceType *New
2070 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002071 Types.push_back(New);
2072 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002073 return QualType(New, 0);
2074}
2075
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002076/// getMemberPointerType - Return the uniqued reference to the type for a
2077/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002078QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002079 // Unique pointers, to guarantee there is only one pointer of a particular
2080 // structure.
2081 llvm::FoldingSetNodeID ID;
2082 MemberPointerType::Profile(ID, T, Cls);
2083
2084 void *InsertPos = 0;
2085 if (MemberPointerType *PT =
2086 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2087 return QualType(PT, 0);
2088
2089 // If the pointee or class type isn't canonical, this won't be a canonical
2090 // type either, so fill in the canonical type field.
2091 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002092 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002093 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2094
2095 // Get the new insert position for the node we care about.
2096 MemberPointerType *NewIP =
2097 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002098 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002099 }
John McCall90d1c2d2009-09-24 23:30:46 +00002100 MemberPointerType *New
2101 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002102 Types.push_back(New);
2103 MemberPointerTypes.InsertNode(New, InsertPos);
2104 return QualType(New, 0);
2105}
2106
Mike Stump11289f42009-09-09 15:08:12 +00002107/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002108/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002109QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002110 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002111 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002112 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002113 assert((EltTy->isDependentType() ||
2114 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002115 "Constant array of VLAs is illegal!");
2116
Chris Lattnere2df3f92009-05-13 04:12:56 +00002117 // Convert the array size into a canonical width matching the pointer size for
2118 // the target.
2119 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002120 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002121 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002122
Chris Lattner23b7eb62007-06-15 23:05:46 +00002123 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002124 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002125
Chris Lattner36f8e652007-01-27 08:31:04 +00002126 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002127 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002128 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002129 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002130
John McCall33ddac02011-01-19 10:06:00 +00002131 // If the element type isn't canonical or has qualifiers, this won't
2132 // be a canonical type either, so fill in the canonical type field.
2133 QualType Canon;
2134 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2135 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002136 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002137 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002138 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002139
Chris Lattner36f8e652007-01-27 08:31:04 +00002140 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002141 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002142 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002143 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002144 }
Mike Stump11289f42009-09-09 15:08:12 +00002145
John McCall90d1c2d2009-09-24 23:30:46 +00002146 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002147 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002148 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002149 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002150 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002151}
2152
John McCall06549462011-01-18 08:40:38 +00002153/// getVariableArrayDecayedType - Turns the given type, which may be
2154/// variably-modified, into the corresponding type with all the known
2155/// sizes replaced with [*].
2156QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2157 // Vastly most common case.
2158 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002159
John McCall06549462011-01-18 08:40:38 +00002160 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002161
John McCall06549462011-01-18 08:40:38 +00002162 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002163 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002164 switch (ty->getTypeClass()) {
2165#define TYPE(Class, Base)
2166#define ABSTRACT_TYPE(Class, Base)
2167#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2168#include "clang/AST/TypeNodes.def"
2169 llvm_unreachable("didn't desugar past all non-canonical types?");
2170
2171 // These types should never be variably-modified.
2172 case Type::Builtin:
2173 case Type::Complex:
2174 case Type::Vector:
2175 case Type::ExtVector:
2176 case Type::DependentSizedExtVector:
2177 case Type::ObjCObject:
2178 case Type::ObjCInterface:
2179 case Type::ObjCObjectPointer:
2180 case Type::Record:
2181 case Type::Enum:
2182 case Type::UnresolvedUsing:
2183 case Type::TypeOfExpr:
2184 case Type::TypeOf:
2185 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002186 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002187 case Type::DependentName:
2188 case Type::InjectedClassName:
2189 case Type::TemplateSpecialization:
2190 case Type::DependentTemplateSpecialization:
2191 case Type::TemplateTypeParm:
2192 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002193 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002194 case Type::PackExpansion:
2195 llvm_unreachable("type should never be variably-modified");
2196
2197 // These types can be variably-modified but should never need to
2198 // further decay.
2199 case Type::FunctionNoProto:
2200 case Type::FunctionProto:
2201 case Type::BlockPointer:
2202 case Type::MemberPointer:
2203 return type;
2204
2205 // These types can be variably-modified. All these modifications
2206 // preserve structure except as noted by comments.
2207 // TODO: if we ever care about optimizing VLAs, there are no-op
2208 // optimizations available here.
2209 case Type::Pointer:
2210 result = getPointerType(getVariableArrayDecayedType(
2211 cast<PointerType>(ty)->getPointeeType()));
2212 break;
2213
2214 case Type::LValueReference: {
2215 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2216 result = getLValueReferenceType(
2217 getVariableArrayDecayedType(lv->getPointeeType()),
2218 lv->isSpelledAsLValue());
2219 break;
2220 }
2221
2222 case Type::RValueReference: {
2223 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2224 result = getRValueReferenceType(
2225 getVariableArrayDecayedType(lv->getPointeeType()));
2226 break;
2227 }
2228
Eli Friedman0dfb8892011-10-06 23:00:33 +00002229 case Type::Atomic: {
2230 const AtomicType *at = cast<AtomicType>(ty);
2231 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2232 break;
2233 }
2234
John McCall06549462011-01-18 08:40:38 +00002235 case Type::ConstantArray: {
2236 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2237 result = getConstantArrayType(
2238 getVariableArrayDecayedType(cat->getElementType()),
2239 cat->getSize(),
2240 cat->getSizeModifier(),
2241 cat->getIndexTypeCVRQualifiers());
2242 break;
2243 }
2244
2245 case Type::DependentSizedArray: {
2246 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2247 result = getDependentSizedArrayType(
2248 getVariableArrayDecayedType(dat->getElementType()),
2249 dat->getSizeExpr(),
2250 dat->getSizeModifier(),
2251 dat->getIndexTypeCVRQualifiers(),
2252 dat->getBracketsRange());
2253 break;
2254 }
2255
2256 // Turn incomplete types into [*] types.
2257 case Type::IncompleteArray: {
2258 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2259 result = getVariableArrayType(
2260 getVariableArrayDecayedType(iat->getElementType()),
2261 /*size*/ 0,
2262 ArrayType::Normal,
2263 iat->getIndexTypeCVRQualifiers(),
2264 SourceRange());
2265 break;
2266 }
2267
2268 // Turn VLA types into [*] types.
2269 case Type::VariableArray: {
2270 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2271 result = getVariableArrayType(
2272 getVariableArrayDecayedType(vat->getElementType()),
2273 /*size*/ 0,
2274 ArrayType::Star,
2275 vat->getIndexTypeCVRQualifiers(),
2276 vat->getBracketsRange());
2277 break;
2278 }
2279 }
2280
2281 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002282 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002283}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002284
Steve Naroffcadebd02007-08-30 18:14:25 +00002285/// getVariableArrayType - Returns a non-unique reference to the type for a
2286/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002287QualType ASTContext::getVariableArrayType(QualType EltTy,
2288 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002289 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002290 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002291 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002292 // Since we don't unique expressions, it isn't possible to unique VLA's
2293 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002294 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002295
John McCall33ddac02011-01-19 10:06:00 +00002296 // Be sure to pull qualifiers off the element type.
2297 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2298 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002299 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002300 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002301 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002302 }
2303
John McCall90d1c2d2009-09-24 23:30:46 +00002304 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002305 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002306
2307 VariableArrayTypes.push_back(New);
2308 Types.push_back(New);
2309 return QualType(New, 0);
2310}
2311
Douglas Gregor4619e432008-12-05 23:32:09 +00002312/// getDependentSizedArrayType - Returns a non-unique reference to
2313/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002314/// type.
John McCall33ddac02011-01-19 10:06:00 +00002315QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2316 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002317 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002318 unsigned elementTypeQuals,
2319 SourceRange brackets) const {
2320 assert((!numElements || numElements->isTypeDependent() ||
2321 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002322 "Size must be type- or value-dependent!");
2323
John McCall33ddac02011-01-19 10:06:00 +00002324 // Dependently-sized array types that do not have a specified number
2325 // of elements will have their sizes deduced from a dependent
2326 // initializer. We do no canonicalization here at all, which is okay
2327 // because they can't be used in most locations.
2328 if (!numElements) {
2329 DependentSizedArrayType *newType
2330 = new (*this, TypeAlignment)
2331 DependentSizedArrayType(*this, elementType, QualType(),
2332 numElements, ASM, elementTypeQuals,
2333 brackets);
2334 Types.push_back(newType);
2335 return QualType(newType, 0);
2336 }
2337
2338 // Otherwise, we actually build a new type every time, but we
2339 // also build a canonical type.
2340
2341 SplitQualType canonElementType = getCanonicalType(elementType).split();
2342
2343 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002344 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002345 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002346 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002347 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002348
John McCall33ddac02011-01-19 10:06:00 +00002349 // Look for an existing type with these properties.
2350 DependentSizedArrayType *canonTy =
2351 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002352
John McCall33ddac02011-01-19 10:06:00 +00002353 // If we don't have one, build one.
2354 if (!canonTy) {
2355 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002356 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002357 QualType(), numElements, ASM, elementTypeQuals,
2358 brackets);
2359 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2360 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002361 }
2362
John McCall33ddac02011-01-19 10:06:00 +00002363 // Apply qualifiers from the element type to the array.
2364 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002365 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002366
John McCall33ddac02011-01-19 10:06:00 +00002367 // If we didn't need extra canonicalization for the element type,
2368 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002369 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002370 return canon;
2371
2372 // Otherwise, we need to build a type which follows the spelling
2373 // of the element type.
2374 DependentSizedArrayType *sugaredType
2375 = new (*this, TypeAlignment)
2376 DependentSizedArrayType(*this, elementType, canon, numElements,
2377 ASM, elementTypeQuals, brackets);
2378 Types.push_back(sugaredType);
2379 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002380}
2381
John McCall33ddac02011-01-19 10:06:00 +00002382QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002383 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002384 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002385 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002386 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002387
John McCall33ddac02011-01-19 10:06:00 +00002388 void *insertPos = 0;
2389 if (IncompleteArrayType *iat =
2390 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2391 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002392
2393 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002394 // either, so fill in the canonical type field. We also have to pull
2395 // qualifiers off the element type.
2396 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002397
John McCall33ddac02011-01-19 10:06:00 +00002398 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2399 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002400 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002401 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002402 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002403
2404 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002405 IncompleteArrayType *existing =
2406 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2407 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002408 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002409
John McCall33ddac02011-01-19 10:06:00 +00002410 IncompleteArrayType *newType = new (*this, TypeAlignment)
2411 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002412
John McCall33ddac02011-01-19 10:06:00 +00002413 IncompleteArrayTypes.InsertNode(newType, insertPos);
2414 Types.push_back(newType);
2415 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002416}
2417
Steve Naroff91fcddb2007-07-18 18:00:27 +00002418/// getVectorType - Return the unique reference to a vector type of
2419/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002420QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002421 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002422 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002423
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002424 // Check if we've already instantiated a vector of this type.
2425 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002426 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002427
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002428 void *InsertPos = 0;
2429 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2430 return QualType(VTP, 0);
2431
2432 // If the element type isn't canonical, this won't be a canonical type either,
2433 // so fill in the canonical type field.
2434 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002435 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002436 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002437
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002438 // Get the new insert position for the node we care about.
2439 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002440 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002441 }
John McCall90d1c2d2009-09-24 23:30:46 +00002442 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002443 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002444 VectorTypes.InsertNode(New, InsertPos);
2445 Types.push_back(New);
2446 return QualType(New, 0);
2447}
2448
Nate Begemance4d7fc2008-04-18 23:10:10 +00002449/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002450/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002451QualType
2452ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002453 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002454
Steve Naroff91fcddb2007-07-18 18:00:27 +00002455 // Check if we've already instantiated a vector of this type.
2456 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002457 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002458 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002459 void *InsertPos = 0;
2460 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2461 return QualType(VTP, 0);
2462
2463 // If the element type isn't canonical, this won't be a canonical type either,
2464 // so fill in the canonical type field.
2465 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002466 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002467 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002468
Steve Naroff91fcddb2007-07-18 18:00:27 +00002469 // Get the new insert position for the node we care about.
2470 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002471 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002472 }
John McCall90d1c2d2009-09-24 23:30:46 +00002473 ExtVectorType *New = new (*this, TypeAlignment)
2474 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002475 VectorTypes.InsertNode(New, InsertPos);
2476 Types.push_back(New);
2477 return QualType(New, 0);
2478}
2479
Jay Foad39c79802011-01-12 09:06:06 +00002480QualType
2481ASTContext::getDependentSizedExtVectorType(QualType vecType,
2482 Expr *SizeExpr,
2483 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002484 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002485 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002486 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002487
Douglas Gregor352169a2009-07-31 03:54:25 +00002488 void *InsertPos = 0;
2489 DependentSizedExtVectorType *Canon
2490 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2491 DependentSizedExtVectorType *New;
2492 if (Canon) {
2493 // We already have a canonical version of this array type; use it as
2494 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002495 New = new (*this, TypeAlignment)
2496 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2497 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002498 } else {
2499 QualType CanonVecTy = getCanonicalType(vecType);
2500 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002501 New = new (*this, TypeAlignment)
2502 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2503 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002504
2505 DependentSizedExtVectorType *CanonCheck
2506 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2507 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2508 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002509 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2510 } else {
2511 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2512 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002513 New = new (*this, TypeAlignment)
2514 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002515 }
2516 }
Mike Stump11289f42009-09-09 15:08:12 +00002517
Douglas Gregor758a8692009-06-17 21:51:59 +00002518 Types.push_back(New);
2519 return QualType(New, 0);
2520}
2521
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002522/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002523///
Jay Foad39c79802011-01-12 09:06:06 +00002524QualType
2525ASTContext::getFunctionNoProtoType(QualType ResultTy,
2526 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002527 const CallingConv DefaultCC = Info.getCC();
2528 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2529 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002530 // Unique functions, to guarantee there is only one function of a particular
2531 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002532 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002533 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002534
Chris Lattner47955de2007-01-27 08:37:20 +00002535 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002536 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002537 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002538 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002539
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002540 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002541 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002542 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002543 Canonical =
2544 getFunctionNoProtoType(getCanonicalType(ResultTy),
2545 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002546
Chris Lattner47955de2007-01-27 08:37:20 +00002547 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002548 FunctionNoProtoType *NewIP =
2549 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002550 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002551 }
Mike Stump11289f42009-09-09 15:08:12 +00002552
Roman Divacky65b88cd2011-03-01 17:40:53 +00002553 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002554 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002555 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002556 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002557 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002558 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002559}
2560
2561/// getFunctionType - Return a normal function type with a typed argument
2562/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002563QualType
2564ASTContext::getFunctionType(QualType ResultTy,
2565 const QualType *ArgArray, unsigned NumArgs,
2566 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002567 // Unique functions, to guarantee there is only one function of a particular
2568 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002569 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002570 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002571
2572 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002573 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002574 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002575 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002576
2577 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002578 bool isCanonical =
2579 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2580 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002581 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002582 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002583 isCanonical = false;
2584
Roman Divacky65b88cd2011-03-01 17:40:53 +00002585 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2586 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2587 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002588
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002589 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002590 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002591 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002592 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002593 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002594 CanonicalArgs.reserve(NumArgs);
2595 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002596 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002597
John McCalldb40c7f2010-12-14 08:05:40 +00002598 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002599 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002600 CanonicalEPI.ExceptionSpecType = EST_None;
2601 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002602 CanonicalEPI.ExtInfo
2603 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2604
Chris Lattner76a00cf2008-04-06 22:59:24 +00002605 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002606 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002607 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002608
Chris Lattnerfd4de792007-01-27 01:15:32 +00002609 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002610 FunctionProtoType *NewIP =
2611 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002612 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002613 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002614
John McCall31168b02011-06-15 23:02:42 +00002615 // FunctionProtoType objects are allocated with extra bytes after
2616 // them for three variable size arrays at the end:
2617 // - parameter types
2618 // - exception types
2619 // - consumed-arguments flags
2620 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002621 // expression, or information used to resolve the exception
2622 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002623 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002624 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002625 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002626 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002627 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002628 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002629 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002630 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002631 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2632 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002633 }
John McCall31168b02011-06-15 23:02:42 +00002634 if (EPI.ConsumedArguments)
2635 Size += NumArgs * sizeof(bool);
2636
John McCalldb40c7f2010-12-14 08:05:40 +00002637 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002638 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2639 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002640 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002641 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002642 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002643 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002644}
Chris Lattneref51c202006-11-10 07:17:23 +00002645
John McCalle78aac42010-03-10 03:28:59 +00002646#ifndef NDEBUG
2647static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2648 if (!isa<CXXRecordDecl>(D)) return false;
2649 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2650 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2651 return true;
2652 if (RD->getDescribedClassTemplate() &&
2653 !isa<ClassTemplateSpecializationDecl>(RD))
2654 return true;
2655 return false;
2656}
2657#endif
2658
2659/// getInjectedClassNameType - Return the unique reference to the
2660/// injected class name type for the specified templated declaration.
2661QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002662 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002663 assert(NeedsInjectedClassNameType(Decl));
2664 if (Decl->TypeForDecl) {
2665 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002666 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002667 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2668 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2669 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2670 } else {
John McCall424cec92011-01-19 06:33:43 +00002671 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002672 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002673 Decl->TypeForDecl = newType;
2674 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002675 }
2676 return QualType(Decl->TypeForDecl, 0);
2677}
2678
Douglas Gregor83a586e2008-04-13 21:07:44 +00002679/// getTypeDeclType - Return the unique reference to the type for the
2680/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002681QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002682 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002683 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002684
Richard Smithdda56e42011-04-15 14:24:37 +00002685 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002686 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002687
John McCall96f0b5f2010-03-10 06:48:02 +00002688 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2689 "Template type parameter types are always available.");
2690
John McCall81e38502010-02-16 03:57:14 +00002691 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002692 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002693 "struct/union has previous declaration");
2694 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002695 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002696 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002697 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002698 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002699 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002700 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002701 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002702 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2703 Decl->TypeForDecl = newType;
2704 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002705 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002706 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002707
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002708 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002709}
2710
Chris Lattner32d920b2007-01-26 02:01:53 +00002711/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002712/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002713QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002714ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2715 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002716 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002717
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002718 if (Canonical.isNull())
2719 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002720 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002721 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002722 Decl->TypeForDecl = newType;
2723 Types.push_back(newType);
2724 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002725}
2726
Jay Foad39c79802011-01-12 09:06:06 +00002727QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002728 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2729
Douglas Gregorec9fd132012-01-14 16:38:05 +00002730 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002731 if (PrevDecl->TypeForDecl)
2732 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2733
John McCall424cec92011-01-19 06:33:43 +00002734 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2735 Decl->TypeForDecl = newType;
2736 Types.push_back(newType);
2737 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002738}
2739
Jay Foad39c79802011-01-12 09:06:06 +00002740QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002741 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2742
Douglas Gregorec9fd132012-01-14 16:38:05 +00002743 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002744 if (PrevDecl->TypeForDecl)
2745 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2746
John McCall424cec92011-01-19 06:33:43 +00002747 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2748 Decl->TypeForDecl = newType;
2749 Types.push_back(newType);
2750 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002751}
2752
John McCall81904512011-01-06 01:58:22 +00002753QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2754 QualType modifiedType,
2755 QualType equivalentType) {
2756 llvm::FoldingSetNodeID id;
2757 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2758
2759 void *insertPos = 0;
2760 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2761 if (type) return QualType(type, 0);
2762
2763 QualType canon = getCanonicalType(equivalentType);
2764 type = new (*this, TypeAlignment)
2765 AttributedType(canon, attrKind, modifiedType, equivalentType);
2766
2767 Types.push_back(type);
2768 AttributedTypes.InsertNode(type, insertPos);
2769
2770 return QualType(type, 0);
2771}
2772
2773
John McCallcebee162009-10-18 09:09:24 +00002774/// \brief Retrieve a substitution-result type.
2775QualType
2776ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002777 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002778 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002779 && "replacement types must always be canonical");
2780
2781 llvm::FoldingSetNodeID ID;
2782 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2783 void *InsertPos = 0;
2784 SubstTemplateTypeParmType *SubstParm
2785 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2786
2787 if (!SubstParm) {
2788 SubstParm = new (*this, TypeAlignment)
2789 SubstTemplateTypeParmType(Parm, Replacement);
2790 Types.push_back(SubstParm);
2791 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2792 }
2793
2794 return QualType(SubstParm, 0);
2795}
2796
Douglas Gregorada4b792011-01-14 02:55:32 +00002797/// \brief Retrieve a
2798QualType ASTContext::getSubstTemplateTypeParmPackType(
2799 const TemplateTypeParmType *Parm,
2800 const TemplateArgument &ArgPack) {
2801#ifndef NDEBUG
2802 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2803 PEnd = ArgPack.pack_end();
2804 P != PEnd; ++P) {
2805 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2806 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2807 }
2808#endif
2809
2810 llvm::FoldingSetNodeID ID;
2811 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2812 void *InsertPos = 0;
2813 if (SubstTemplateTypeParmPackType *SubstParm
2814 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2815 return QualType(SubstParm, 0);
2816
2817 QualType Canon;
2818 if (!Parm->isCanonicalUnqualified()) {
2819 Canon = getCanonicalType(QualType(Parm, 0));
2820 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2821 ArgPack);
2822 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2823 }
2824
2825 SubstTemplateTypeParmPackType *SubstParm
2826 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2827 ArgPack);
2828 Types.push_back(SubstParm);
2829 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2830 return QualType(SubstParm, 0);
2831}
2832
Douglas Gregoreff93e02009-02-05 23:33:38 +00002833/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002834/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002835/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002836QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002837 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002838 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002839 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002840 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002841 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002842 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002843 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2844
2845 if (TypeParm)
2846 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002847
Chandler Carruth08836322011-05-01 00:51:33 +00002848 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002849 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002850 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002851
2852 TemplateTypeParmType *TypeCheck
2853 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2854 assert(!TypeCheck && "Template type parameter canonical type broken");
2855 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002856 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002857 TypeParm = new (*this, TypeAlignment)
2858 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002859
2860 Types.push_back(TypeParm);
2861 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2862
2863 return QualType(TypeParm, 0);
2864}
2865
John McCalle78aac42010-03-10 03:28:59 +00002866TypeSourceInfo *
2867ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2868 SourceLocation NameLoc,
2869 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002870 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002871 assert(!Name.getAsDependentTemplateName() &&
2872 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002873 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002874
2875 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2876 TemplateSpecializationTypeLoc TL
2877 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002878 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002879 TL.setTemplateNameLoc(NameLoc);
2880 TL.setLAngleLoc(Args.getLAngleLoc());
2881 TL.setRAngleLoc(Args.getRAngleLoc());
2882 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2883 TL.setArgLocInfo(i, Args[i].getLocInfo());
2884 return DI;
2885}
2886
Mike Stump11289f42009-09-09 15:08:12 +00002887QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002888ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002889 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002890 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002891 assert(!Template.getAsDependentTemplateName() &&
2892 "No dependent template names here!");
2893
John McCall6b51f282009-11-23 01:53:49 +00002894 unsigned NumArgs = Args.size();
2895
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002896 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002897 ArgVec.reserve(NumArgs);
2898 for (unsigned i = 0; i != NumArgs; ++i)
2899 ArgVec.push_back(Args[i].getArgument());
2900
John McCall2408e322010-04-27 00:57:59 +00002901 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002902 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002903}
2904
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002905#ifndef NDEBUG
2906static bool hasAnyPackExpansions(const TemplateArgument *Args,
2907 unsigned NumArgs) {
2908 for (unsigned I = 0; I != NumArgs; ++I)
2909 if (Args[I].isPackExpansion())
2910 return true;
2911
2912 return true;
2913}
2914#endif
2915
John McCall0ad16662009-10-29 08:12:44 +00002916QualType
2917ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002918 const TemplateArgument *Args,
2919 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002920 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002921 assert(!Template.getAsDependentTemplateName() &&
2922 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002923 // Look through qualified template names.
2924 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2925 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002926
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002927 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002928 Template.getAsTemplateDecl() &&
2929 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002930 QualType CanonType;
2931 if (!Underlying.isNull())
2932 CanonType = getCanonicalType(Underlying);
2933 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002934 // We can get here with an alias template when the specialization contains
2935 // a pack expansion that does not match up with a parameter pack.
2936 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2937 "Caller must compute aliased type");
2938 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002939 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2940 NumArgs);
2941 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002942
Douglas Gregora8e02e72009-07-28 23:00:59 +00002943 // Allocate the (non-canonical) template specialization type, but don't
2944 // try to unique it: these types typically have location information that
2945 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002946 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2947 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002948 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002949 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002950 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002951 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2952 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002953
Douglas Gregor8bf42052009-02-09 18:46:07 +00002954 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002955 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002956}
2957
Mike Stump11289f42009-09-09 15:08:12 +00002958QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002959ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2960 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002961 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002962 assert(!Template.getAsDependentTemplateName() &&
2963 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002964
Douglas Gregore29139c2011-03-03 17:04:51 +00002965 // Look through qualified template names.
2966 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2967 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002968
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002969 // Build the canonical template specialization type.
2970 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002971 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002972 CanonArgs.reserve(NumArgs);
2973 for (unsigned I = 0; I != NumArgs; ++I)
2974 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2975
2976 // Determine whether this canonical template specialization type already
2977 // exists.
2978 llvm::FoldingSetNodeID ID;
2979 TemplateSpecializationType::Profile(ID, CanonTemplate,
2980 CanonArgs.data(), NumArgs, *this);
2981
2982 void *InsertPos = 0;
2983 TemplateSpecializationType *Spec
2984 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2985
2986 if (!Spec) {
2987 // Allocate a new canonical template specialization type.
2988 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2989 sizeof(TemplateArgument) * NumArgs),
2990 TypeAlignment);
2991 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2992 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002993 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002994 Types.push_back(Spec);
2995 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2996 }
2997
2998 assert(Spec->isDependentType() &&
2999 "Non-dependent template-id type must have a canonical type");
3000 return QualType(Spec, 0);
3001}
3002
3003QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003004ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3005 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003006 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003007 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003008 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003009
3010 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003011 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003012 if (T)
3013 return QualType(T, 0);
3014
Douglas Gregorc42075a2010-02-04 18:10:26 +00003015 QualType Canon = NamedType;
3016 if (!Canon.isCanonical()) {
3017 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003018 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3019 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003020 (void)CheckT;
3021 }
3022
Abramo Bagnara6150c882010-05-11 21:36:43 +00003023 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003024 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003025 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003026 return QualType(T, 0);
3027}
3028
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003029QualType
Jay Foad39c79802011-01-12 09:06:06 +00003030ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003031 llvm::FoldingSetNodeID ID;
3032 ParenType::Profile(ID, InnerType);
3033
3034 void *InsertPos = 0;
3035 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3036 if (T)
3037 return QualType(T, 0);
3038
3039 QualType Canon = InnerType;
3040 if (!Canon.isCanonical()) {
3041 Canon = getCanonicalType(InnerType);
3042 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3043 assert(!CheckT && "Paren canonical type broken");
3044 (void)CheckT;
3045 }
3046
3047 T = new (*this) ParenType(InnerType, Canon);
3048 Types.push_back(T);
3049 ParenTypes.InsertNode(T, InsertPos);
3050 return QualType(T, 0);
3051}
3052
Douglas Gregor02085352010-03-31 20:19:30 +00003053QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3054 NestedNameSpecifier *NNS,
3055 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003056 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003057 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3058
3059 if (Canon.isNull()) {
3060 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003061 ElaboratedTypeKeyword CanonKeyword = Keyword;
3062 if (Keyword == ETK_None)
3063 CanonKeyword = ETK_Typename;
3064
3065 if (CanonNNS != NNS || CanonKeyword != Keyword)
3066 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003067 }
3068
3069 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003070 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003071
3072 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003073 DependentNameType *T
3074 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003075 if (T)
3076 return QualType(T, 0);
3077
Douglas Gregor02085352010-03-31 20:19:30 +00003078 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003079 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003080 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003081 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003082}
3083
Mike Stump11289f42009-09-09 15:08:12 +00003084QualType
John McCallc392f372010-06-11 00:33:02 +00003085ASTContext::getDependentTemplateSpecializationType(
3086 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003087 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003088 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003089 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003090 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003091 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003092 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3093 ArgCopy.push_back(Args[I].getArgument());
3094 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3095 ArgCopy.size(),
3096 ArgCopy.data());
3097}
3098
3099QualType
3100ASTContext::getDependentTemplateSpecializationType(
3101 ElaboratedTypeKeyword Keyword,
3102 NestedNameSpecifier *NNS,
3103 const IdentifierInfo *Name,
3104 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003105 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003106 assert((!NNS || NNS->isDependent()) &&
3107 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003108
Douglas Gregorc42075a2010-02-04 18:10:26 +00003109 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003110 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3111 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003112
3113 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003114 DependentTemplateSpecializationType *T
3115 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003116 if (T)
3117 return QualType(T, 0);
3118
John McCallc392f372010-06-11 00:33:02 +00003119 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003120
John McCallc392f372010-06-11 00:33:02 +00003121 ElaboratedTypeKeyword CanonKeyword = Keyword;
3122 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3123
3124 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003125 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003126 for (unsigned I = 0; I != NumArgs; ++I) {
3127 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3128 if (!CanonArgs[I].structurallyEquals(Args[I]))
3129 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003130 }
3131
John McCallc392f372010-06-11 00:33:02 +00003132 QualType Canon;
3133 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3134 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3135 Name, NumArgs,
3136 CanonArgs.data());
3137
3138 // Find the insert position again.
3139 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3140 }
3141
3142 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3143 sizeof(TemplateArgument) * NumArgs),
3144 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003145 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003146 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003147 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003148 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003149 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003150}
3151
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003152QualType ASTContext::getPackExpansionType(QualType Pattern,
3153 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003154 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003155 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003156
3157 assert(Pattern->containsUnexpandedParameterPack() &&
3158 "Pack expansions must expand one or more parameter packs");
3159 void *InsertPos = 0;
3160 PackExpansionType *T
3161 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3162 if (T)
3163 return QualType(T, 0);
3164
3165 QualType Canon;
3166 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003167 Canon = getCanonicalType(Pattern);
3168 // The canonical type might not contain an unexpanded parameter pack, if it
3169 // contains an alias template specialization which ignores one of its
3170 // parameters.
3171 if (Canon->containsUnexpandedParameterPack()) {
3172 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003173
Richard Smith68eea502012-07-16 00:20:35 +00003174 // Find the insert position again, in case we inserted an element into
3175 // PackExpansionTypes and invalidated our insert position.
3176 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3177 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003178 }
3179
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003180 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003181 Types.push_back(T);
3182 PackExpansionTypes.InsertNode(T, InsertPos);
3183 return QualType(T, 0);
3184}
3185
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003186/// CmpProtocolNames - Comparison predicate for sorting protocols
3187/// alphabetically.
3188static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3189 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003190 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003191}
3192
John McCall8b07ec22010-05-15 11:32:37 +00003193static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003194 unsigned NumProtocols) {
3195 if (NumProtocols == 0) return true;
3196
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003197 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3198 return false;
3199
John McCallfc93cf92009-10-22 22:37:11 +00003200 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003201 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3202 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003203 return false;
3204 return true;
3205}
3206
3207static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003208 unsigned &NumProtocols) {
3209 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003210
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003211 // Sort protocols, keyed by name.
3212 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3213
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003214 // Canonicalize.
3215 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3216 Protocols[I] = Protocols[I]->getCanonicalDecl();
3217
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003218 // Remove duplicates.
3219 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3220 NumProtocols = ProtocolsEnd-Protocols;
3221}
3222
John McCall8b07ec22010-05-15 11:32:37 +00003223QualType ASTContext::getObjCObjectType(QualType BaseType,
3224 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003225 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003226 // If the base type is an interface and there aren't any protocols
3227 // to add, then the interface type will do just fine.
3228 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3229 return BaseType;
3230
3231 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003232 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003233 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003234 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003235 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3236 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003237
John McCall8b07ec22010-05-15 11:32:37 +00003238 // Build the canonical type, which has the canonical base type and
3239 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003240 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003241 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3242 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3243 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003244 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003245 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003246 unsigned UniqueCount = NumProtocols;
3247
John McCallfc93cf92009-10-22 22:37:11 +00003248 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003249 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3250 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003251 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003252 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3253 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003254 }
3255
3256 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003257 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3258 }
3259
3260 unsigned Size = sizeof(ObjCObjectTypeImpl);
3261 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3262 void *Mem = Allocate(Size, TypeAlignment);
3263 ObjCObjectTypeImpl *T =
3264 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3265
3266 Types.push_back(T);
3267 ObjCObjectTypes.InsertNode(T, InsertPos);
3268 return QualType(T, 0);
3269}
3270
3271/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3272/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003273QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003274 llvm::FoldingSetNodeID ID;
3275 ObjCObjectPointerType::Profile(ID, ObjectT);
3276
3277 void *InsertPos = 0;
3278 if (ObjCObjectPointerType *QT =
3279 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3280 return QualType(QT, 0);
3281
3282 // Find the canonical object type.
3283 QualType Canonical;
3284 if (!ObjectT.isCanonical()) {
3285 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3286
3287 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003288 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3289 }
3290
Douglas Gregorf85bee62010-02-08 22:59:26 +00003291 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003292 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3293 ObjCObjectPointerType *QType =
3294 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003295
Steve Narofffb4330f2009-06-17 22:40:22 +00003296 Types.push_back(QType);
3297 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003298 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003299}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003300
Douglas Gregor1c283312010-08-11 12:19:30 +00003301/// getObjCInterfaceType - Return the unique reference to the type for the
3302/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003303QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3304 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003305 if (Decl->TypeForDecl)
3306 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003307
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003308 if (PrevDecl) {
3309 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3310 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3311 return QualType(PrevDecl->TypeForDecl, 0);
3312 }
3313
Douglas Gregor7671e532011-12-16 16:34:57 +00003314 // Prefer the definition, if there is one.
3315 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3316 Decl = Def;
3317
Douglas Gregor1c283312010-08-11 12:19:30 +00003318 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3319 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3320 Decl->TypeForDecl = T;
3321 Types.push_back(T);
3322 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003323}
3324
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003325/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3326/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003327/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003328/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003329/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003330QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003331 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003332 if (tofExpr->isTypeDependent()) {
3333 llvm::FoldingSetNodeID ID;
3334 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003335
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003336 void *InsertPos = 0;
3337 DependentTypeOfExprType *Canon
3338 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3339 if (Canon) {
3340 // We already have a "canonical" version of an identical, dependent
3341 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003342 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003343 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003344 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003345 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003346 Canon
3347 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003348 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3349 toe = Canon;
3350 }
3351 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003352 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003353 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003354 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003355 Types.push_back(toe);
3356 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003357}
3358
Steve Naroffa773cd52007-08-01 18:02:17 +00003359/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3360/// TypeOfType AST's. The only motivation to unique these nodes would be
3361/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003362/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003363/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003364QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003365 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003366 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003367 Types.push_back(tot);
3368 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003369}
3370
Anders Carlssonad6bd352009-06-24 21:24:56 +00003371
Anders Carlsson81df7b82009-06-24 19:06:50 +00003372/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3373/// DecltypeType AST's. The only motivation to unique these nodes would be
3374/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003375/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003376/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003377QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003378 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003379
3380 // C++0x [temp.type]p2:
3381 // If an expression e involves a template parameter, decltype(e) denotes a
3382 // unique dependent type. Two such decltype-specifiers refer to the same
3383 // type only if their expressions are equivalent (14.5.6.1).
3384 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003385 llvm::FoldingSetNodeID ID;
3386 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003387
Douglas Gregora21f6c32009-07-30 23:36:40 +00003388 void *InsertPos = 0;
3389 DependentDecltypeType *Canon
3390 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3391 if (Canon) {
3392 // We already have a "canonical" version of an equivalent, dependent
3393 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003394 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003395 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003396 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003397 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003398 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003399 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3400 dt = Canon;
3401 }
3402 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003403 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3404 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003405 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003406 Types.push_back(dt);
3407 return QualType(dt, 0);
3408}
3409
Alexis Hunte852b102011-05-24 22:41:36 +00003410/// getUnaryTransformationType - We don't unique these, since the memory
3411/// savings are minimal and these are rare.
3412QualType ASTContext::getUnaryTransformType(QualType BaseType,
3413 QualType UnderlyingType,
3414 UnaryTransformType::UTTKind Kind)
3415 const {
3416 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003417 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3418 Kind,
3419 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003420 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003421 Types.push_back(Ty);
3422 return QualType(Ty, 0);
3423}
3424
Richard Smithb2bc2e62011-02-21 20:05:19 +00003425/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003426QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003427 void *InsertPos = 0;
3428 if (!DeducedType.isNull()) {
3429 // Look in the folding set for an existing type.
3430 llvm::FoldingSetNodeID ID;
3431 AutoType::Profile(ID, DeducedType);
3432 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3433 return QualType(AT, 0);
3434 }
3435
3436 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3437 Types.push_back(AT);
3438 if (InsertPos)
3439 AutoTypes.InsertNode(AT, InsertPos);
3440 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003441}
3442
Eli Friedman0dfb8892011-10-06 23:00:33 +00003443/// getAtomicType - Return the uniqued reference to the atomic type for
3444/// the given value type.
3445QualType ASTContext::getAtomicType(QualType T) const {
3446 // Unique pointers, to guarantee there is only one pointer of a particular
3447 // structure.
3448 llvm::FoldingSetNodeID ID;
3449 AtomicType::Profile(ID, T);
3450
3451 void *InsertPos = 0;
3452 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3453 return QualType(AT, 0);
3454
3455 // If the atomic value type isn't canonical, this won't be a canonical type
3456 // either, so fill in the canonical type field.
3457 QualType Canonical;
3458 if (!T.isCanonical()) {
3459 Canonical = getAtomicType(getCanonicalType(T));
3460
3461 // Get the new insert position for the node we care about.
3462 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3463 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3464 }
3465 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3466 Types.push_back(New);
3467 AtomicTypes.InsertNode(New, InsertPos);
3468 return QualType(New, 0);
3469}
3470
Richard Smith02e85f32011-04-14 22:09:26 +00003471/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3472QualType ASTContext::getAutoDeductType() const {
3473 if (AutoDeductTy.isNull())
3474 AutoDeductTy = getAutoType(QualType());
3475 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3476 return AutoDeductTy;
3477}
3478
3479/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3480QualType ASTContext::getAutoRRefDeductType() const {
3481 if (AutoRRefDeductTy.isNull())
3482 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3483 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3484 return AutoRRefDeductTy;
3485}
3486
Chris Lattnerfb072462007-01-23 05:45:31 +00003487/// getTagDeclType - Return the unique reference to the type for the
3488/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003489QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003490 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003491 // FIXME: What is the design on getTagDeclType when it requires casting
3492 // away const? mutable?
3493 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003494}
3495
Mike Stump11289f42009-09-09 15:08:12 +00003496/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3497/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3498/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003499CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003500 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003501}
Chris Lattnerfb072462007-01-23 05:45:31 +00003502
Hans Wennborg27541db2011-10-27 08:29:09 +00003503/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3504CanQualType ASTContext::getIntMaxType() const {
3505 return getFromTargetType(Target->getIntMaxType());
3506}
3507
3508/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3509CanQualType ASTContext::getUIntMaxType() const {
3510 return getFromTargetType(Target->getUIntMaxType());
3511}
3512
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003513/// getSignedWCharType - Return the type of "signed wchar_t".
3514/// Used when in C++, as a GCC extension.
3515QualType ASTContext::getSignedWCharType() const {
3516 // FIXME: derive from "Target" ?
3517 return WCharTy;
3518}
3519
3520/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3521/// Used when in C++, as a GCC extension.
3522QualType ASTContext::getUnsignedWCharType() const {
3523 // FIXME: derive from "Target" ?
3524 return UnsignedIntTy;
3525}
3526
Hans Wennborg27541db2011-10-27 08:29:09 +00003527/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003528/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3529QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003530 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003531}
3532
Chris Lattnera21ad802008-04-02 05:18:44 +00003533//===----------------------------------------------------------------------===//
3534// Type Operators
3535//===----------------------------------------------------------------------===//
3536
Jay Foad39c79802011-01-12 09:06:06 +00003537CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003538 // Push qualifiers into arrays, and then discard any remaining
3539 // qualifiers.
3540 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003541 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003542 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003543 QualType Result;
3544 if (isa<ArrayType>(Ty)) {
3545 Result = getArrayDecayedType(QualType(Ty,0));
3546 } else if (isa<FunctionType>(Ty)) {
3547 Result = getPointerType(QualType(Ty, 0));
3548 } else {
3549 Result = QualType(Ty, 0);
3550 }
3551
3552 return CanQualType::CreateUnsafe(Result);
3553}
3554
John McCall6c9dd522011-01-18 07:41:22 +00003555QualType ASTContext::getUnqualifiedArrayType(QualType type,
3556 Qualifiers &quals) {
3557 SplitQualType splitType = type.getSplitUnqualifiedType();
3558
3559 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3560 // the unqualified desugared type and then drops it on the floor.
3561 // We then have to strip that sugar back off with
3562 // getUnqualifiedDesugaredType(), which is silly.
3563 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003564 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003565
3566 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003567 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003568 quals = splitType.Quals;
3569 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003570 }
3571
John McCall6c9dd522011-01-18 07:41:22 +00003572 // Otherwise, recurse on the array's element type.
3573 QualType elementType = AT->getElementType();
3574 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3575
3576 // If that didn't change the element type, AT has no qualifiers, so we
3577 // can just use the results in splitType.
3578 if (elementType == unqualElementType) {
3579 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003580 quals = splitType.Quals;
3581 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003582 }
3583
3584 // Otherwise, add in the qualifiers from the outermost type, then
3585 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003586 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003587
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003588 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003589 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003590 CAT->getSizeModifier(), 0);
3591 }
3592
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003593 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003594 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003595 }
3596
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003597 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003598 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003599 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003600 VAT->getSizeModifier(),
3601 VAT->getIndexTypeCVRQualifiers(),
3602 VAT->getBracketsRange());
3603 }
3604
3605 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003606 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003607 DSAT->getSizeModifier(), 0,
3608 SourceRange());
3609}
3610
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003611/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3612/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3613/// they point to and return true. If T1 and T2 aren't pointer types
3614/// or pointer-to-member types, or if they are not similar at this
3615/// level, returns false and leaves T1 and T2 unchanged. Top-level
3616/// qualifiers on T1 and T2 are ignored. This function will typically
3617/// be called in a loop that successively "unwraps" pointer and
3618/// pointer-to-member types to compare them at each level.
3619bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3620 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3621 *T2PtrType = T2->getAs<PointerType>();
3622 if (T1PtrType && T2PtrType) {
3623 T1 = T1PtrType->getPointeeType();
3624 T2 = T2PtrType->getPointeeType();
3625 return true;
3626 }
3627
3628 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3629 *T2MPType = T2->getAs<MemberPointerType>();
3630 if (T1MPType && T2MPType &&
3631 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3632 QualType(T2MPType->getClass(), 0))) {
3633 T1 = T1MPType->getPointeeType();
3634 T2 = T2MPType->getPointeeType();
3635 return true;
3636 }
3637
David Blaikiebbafb8a2012-03-11 07:00:24 +00003638 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003639 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3640 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3641 if (T1OPType && T2OPType) {
3642 T1 = T1OPType->getPointeeType();
3643 T2 = T2OPType->getPointeeType();
3644 return true;
3645 }
3646 }
3647
3648 // FIXME: Block pointers, too?
3649
3650 return false;
3651}
3652
Jay Foad39c79802011-01-12 09:06:06 +00003653DeclarationNameInfo
3654ASTContext::getNameForTemplate(TemplateName Name,
3655 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003656 switch (Name.getKind()) {
3657 case TemplateName::QualifiedTemplate:
3658 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003659 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003660 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3661 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003662
John McCalld9dfe3a2011-06-30 08:33:18 +00003663 case TemplateName::OverloadedTemplate: {
3664 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3665 // DNInfo work in progress: CHECKME: what about DNLoc?
3666 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3667 }
3668
3669 case TemplateName::DependentTemplate: {
3670 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003671 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003672 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003673 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3674 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003675 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003676 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3677 // DNInfo work in progress: FIXME: source locations?
3678 DeclarationNameLoc DNLoc;
3679 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3680 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3681 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003682 }
3683 }
3684
John McCalld9dfe3a2011-06-30 08:33:18 +00003685 case TemplateName::SubstTemplateTemplateParm: {
3686 SubstTemplateTemplateParmStorage *subst
3687 = Name.getAsSubstTemplateTemplateParm();
3688 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3689 NameLoc);
3690 }
3691
3692 case TemplateName::SubstTemplateTemplateParmPack: {
3693 SubstTemplateTemplateParmPackStorage *subst
3694 = Name.getAsSubstTemplateTemplateParmPack();
3695 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3696 NameLoc);
3697 }
3698 }
3699
3700 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003701}
3702
Jay Foad39c79802011-01-12 09:06:06 +00003703TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003704 switch (Name.getKind()) {
3705 case TemplateName::QualifiedTemplate:
3706 case TemplateName::Template: {
3707 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003708 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003709 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003710 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3711
3712 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003713 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003714 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003715
John McCalld9dfe3a2011-06-30 08:33:18 +00003716 case TemplateName::OverloadedTemplate:
3717 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003718
John McCalld9dfe3a2011-06-30 08:33:18 +00003719 case TemplateName::DependentTemplate: {
3720 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3721 assert(DTN && "Non-dependent template names must refer to template decls.");
3722 return DTN->CanonicalTemplateName;
3723 }
3724
3725 case TemplateName::SubstTemplateTemplateParm: {
3726 SubstTemplateTemplateParmStorage *subst
3727 = Name.getAsSubstTemplateTemplateParm();
3728 return getCanonicalTemplateName(subst->getReplacement());
3729 }
3730
3731 case TemplateName::SubstTemplateTemplateParmPack: {
3732 SubstTemplateTemplateParmPackStorage *subst
3733 = Name.getAsSubstTemplateTemplateParmPack();
3734 TemplateTemplateParmDecl *canonParameter
3735 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3736 TemplateArgument canonArgPack
3737 = getCanonicalTemplateArgument(subst->getArgumentPack());
3738 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3739 }
3740 }
3741
3742 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003743}
3744
Douglas Gregoradee3e32009-11-11 23:06:43 +00003745bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3746 X = getCanonicalTemplateName(X);
3747 Y = getCanonicalTemplateName(Y);
3748 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3749}
3750
Mike Stump11289f42009-09-09 15:08:12 +00003751TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003752ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003753 switch (Arg.getKind()) {
3754 case TemplateArgument::Null:
3755 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003756
Douglas Gregora8e02e72009-07-28 23:00:59 +00003757 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003758 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003759
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003760 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00003761 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3762 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003763 }
Mike Stump11289f42009-09-09 15:08:12 +00003764
Eli Friedmanb826a002012-09-26 02:36:12 +00003765 case TemplateArgument::NullPtr:
3766 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3767 /*isNullPtr*/true);
3768
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003769 case TemplateArgument::Template:
3770 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003771
3772 case TemplateArgument::TemplateExpansion:
3773 return TemplateArgument(getCanonicalTemplateName(
3774 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003775 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003776
Douglas Gregora8e02e72009-07-28 23:00:59 +00003777 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003778 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003779
Douglas Gregora8e02e72009-07-28 23:00:59 +00003780 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003781 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003782
Douglas Gregora8e02e72009-07-28 23:00:59 +00003783 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003784 if (Arg.pack_size() == 0)
3785 return Arg;
3786
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003787 TemplateArgument *CanonArgs
3788 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003789 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003790 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003791 AEnd = Arg.pack_end();
3792 A != AEnd; (void)++A, ++Idx)
3793 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003794
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003795 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003796 }
3797 }
3798
3799 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003800 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003801}
3802
Douglas Gregor333489b2009-03-27 23:10:48 +00003803NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003804ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003805 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003806 return 0;
3807
3808 switch (NNS->getKind()) {
3809 case NestedNameSpecifier::Identifier:
3810 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003811 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003812 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3813 NNS->getAsIdentifier());
3814
3815 case NestedNameSpecifier::Namespace:
3816 // A namespace is canonical; build a nested-name-specifier with
3817 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003818 return NestedNameSpecifier::Create(*this, 0,
3819 NNS->getAsNamespace()->getOriginalNamespace());
3820
3821 case NestedNameSpecifier::NamespaceAlias:
3822 // A namespace is canonical; build a nested-name-specifier with
3823 // this namespace and no prefix.
3824 return NestedNameSpecifier::Create(*this, 0,
3825 NNS->getAsNamespaceAlias()->getNamespace()
3826 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003827
3828 case NestedNameSpecifier::TypeSpec:
3829 case NestedNameSpecifier::TypeSpecWithTemplate: {
3830 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003831
3832 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3833 // break it apart into its prefix and identifier, then reconsititute those
3834 // as the canonical nested-name-specifier. This is required to canonicalize
3835 // a dependent nested-name-specifier involving typedefs of dependent-name
3836 // types, e.g.,
3837 // typedef typename T::type T1;
3838 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003839 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3840 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003841 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003842
Eli Friedman5358a0a2012-03-03 04:09:56 +00003843 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3844 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3845 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003846 return NestedNameSpecifier::Create(*this, 0, false,
3847 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003848 }
3849
3850 case NestedNameSpecifier::Global:
3851 // The global specifier is canonical and unique.
3852 return NNS;
3853 }
3854
David Blaikie8a40f702012-01-17 06:56:22 +00003855 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003856}
3857
Chris Lattner7adf0762008-08-04 07:31:14 +00003858
Jay Foad39c79802011-01-12 09:06:06 +00003859const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003860 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003861 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003862 // Handle the common positive case fast.
3863 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3864 return AT;
3865 }
Mike Stump11289f42009-09-09 15:08:12 +00003866
John McCall8ccfcb52009-09-24 19:53:00 +00003867 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003868 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003869 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003870
John McCall8ccfcb52009-09-24 19:53:00 +00003871 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003872 // implements C99 6.7.3p8: "If the specification of an array type includes
3873 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003874
Chris Lattner7adf0762008-08-04 07:31:14 +00003875 // If we get here, we either have type qualifiers on the type, or we have
3876 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003877 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003878
John McCall33ddac02011-01-19 10:06:00 +00003879 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003880 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003881
Chris Lattner7adf0762008-08-04 07:31:14 +00003882 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003883 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003884 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003885 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003886
Chris Lattner7adf0762008-08-04 07:31:14 +00003887 // Otherwise, we have an array and we have qualifiers on it. Push the
3888 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003889 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003890
Chris Lattner7adf0762008-08-04 07:31:14 +00003891 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3892 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3893 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003894 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003895 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3896 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3897 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003898 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003899
Mike Stump11289f42009-09-09 15:08:12 +00003900 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003901 = dyn_cast<DependentSizedArrayType>(ATy))
3902 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003903 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003904 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003905 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003906 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003907 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003908
Chris Lattner7adf0762008-08-04 07:31:14 +00003909 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003910 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003911 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003912 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003913 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003914 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003915}
3916
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003917QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003918 // C99 6.7.5.3p7:
3919 // A declaration of a parameter as "array of type" shall be
3920 // adjusted to "qualified pointer to type", where the type
3921 // qualifiers (if any) are those specified within the [ and ] of
3922 // the array type derivation.
3923 if (T->isArrayType())
3924 return getArrayDecayedType(T);
3925
3926 // C99 6.7.5.3p8:
3927 // A declaration of a parameter as "function returning type"
3928 // shall be adjusted to "pointer to function returning type", as
3929 // in 6.3.2.1.
3930 if (T->isFunctionType())
3931 return getPointerType(T);
3932
3933 return T;
3934}
3935
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003936QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003937 T = getVariableArrayDecayedType(T);
3938 T = getAdjustedParameterType(T);
3939 return T.getUnqualifiedType();
3940}
3941
Chris Lattnera21ad802008-04-02 05:18:44 +00003942/// getArrayDecayedType - Return the properly qualified result of decaying the
3943/// specified array type to a pointer. This operation is non-trivial when
3944/// handling typedefs etc. The canonical type of "T" must be an array type,
3945/// this returns a pointer to a properly qualified element of the array.
3946///
3947/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003948QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003949 // Get the element type with 'getAsArrayType' so that we don't lose any
3950 // typedefs in the element type of the array. This also handles propagation
3951 // of type qualifiers from the array type into the element type if present
3952 // (C99 6.7.3p8).
3953 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3954 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003955
Chris Lattner7adf0762008-08-04 07:31:14 +00003956 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003957
3958 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003959 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003960}
3961
John McCall33ddac02011-01-19 10:06:00 +00003962QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3963 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003964}
3965
John McCall33ddac02011-01-19 10:06:00 +00003966QualType ASTContext::getBaseElementType(QualType type) const {
3967 Qualifiers qs;
3968 while (true) {
3969 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003970 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003971 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003972
John McCall33ddac02011-01-19 10:06:00 +00003973 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003974 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003975 }
Mike Stump11289f42009-09-09 15:08:12 +00003976
John McCall33ddac02011-01-19 10:06:00 +00003977 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003978}
3979
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003980/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003981uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003982ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3983 uint64_t ElementCount = 1;
3984 do {
3985 ElementCount *= CA->getSize().getZExtValue();
3986 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3987 } while (CA);
3988 return ElementCount;
3989}
3990
Steve Naroff0af91202007-04-27 21:51:21 +00003991/// getFloatingRank - Return a relative rank for floating point types.
3992/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003993static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003994 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003995 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003996
John McCall9dd450b2009-09-21 23:43:11 +00003997 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3998 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003999 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004000 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004001 case BuiltinType::Float: return FloatRank;
4002 case BuiltinType::Double: return DoubleRank;
4003 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004004 }
4005}
4006
Mike Stump11289f42009-09-09 15:08:12 +00004007/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4008/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004009/// 'typeDomain' is a real floating point or complex type.
4010/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004011QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4012 QualType Domain) const {
4013 FloatingRank EltRank = getFloatingRank(Size);
4014 if (Domain->isComplexType()) {
4015 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004016 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004017 case FloatRank: return FloatComplexTy;
4018 case DoubleRank: return DoubleComplexTy;
4019 case LongDoubleRank: return LongDoubleComplexTy;
4020 }
Steve Naroff0af91202007-04-27 21:51:21 +00004021 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004022
4023 assert(Domain->isRealFloatingType() && "Unknown domain!");
4024 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004025 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004026 case FloatRank: return FloatTy;
4027 case DoubleRank: return DoubleTy;
4028 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004029 }
David Blaikief47fa302012-01-17 02:30:50 +00004030 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004031}
4032
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004033/// getFloatingTypeOrder - Compare the rank of the two specified floating
4034/// point types, ignoring the domain of the type (i.e. 'double' ==
4035/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004036/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004037int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004038 FloatingRank LHSR = getFloatingRank(LHS);
4039 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004040
Chris Lattnerb90739d2008-04-06 23:38:49 +00004041 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004042 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004043 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004044 return 1;
4045 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004046}
4047
Chris Lattner76a00cf2008-04-06 22:59:24 +00004048/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4049/// routine will assert if passed a built-in type that isn't an integer or enum,
4050/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004051unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004052 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004053
Chris Lattner76a00cf2008-04-06 22:59:24 +00004054 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004055 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004056 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004057 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004058 case BuiltinType::Char_S:
4059 case BuiltinType::Char_U:
4060 case BuiltinType::SChar:
4061 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004062 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004063 case BuiltinType::Short:
4064 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004065 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004066 case BuiltinType::Int:
4067 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004068 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004069 case BuiltinType::Long:
4070 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004071 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004072 case BuiltinType::LongLong:
4073 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004074 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004075 case BuiltinType::Int128:
4076 case BuiltinType::UInt128:
4077 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004078 }
4079}
4080
Eli Friedman629ffb92009-08-20 04:21:42 +00004081/// \brief Whether this is a promotable bitfield reference according
4082/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4083///
4084/// \returns the type this bit-field will promote to, or NULL if no
4085/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004086QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004087 if (E->isTypeDependent() || E->isValueDependent())
4088 return QualType();
4089
Eli Friedman629ffb92009-08-20 04:21:42 +00004090 FieldDecl *Field = E->getBitField();
4091 if (!Field)
4092 return QualType();
4093
4094 QualType FT = Field->getType();
4095
Richard Smithcaf33902011-10-10 18:28:20 +00004096 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004097 uint64_t IntSize = getTypeSize(IntTy);
4098 // GCC extension compatibility: if the bit-field size is less than or equal
4099 // to the size of int, it gets promoted no matter what its type is.
4100 // For instance, unsigned long bf : 4 gets promoted to signed int.
4101 if (BitWidth < IntSize)
4102 return IntTy;
4103
4104 if (BitWidth == IntSize)
4105 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4106
4107 // Types bigger than int are not subject to promotions, and therefore act
4108 // like the base type.
4109 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4110 // is ridiculous.
4111 return QualType();
4112}
4113
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004114/// getPromotedIntegerType - Returns the type that Promotable will
4115/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4116/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004117QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004118 assert(!Promotable.isNull());
4119 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004120 if (const EnumType *ET = Promotable->getAs<EnumType>())
4121 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004122
4123 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4124 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4125 // (3.9.1) can be converted to a prvalue of the first of the following
4126 // types that can represent all the values of its underlying type:
4127 // int, unsigned int, long int, unsigned long int, long long int, or
4128 // unsigned long long int [...]
4129 // FIXME: Is there some better way to compute this?
4130 if (BT->getKind() == BuiltinType::WChar_S ||
4131 BT->getKind() == BuiltinType::WChar_U ||
4132 BT->getKind() == BuiltinType::Char16 ||
4133 BT->getKind() == BuiltinType::Char32) {
4134 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4135 uint64_t FromSize = getTypeSize(BT);
4136 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4137 LongLongTy, UnsignedLongLongTy };
4138 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4139 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4140 if (FromSize < ToSize ||
4141 (FromSize == ToSize &&
4142 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4143 return PromoteTypes[Idx];
4144 }
4145 llvm_unreachable("char type should fit into long long");
4146 }
4147 }
4148
4149 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004150 if (Promotable->isSignedIntegerType())
4151 return IntTy;
4152 uint64_t PromotableSize = getTypeSize(Promotable);
4153 uint64_t IntSize = getTypeSize(IntTy);
4154 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4155 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4156}
4157
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004158/// \brief Recurses in pointer/array types until it finds an objc retainable
4159/// type and returns its ownership.
4160Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4161 while (!T.isNull()) {
4162 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4163 return T.getObjCLifetime();
4164 if (T->isArrayType())
4165 T = getBaseElementType(T);
4166 else if (const PointerType *PT = T->getAs<PointerType>())
4167 T = PT->getPointeeType();
4168 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004169 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004170 else
4171 break;
4172 }
4173
4174 return Qualifiers::OCL_None;
4175}
4176
Mike Stump11289f42009-09-09 15:08:12 +00004177/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004178/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004179/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004180int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004181 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4182 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004183 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004184
Chris Lattner76a00cf2008-04-06 22:59:24 +00004185 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4186 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004187
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004188 unsigned LHSRank = getIntegerRank(LHSC);
4189 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004190
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004191 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4192 if (LHSRank == RHSRank) return 0;
4193 return LHSRank > RHSRank ? 1 : -1;
4194 }
Mike Stump11289f42009-09-09 15:08:12 +00004195
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004196 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4197 if (LHSUnsigned) {
4198 // If the unsigned [LHS] type is larger, return it.
4199 if (LHSRank >= RHSRank)
4200 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004201
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004202 // If the signed type can represent all values of the unsigned type, it
4203 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004204 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004205 return -1;
4206 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004207
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004208 // If the unsigned [RHS] type is larger, return it.
4209 if (RHSRank >= LHSRank)
4210 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004211
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004212 // If the signed type can represent all values of the unsigned type, it
4213 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004214 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004215 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004216}
Anders Carlsson98f07902007-08-17 05:31:46 +00004217
Anders Carlsson6d417272009-11-14 21:45:58 +00004218static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004219CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4220 DeclContext *DC, IdentifierInfo *Id) {
4221 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004222 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004223 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004224 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004225 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004226}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004227
Mike Stump11289f42009-09-09 15:08:12 +00004228// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004229QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004230 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004231 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004232 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004233 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004234 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004235
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004236 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004237
Anders Carlsson98f07902007-08-17 05:31:46 +00004238 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004239 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004240 // int flags;
4241 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004242 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004243 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004244 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004245 FieldTypes[3] = LongTy;
4246
Anders Carlsson98f07902007-08-17 05:31:46 +00004247 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004248 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004249 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004250 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004251 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004252 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004253 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004254 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004255 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004256 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004257 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004258 }
4259
Douglas Gregord5058122010-02-11 01:19:42 +00004260 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004261 }
Mike Stump11289f42009-09-09 15:08:12 +00004262
Anders Carlsson98f07902007-08-17 05:31:46 +00004263 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004264}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004265
Douglas Gregor512b0772009-04-23 22:29:11 +00004266void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004267 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004268 assert(Rec && "Invalid CFConstantStringType");
4269 CFConstantStringTypeDecl = Rec->getDecl();
4270}
4271
Jay Foad39c79802011-01-12 09:06:06 +00004272QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004273 if (BlockDescriptorType)
4274 return getTagDeclType(BlockDescriptorType);
4275
4276 RecordDecl *T;
4277 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004278 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004279 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004280 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004281
4282 QualType FieldTypes[] = {
4283 UnsignedLongTy,
4284 UnsignedLongTy,
4285 };
4286
4287 const char *FieldNames[] = {
4288 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004289 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004290 };
4291
4292 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004293 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004294 SourceLocation(),
4295 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004296 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004297 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004298 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004299 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004300 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004301 T->addDecl(Field);
4302 }
4303
Douglas Gregord5058122010-02-11 01:19:42 +00004304 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004305
4306 BlockDescriptorType = T;
4307
4308 return getTagDeclType(BlockDescriptorType);
4309}
4310
Jay Foad39c79802011-01-12 09:06:06 +00004311QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004312 if (BlockDescriptorExtendedType)
4313 return getTagDeclType(BlockDescriptorExtendedType);
4314
4315 RecordDecl *T;
4316 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004317 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004318 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004319 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004320
4321 QualType FieldTypes[] = {
4322 UnsignedLongTy,
4323 UnsignedLongTy,
4324 getPointerType(VoidPtrTy),
4325 getPointerType(VoidPtrTy)
4326 };
4327
4328 const char *FieldNames[] = {
4329 "reserved",
4330 "Size",
4331 "CopyFuncPtr",
4332 "DestroyFuncPtr"
4333 };
4334
4335 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004336 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004337 SourceLocation(),
4338 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004339 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004340 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004341 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004342 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004343 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004344 T->addDecl(Field);
4345 }
4346
Douglas Gregord5058122010-02-11 01:19:42 +00004347 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004348
4349 BlockDescriptorExtendedType = T;
4350
4351 return getTagDeclType(BlockDescriptorExtendedType);
4352}
4353
Jay Foad39c79802011-01-12 09:06:06 +00004354bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004355 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004356 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004357 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004358 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4359 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004360 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004361
4362 }
4363 }
Mike Stump94967902009-10-21 18:16:27 +00004364 return false;
4365}
4366
Jay Foad39c79802011-01-12 09:06:06 +00004367QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004368ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004369 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004370 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004371 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004372 // unsigned int __flags;
4373 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004374 // void *__copy_helper; // as needed
4375 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004376 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004377 // } *
4378
Mike Stump94967902009-10-21 18:16:27 +00004379 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4380
4381 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004382 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004383 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4384 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004385 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004386 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004387 T->startDefinition();
4388 QualType Int32Ty = IntTy;
4389 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4390 QualType FieldTypes[] = {
4391 getPointerType(VoidPtrTy),
4392 getPointerType(getTagDeclType(T)),
4393 Int32Ty,
4394 Int32Ty,
4395 getPointerType(VoidPtrTy),
4396 getPointerType(VoidPtrTy),
4397 Ty
4398 };
4399
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004400 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004401 "__isa",
4402 "__forwarding",
4403 "__flags",
4404 "__size",
4405 "__copy_helper",
4406 "__destroy_helper",
4407 DeclName,
4408 };
4409
4410 for (size_t i = 0; i < 7; ++i) {
4411 if (!HasCopyAndDispose && i >=4 && i <= 5)
4412 continue;
4413 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004414 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004415 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004416 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004417 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004418 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004419 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004420 T->addDecl(Field);
4421 }
4422
Douglas Gregord5058122010-02-11 01:19:42 +00004423 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004424
4425 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004426}
4427
Douglas Gregorbab8a962011-09-08 01:46:34 +00004428TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4429 if (!ObjCInstanceTypeDecl)
4430 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4431 getTranslationUnitDecl(),
4432 SourceLocation(),
4433 SourceLocation(),
4434 &Idents.get("instancetype"),
4435 getTrivialTypeSourceInfo(getObjCIdType()));
4436 return ObjCInstanceTypeDecl;
4437}
4438
Anders Carlsson18acd442007-10-29 06:33:42 +00004439// This returns true if a type has been typedefed to BOOL:
4440// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004441static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004442 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004443 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4444 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004445
Anders Carlssond8499822007-10-29 05:01:08 +00004446 return false;
4447}
4448
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004449/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004450/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004451CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004452 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4453 return CharUnits::Zero();
4454
Ken Dyck40775002010-01-11 17:06:35 +00004455 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004456
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004457 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004458 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004459 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004460 // Treat arrays as pointers, since that's how they're passed in.
4461 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004462 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004463 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004464}
4465
4466static inline
4467std::string charUnitsToString(const CharUnits &CU) {
4468 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004469}
4470
John McCall351762c2011-02-07 10:33:21 +00004471/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004472/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004473std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4474 std::string S;
4475
David Chisnall950a9512009-11-17 19:33:30 +00004476 const BlockDecl *Decl = Expr->getBlockDecl();
4477 QualType BlockTy =
4478 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4479 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004480 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004481 // Compute size of all parameters.
4482 // Start with computing size of a pointer in number of bytes.
4483 // FIXME: There might(should) be a better way of doing this computation!
4484 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004485 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4486 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004487 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004488 E = Decl->param_end(); PI != E; ++PI) {
4489 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004490 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004491 if (sz.isZero())
4492 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004493 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004494 ParmOffset += sz;
4495 }
4496 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004497 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004498 // Block pointer and offset.
4499 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004500
4501 // Argument types.
4502 ParmOffset = PtrSize;
4503 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4504 Decl->param_end(); PI != E; ++PI) {
4505 ParmVarDecl *PVDecl = *PI;
4506 QualType PType = PVDecl->getOriginalType();
4507 if (const ArrayType *AT =
4508 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4509 // Use array's original type only if it has known number of
4510 // elements.
4511 if (!isa<ConstantArrayType>(AT))
4512 PType = PVDecl->getType();
4513 } else if (PType->isFunctionType())
4514 PType = PVDecl->getType();
4515 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004516 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004517 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004518 }
John McCall351762c2011-02-07 10:33:21 +00004519
4520 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004521}
4522
Douglas Gregora9d84932011-05-27 01:19:52 +00004523bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004524 std::string& S) {
4525 // Encode result type.
4526 getObjCEncodingForType(Decl->getResultType(), S);
4527 CharUnits ParmOffset;
4528 // Compute size of all parameters.
4529 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4530 E = Decl->param_end(); PI != E; ++PI) {
4531 QualType PType = (*PI)->getType();
4532 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004533 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004534 continue;
4535
David Chisnall50e4eba2010-12-30 14:05:53 +00004536 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004537 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004538 ParmOffset += sz;
4539 }
4540 S += charUnitsToString(ParmOffset);
4541 ParmOffset = CharUnits::Zero();
4542
4543 // Argument types.
4544 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4545 E = Decl->param_end(); PI != E; ++PI) {
4546 ParmVarDecl *PVDecl = *PI;
4547 QualType PType = PVDecl->getOriginalType();
4548 if (const ArrayType *AT =
4549 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4550 // Use array's original type only if it has known number of
4551 // elements.
4552 if (!isa<ConstantArrayType>(AT))
4553 PType = PVDecl->getType();
4554 } else if (PType->isFunctionType())
4555 PType = PVDecl->getType();
4556 getObjCEncodingForType(PType, S);
4557 S += charUnitsToString(ParmOffset);
4558 ParmOffset += getObjCEncodingTypeSize(PType);
4559 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004560
4561 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004562}
4563
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004564/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4565/// method parameter or return type. If Extended, include class names and
4566/// block object types.
4567void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4568 QualType T, std::string& S,
4569 bool Extended) const {
4570 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4571 getObjCEncodingForTypeQualifier(QT, S);
4572 // Encode parameter type.
4573 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4574 true /*OutermostType*/,
4575 false /*EncodingProperty*/,
4576 false /*StructField*/,
4577 Extended /*EncodeBlockParameters*/,
4578 Extended /*EncodeClassNames*/);
4579}
4580
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004581/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004582/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004583bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004584 std::string& S,
4585 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004586 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004587 // Encode return type.
4588 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4589 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004590 // Compute size of all parameters.
4591 // Start with computing size of a pointer in number of bytes.
4592 // FIXME: There might(should) be a better way of doing this computation!
4593 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004594 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004595 // The first two arguments (self and _cmd) are pointers; account for
4596 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004597 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004598 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004599 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004600 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004601 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004602 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004603 continue;
4604
Ken Dyck40775002010-01-11 17:06:35 +00004605 assert (sz.isPositive() &&
4606 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004607 ParmOffset += sz;
4608 }
Ken Dyck40775002010-01-11 17:06:35 +00004609 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004610 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004611 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004612
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004613 // Argument types.
4614 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004615 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004616 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004617 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004618 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004619 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004620 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4621 // Use array's original type only if it has known number of
4622 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004623 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004624 PType = PVDecl->getType();
4625 } else if (PType->isFunctionType())
4626 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004627 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4628 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004629 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004630 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004631 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004632
4633 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004634}
4635
Daniel Dunbar4932b362008-08-28 04:38:10 +00004636/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004637/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004638/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4639/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004640/// Property attributes are stored as a comma-delimited C string. The simple
4641/// attributes readonly and bycopy are encoded as single characters. The
4642/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4643/// encoded as single characters, followed by an identifier. Property types
4644/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004645/// these attributes are defined by the following enumeration:
4646/// @code
4647/// enum PropertyAttributes {
4648/// kPropertyReadOnly = 'R', // property is read-only.
4649/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4650/// kPropertyByref = '&', // property is a reference to the value last assigned
4651/// kPropertyDynamic = 'D', // property is dynamic
4652/// kPropertyGetter = 'G', // followed by getter selector name
4653/// kPropertySetter = 'S', // followed by setter selector name
4654/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004655/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004656/// kPropertyWeak = 'W' // 'weak' property
4657/// kPropertyStrong = 'P' // property GC'able
4658/// kPropertyNonAtomic = 'N' // property non-atomic
4659/// };
4660/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004661void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004662 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004663 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004664 // Collect information from the property implementation decl(s).
4665 bool Dynamic = false;
4666 ObjCPropertyImplDecl *SynthesizePID = 0;
4667
4668 // FIXME: Duplicated code due to poor abstraction.
4669 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004670 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004671 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4672 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004673 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004674 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004675 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004676 if (PID->getPropertyDecl() == PD) {
4677 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4678 Dynamic = true;
4679 } else {
4680 SynthesizePID = PID;
4681 }
4682 }
4683 }
4684 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004685 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004686 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004687 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004688 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004689 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004690 if (PID->getPropertyDecl() == PD) {
4691 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4692 Dynamic = true;
4693 } else {
4694 SynthesizePID = PID;
4695 }
4696 }
Mike Stump11289f42009-09-09 15:08:12 +00004697 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004698 }
4699 }
4700
4701 // FIXME: This is not very efficient.
4702 S = "T";
4703
4704 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004705 // GCC has some special rules regarding encoding of properties which
4706 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004707 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004708 true /* outermost type */,
4709 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004710
4711 if (PD->isReadOnly()) {
4712 S += ",R";
4713 } else {
4714 switch (PD->getSetterKind()) {
4715 case ObjCPropertyDecl::Assign: break;
4716 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004717 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004718 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004719 }
4720 }
4721
4722 // It really isn't clear at all what this means, since properties
4723 // are "dynamic by default".
4724 if (Dynamic)
4725 S += ",D";
4726
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004727 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4728 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004729
Daniel Dunbar4932b362008-08-28 04:38:10 +00004730 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4731 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004732 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004733 }
4734
4735 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4736 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004737 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004738 }
4739
4740 if (SynthesizePID) {
4741 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4742 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004743 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004744 }
4745
4746 // FIXME: OBJCGC: weak & strong
4747}
4748
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004749/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004750/// Another legacy compatibility encoding: 32-bit longs are encoded as
4751/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004752/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4753///
4754void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004755 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004756 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004757 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004758 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004759 else
Jay Foad39c79802011-01-12 09:06:06 +00004760 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004761 PointeeTy = IntTy;
4762 }
4763 }
4764}
4765
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004766void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004767 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004768 // We follow the behavior of gcc, expanding structures which are
4769 // directly pointed to, and expanding embedded structures. Note that
4770 // these rules are sufficient to prevent recursive encoding of the
4771 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004772 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004773 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004774}
4775
David Chisnallb190a2c2010-06-04 01:10:52 +00004776static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4777 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004778 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004779 case BuiltinType::Void: return 'v';
4780 case BuiltinType::Bool: return 'B';
4781 case BuiltinType::Char_U:
4782 case BuiltinType::UChar: return 'C';
4783 case BuiltinType::UShort: return 'S';
4784 case BuiltinType::UInt: return 'I';
4785 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004786 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004787 case BuiltinType::UInt128: return 'T';
4788 case BuiltinType::ULongLong: return 'Q';
4789 case BuiltinType::Char_S:
4790 case BuiltinType::SChar: return 'c';
4791 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004792 case BuiltinType::WChar_S:
4793 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004794 case BuiltinType::Int: return 'i';
4795 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004796 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004797 case BuiltinType::LongLong: return 'q';
4798 case BuiltinType::Int128: return 't';
4799 case BuiltinType::Float: return 'f';
4800 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004801 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004802 }
4803}
4804
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004805static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4806 EnumDecl *Enum = ET->getDecl();
4807
4808 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4809 if (!Enum->isFixed())
4810 return 'i';
4811
4812 // The encoding of a fixed enum type matches its fixed underlying type.
4813 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4814}
4815
Jay Foad39c79802011-01-12 09:06:06 +00004816static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004817 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004818 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004819 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004820 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4821 // The GNU runtime requires more information; bitfields are encoded as b,
4822 // then the offset (in bits) of the first element, then the type of the
4823 // bitfield, then the size in bits. For example, in this structure:
4824 //
4825 // struct
4826 // {
4827 // int integer;
4828 // int flags:2;
4829 // };
4830 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4831 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4832 // information is not especially sensible, but we're stuck with it for
4833 // compatibility with GCC, although providing it breaks anything that
4834 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004835 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004836 const RecordDecl *RD = FD->getParent();
4837 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004838 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004839 if (const EnumType *ET = T->getAs<EnumType>())
4840 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004841 else
Jay Foad39c79802011-01-12 09:06:06 +00004842 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004843 }
Richard Smithcaf33902011-10-10 18:28:20 +00004844 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004845}
4846
Daniel Dunbar07d07852009-10-18 21:17:35 +00004847// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004848void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4849 bool ExpandPointedToStructures,
4850 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004851 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004852 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004853 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004854 bool StructField,
4855 bool EncodeBlockParameters,
4856 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004857 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004858 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004859 return EncodeBitField(this, S, T, FD);
4860 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004861 return;
4862 }
Mike Stump11289f42009-09-09 15:08:12 +00004863
John McCall9dd450b2009-09-21 23:43:11 +00004864 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004865 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004866 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004867 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004868 return;
4869 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004870
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004871 // encoding for pointer or r3eference types.
4872 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004873 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004874 if (PT->isObjCSelType()) {
4875 S += ':';
4876 return;
4877 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004878 PointeeTy = PT->getPointeeType();
4879 }
4880 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4881 PointeeTy = RT->getPointeeType();
4882 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004883 bool isReadOnly = false;
4884 // For historical/compatibility reasons, the read-only qualifier of the
4885 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4886 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004887 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004888 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004889 if (OutermostType && T.isConstQualified()) {
4890 isReadOnly = true;
4891 S += 'r';
4892 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004893 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004894 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004895 while (P->getAs<PointerType>())
4896 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004897 if (P.isConstQualified()) {
4898 isReadOnly = true;
4899 S += 'r';
4900 }
4901 }
4902 if (isReadOnly) {
4903 // Another legacy compatibility encoding. Some ObjC qualifier and type
4904 // combinations need to be rearranged.
4905 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004906 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004907 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004908 }
Mike Stump11289f42009-09-09 15:08:12 +00004909
Anders Carlssond8499822007-10-29 05:01:08 +00004910 if (PointeeTy->isCharType()) {
4911 // char pointer types should be encoded as '*' unless it is a
4912 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004913 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004914 S += '*';
4915 return;
4916 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004917 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004918 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4919 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4920 S += '#';
4921 return;
4922 }
4923 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4924 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4925 S += '@';
4926 return;
4927 }
4928 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004929 }
Anders Carlssond8499822007-10-29 05:01:08 +00004930 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004931 getLegacyIntegralTypeEncoding(PointeeTy);
4932
Mike Stump11289f42009-09-09 15:08:12 +00004933 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004934 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004935 return;
4936 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004937
Chris Lattnere7cabb92009-07-13 00:10:46 +00004938 if (const ArrayType *AT =
4939 // Ignore type qualifiers etc.
4940 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004941 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004942 // Incomplete arrays are encoded as a pointer to the array element.
4943 S += '^';
4944
Mike Stump11289f42009-09-09 15:08:12 +00004945 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004946 false, ExpandStructures, FD);
4947 } else {
4948 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004949
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004950 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4951 if (getTypeSize(CAT->getElementType()) == 0)
4952 S += '0';
4953 else
4954 S += llvm::utostr(CAT->getSize().getZExtValue());
4955 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004956 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004957 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4958 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004959 S += '0';
4960 }
Mike Stump11289f42009-09-09 15:08:12 +00004961
4962 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004963 false, ExpandStructures, FD);
4964 S += ']';
4965 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004966 return;
4967 }
Mike Stump11289f42009-09-09 15:08:12 +00004968
John McCall9dd450b2009-09-21 23:43:11 +00004969 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004970 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004971 return;
4972 }
Mike Stump11289f42009-09-09 15:08:12 +00004973
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004974 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004975 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004976 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004977 // Anonymous structures print as '?'
4978 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4979 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004980 if (ClassTemplateSpecializationDecl *Spec
4981 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4982 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4983 std::string TemplateArgsStr
4984 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004985 TemplateArgs.data(),
4986 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004987 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004988
4989 S += TemplateArgsStr;
4990 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004991 } else {
4992 S += '?';
4993 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004994 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004995 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004996 if (!RDecl->isUnion()) {
4997 getObjCEncodingForStructureImpl(RDecl, S, FD);
4998 } else {
4999 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5000 FieldEnd = RDecl->field_end();
5001 Field != FieldEnd; ++Field) {
5002 if (FD) {
5003 S += '"';
5004 S += Field->getNameAsString();
5005 S += '"';
5006 }
Mike Stump11289f42009-09-09 15:08:12 +00005007
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005008 // Special case bit-fields.
5009 if (Field->isBitField()) {
5010 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005011 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005012 } else {
5013 QualType qt = Field->getType();
5014 getLegacyIntegralTypeEncoding(qt);
5015 getObjCEncodingForTypeImpl(qt, S, false, true,
5016 FD, /*OutermostType*/false,
5017 /*EncodingProperty*/false,
5018 /*StructField*/true);
5019 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005020 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005021 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005022 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005023 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005024 return;
5025 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005026
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005027 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005028 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005029 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005030 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005031 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005032 return;
5033 }
Mike Stump11289f42009-09-09 15:08:12 +00005034
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005035 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00005036 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005037 if (EncodeBlockParameters) {
5038 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
5039
5040 S += '<';
5041 // Block return type
5042 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5043 ExpandPointedToStructures, ExpandStructures,
5044 FD,
5045 false /* OutermostType */,
5046 EncodingProperty,
5047 false /* StructField */,
5048 EncodeBlockParameters,
5049 EncodeClassNames);
5050 // Block self
5051 S += "@?";
5052 // Block parameters
5053 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5054 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5055 E = FPT->arg_type_end(); I && (I != E); ++I) {
5056 getObjCEncodingForTypeImpl(*I, S,
5057 ExpandPointedToStructures,
5058 ExpandStructures,
5059 FD,
5060 false /* OutermostType */,
5061 EncodingProperty,
5062 false /* StructField */,
5063 EncodeBlockParameters,
5064 EncodeClassNames);
5065 }
5066 }
5067 S += '>';
5068 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005069 return;
5070 }
Mike Stump11289f42009-09-09 15:08:12 +00005071
John McCall8b07ec22010-05-15 11:32:37 +00005072 // Ignore protocol qualifiers when mangling at this level.
5073 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
5074 T = OT->getBaseType();
5075
John McCall8ccfcb52009-09-24 19:53:00 +00005076 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005077 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005078 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005079 S += '{';
5080 const IdentifierInfo *II = OI->getIdentifier();
5081 S += II->getName();
5082 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005083 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005084 DeepCollectObjCIvars(OI, true, Ivars);
5085 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005086 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005087 if (Field->isBitField())
5088 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005089 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005090 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005091 }
5092 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005093 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005094 }
Mike Stump11289f42009-09-09 15:08:12 +00005095
John McCall9dd450b2009-09-21 23:43:11 +00005096 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005097 if (OPT->isObjCIdType()) {
5098 S += '@';
5099 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005100 }
Mike Stump11289f42009-09-09 15:08:12 +00005101
Steve Narofff0c86112009-10-28 22:03:49 +00005102 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5103 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5104 // Since this is a binary compatibility issue, need to consult with runtime
5105 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005106 S += '#';
5107 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005108 }
Mike Stump11289f42009-09-09 15:08:12 +00005109
Chris Lattnere7cabb92009-07-13 00:10:46 +00005110 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005111 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005112 ExpandPointedToStructures,
5113 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005114 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005115 // Note that we do extended encoding of protocol qualifer list
5116 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005117 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005118 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5119 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005120 S += '<';
5121 S += (*I)->getNameAsString();
5122 S += '>';
5123 }
5124 S += '"';
5125 }
5126 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005127 }
Mike Stump11289f42009-09-09 15:08:12 +00005128
Chris Lattnere7cabb92009-07-13 00:10:46 +00005129 QualType PointeeTy = OPT->getPointeeType();
5130 if (!EncodingProperty &&
5131 isa<TypedefType>(PointeeTy.getTypePtr())) {
5132 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005133 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005134 // {...};
5135 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005136 getObjCEncodingForTypeImpl(PointeeTy, S,
5137 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00005138 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005139 return;
5140 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005141
5142 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005143 if (OPT->getInterfaceDecl() &&
5144 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005145 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005146 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005147 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5148 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005149 S += '<';
5150 S += (*I)->getNameAsString();
5151 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005152 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005153 S += '"';
5154 }
5155 return;
5156 }
Mike Stump11289f42009-09-09 15:08:12 +00005157
John McCalla9e6e8d2010-05-17 23:56:34 +00005158 // gcc just blithely ignores member pointers.
5159 // TODO: maybe there should be a mangling for these
5160 if (T->getAs<MemberPointerType>())
5161 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005162
5163 if (T->isVectorType()) {
5164 // This matches gcc's encoding, even though technically it is
5165 // insufficient.
5166 // FIXME. We should do a better job than gcc.
5167 return;
5168 }
5169
David Blaikie83d382b2011-09-23 05:06:16 +00005170 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00005171}
5172
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005173void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5174 std::string &S,
5175 const FieldDecl *FD,
5176 bool includeVBases) const {
5177 assert(RDecl && "Expected non-null RecordDecl");
5178 assert(!RDecl->isUnion() && "Should not be called for unions");
5179 if (!RDecl->getDefinition())
5180 return;
5181
5182 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5183 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5184 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5185
5186 if (CXXRec) {
5187 for (CXXRecordDecl::base_class_iterator
5188 BI = CXXRec->bases_begin(),
5189 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5190 if (!BI->isVirtual()) {
5191 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005192 if (base->isEmpty())
5193 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005194 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005195 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5196 std::make_pair(offs, base));
5197 }
5198 }
5199 }
5200
5201 unsigned i = 0;
5202 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5203 FieldEnd = RDecl->field_end();
5204 Field != FieldEnd; ++Field, ++i) {
5205 uint64_t offs = layout.getFieldOffset(i);
5206 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005207 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005208 }
5209
5210 if (CXXRec && includeVBases) {
5211 for (CXXRecordDecl::base_class_iterator
5212 BI = CXXRec->vbases_begin(),
5213 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5214 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005215 if (base->isEmpty())
5216 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005217 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005218 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5219 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5220 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005221 }
5222 }
5223
5224 CharUnits size;
5225 if (CXXRec) {
5226 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5227 } else {
5228 size = layout.getSize();
5229 }
5230
5231 uint64_t CurOffs = 0;
5232 std::multimap<uint64_t, NamedDecl *>::iterator
5233 CurLayObj = FieldOrBaseOffsets.begin();
5234
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005235 if (CXXRec && CXXRec->isDynamicClass() &&
5236 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005237 if (FD) {
5238 S += "\"_vptr$";
5239 std::string recname = CXXRec->getNameAsString();
5240 if (recname.empty()) recname = "?";
5241 S += recname;
5242 S += '"';
5243 }
5244 S += "^^?";
5245 CurOffs += getTypeSize(VoidPtrTy);
5246 }
5247
5248 if (!RDecl->hasFlexibleArrayMember()) {
5249 // Mark the end of the structure.
5250 uint64_t offs = toBits(size);
5251 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5252 std::make_pair(offs, (NamedDecl*)0));
5253 }
5254
5255 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5256 assert(CurOffs <= CurLayObj->first);
5257
5258 if (CurOffs < CurLayObj->first) {
5259 uint64_t padding = CurLayObj->first - CurOffs;
5260 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5261 // packing/alignment of members is different that normal, in which case
5262 // the encoding will be out-of-sync with the real layout.
5263 // If the runtime switches to just consider the size of types without
5264 // taking into account alignment, we could make padding explicit in the
5265 // encoding (e.g. using arrays of chars). The encoding strings would be
5266 // longer then though.
5267 CurOffs += padding;
5268 }
5269
5270 NamedDecl *dcl = CurLayObj->second;
5271 if (dcl == 0)
5272 break; // reached end of structure.
5273
5274 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5275 // We expand the bases without their virtual bases since those are going
5276 // in the initial structure. Note that this differs from gcc which
5277 // expands virtual bases each time one is encountered in the hierarchy,
5278 // making the encoding type bigger than it really is.
5279 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005280 assert(!base->isEmpty());
5281 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005282 } else {
5283 FieldDecl *field = cast<FieldDecl>(dcl);
5284 if (FD) {
5285 S += '"';
5286 S += field->getNameAsString();
5287 S += '"';
5288 }
5289
5290 if (field->isBitField()) {
5291 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005292 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005293 } else {
5294 QualType qt = field->getType();
5295 getLegacyIntegralTypeEncoding(qt);
5296 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5297 /*OutermostType*/false,
5298 /*EncodingProperty*/false,
5299 /*StructField*/true);
5300 CurOffs += getTypeSize(field->getType());
5301 }
5302 }
5303 }
5304}
5305
Mike Stump11289f42009-09-09 15:08:12 +00005306void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005307 std::string& S) const {
5308 if (QT & Decl::OBJC_TQ_In)
5309 S += 'n';
5310 if (QT & Decl::OBJC_TQ_Inout)
5311 S += 'N';
5312 if (QT & Decl::OBJC_TQ_Out)
5313 S += 'o';
5314 if (QT & Decl::OBJC_TQ_Bycopy)
5315 S += 'O';
5316 if (QT & Decl::OBJC_TQ_Byref)
5317 S += 'R';
5318 if (QT & Decl::OBJC_TQ_Oneway)
5319 S += 'V';
5320}
5321
Douglas Gregor3ea72692011-08-12 05:46:01 +00005322TypedefDecl *ASTContext::getObjCIdDecl() const {
5323 if (!ObjCIdDecl) {
5324 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5325 T = getObjCObjectPointerType(T);
5326 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5327 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5328 getTranslationUnitDecl(),
5329 SourceLocation(), SourceLocation(),
5330 &Idents.get("id"), IdInfo);
5331 }
5332
5333 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005334}
5335
Douglas Gregor52e02802011-08-12 06:17:30 +00005336TypedefDecl *ASTContext::getObjCSelDecl() const {
5337 if (!ObjCSelDecl) {
5338 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5339 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5340 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5341 getTranslationUnitDecl(),
5342 SourceLocation(), SourceLocation(),
5343 &Idents.get("SEL"), SelInfo);
5344 }
5345 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005346}
5347
Douglas Gregor0a586182011-08-12 05:59:41 +00005348TypedefDecl *ASTContext::getObjCClassDecl() const {
5349 if (!ObjCClassDecl) {
5350 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5351 T = getObjCObjectPointerType(T);
5352 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5353 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5354 getTranslationUnitDecl(),
5355 SourceLocation(), SourceLocation(),
5356 &Idents.get("Class"), ClassInfo);
5357 }
5358
5359 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005360}
5361
Douglas Gregord53ae832012-01-17 18:09:05 +00005362ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5363 if (!ObjCProtocolClassDecl) {
5364 ObjCProtocolClassDecl
5365 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5366 SourceLocation(),
5367 &Idents.get("Protocol"),
5368 /*PrevDecl=*/0,
5369 SourceLocation(), true);
5370 }
5371
5372 return ObjCProtocolClassDecl;
5373}
5374
Meador Inge5d3fb222012-06-16 03:34:49 +00005375//===----------------------------------------------------------------------===//
5376// __builtin_va_list Construction Functions
5377//===----------------------------------------------------------------------===//
5378
5379static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5380 // typedef char* __builtin_va_list;
5381 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5382 TypeSourceInfo *TInfo
5383 = Context->getTrivialTypeSourceInfo(CharPtrType);
5384
5385 TypedefDecl *VaListTypeDecl
5386 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5387 Context->getTranslationUnitDecl(),
5388 SourceLocation(), SourceLocation(),
5389 &Context->Idents.get("__builtin_va_list"),
5390 TInfo);
5391 return VaListTypeDecl;
5392}
5393
5394static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5395 // typedef void* __builtin_va_list;
5396 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5397 TypeSourceInfo *TInfo
5398 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5399
5400 TypedefDecl *VaListTypeDecl
5401 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5402 Context->getTranslationUnitDecl(),
5403 SourceLocation(), SourceLocation(),
5404 &Context->Idents.get("__builtin_va_list"),
5405 TInfo);
5406 return VaListTypeDecl;
5407}
5408
5409static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5410 // typedef struct __va_list_tag {
5411 RecordDecl *VaListTagDecl;
5412
5413 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5414 Context->getTranslationUnitDecl(),
5415 &Context->Idents.get("__va_list_tag"));
5416 VaListTagDecl->startDefinition();
5417
5418 const size_t NumFields = 5;
5419 QualType FieldTypes[NumFields];
5420 const char *FieldNames[NumFields];
5421
5422 // unsigned char gpr;
5423 FieldTypes[0] = Context->UnsignedCharTy;
5424 FieldNames[0] = "gpr";
5425
5426 // unsigned char fpr;
5427 FieldTypes[1] = Context->UnsignedCharTy;
5428 FieldNames[1] = "fpr";
5429
5430 // unsigned short reserved;
5431 FieldTypes[2] = Context->UnsignedShortTy;
5432 FieldNames[2] = "reserved";
5433
5434 // void* overflow_arg_area;
5435 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5436 FieldNames[3] = "overflow_arg_area";
5437
5438 // void* reg_save_area;
5439 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5440 FieldNames[4] = "reg_save_area";
5441
5442 // Create fields
5443 for (unsigned i = 0; i < NumFields; ++i) {
5444 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5445 SourceLocation(),
5446 SourceLocation(),
5447 &Context->Idents.get(FieldNames[i]),
5448 FieldTypes[i], /*TInfo=*/0,
5449 /*BitWidth=*/0,
5450 /*Mutable=*/false,
5451 ICIS_NoInit);
5452 Field->setAccess(AS_public);
5453 VaListTagDecl->addDecl(Field);
5454 }
5455 VaListTagDecl->completeDefinition();
5456 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005457 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005458
5459 // } __va_list_tag;
5460 TypedefDecl *VaListTagTypedefDecl
5461 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5462 Context->getTranslationUnitDecl(),
5463 SourceLocation(), SourceLocation(),
5464 &Context->Idents.get("__va_list_tag"),
5465 Context->getTrivialTypeSourceInfo(VaListTagType));
5466 QualType VaListTagTypedefType =
5467 Context->getTypedefType(VaListTagTypedefDecl);
5468
5469 // typedef __va_list_tag __builtin_va_list[1];
5470 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5471 QualType VaListTagArrayType
5472 = Context->getConstantArrayType(VaListTagTypedefType,
5473 Size, ArrayType::Normal, 0);
5474 TypeSourceInfo *TInfo
5475 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5476 TypedefDecl *VaListTypedefDecl
5477 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5478 Context->getTranslationUnitDecl(),
5479 SourceLocation(), SourceLocation(),
5480 &Context->Idents.get("__builtin_va_list"),
5481 TInfo);
5482
5483 return VaListTypedefDecl;
5484}
5485
5486static TypedefDecl *
5487CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5488 // typedef struct __va_list_tag {
5489 RecordDecl *VaListTagDecl;
5490 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5491 Context->getTranslationUnitDecl(),
5492 &Context->Idents.get("__va_list_tag"));
5493 VaListTagDecl->startDefinition();
5494
5495 const size_t NumFields = 4;
5496 QualType FieldTypes[NumFields];
5497 const char *FieldNames[NumFields];
5498
5499 // unsigned gp_offset;
5500 FieldTypes[0] = Context->UnsignedIntTy;
5501 FieldNames[0] = "gp_offset";
5502
5503 // unsigned fp_offset;
5504 FieldTypes[1] = Context->UnsignedIntTy;
5505 FieldNames[1] = "fp_offset";
5506
5507 // void* overflow_arg_area;
5508 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5509 FieldNames[2] = "overflow_arg_area";
5510
5511 // void* reg_save_area;
5512 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5513 FieldNames[3] = "reg_save_area";
5514
5515 // Create fields
5516 for (unsigned i = 0; i < NumFields; ++i) {
5517 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5518 VaListTagDecl,
5519 SourceLocation(),
5520 SourceLocation(),
5521 &Context->Idents.get(FieldNames[i]),
5522 FieldTypes[i], /*TInfo=*/0,
5523 /*BitWidth=*/0,
5524 /*Mutable=*/false,
5525 ICIS_NoInit);
5526 Field->setAccess(AS_public);
5527 VaListTagDecl->addDecl(Field);
5528 }
5529 VaListTagDecl->completeDefinition();
5530 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005531 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005532
5533 // } __va_list_tag;
5534 TypedefDecl *VaListTagTypedefDecl
5535 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5536 Context->getTranslationUnitDecl(),
5537 SourceLocation(), SourceLocation(),
5538 &Context->Idents.get("__va_list_tag"),
5539 Context->getTrivialTypeSourceInfo(VaListTagType));
5540 QualType VaListTagTypedefType =
5541 Context->getTypedefType(VaListTagTypedefDecl);
5542
5543 // typedef __va_list_tag __builtin_va_list[1];
5544 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5545 QualType VaListTagArrayType
5546 = Context->getConstantArrayType(VaListTagTypedefType,
5547 Size, ArrayType::Normal,0);
5548 TypeSourceInfo *TInfo
5549 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5550 TypedefDecl *VaListTypedefDecl
5551 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5552 Context->getTranslationUnitDecl(),
5553 SourceLocation(), SourceLocation(),
5554 &Context->Idents.get("__builtin_va_list"),
5555 TInfo);
5556
5557 return VaListTypedefDecl;
5558}
5559
5560static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5561 // typedef int __builtin_va_list[4];
5562 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5563 QualType IntArrayType
5564 = Context->getConstantArrayType(Context->IntTy,
5565 Size, ArrayType::Normal, 0);
5566 TypedefDecl *VaListTypedefDecl
5567 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5568 Context->getTranslationUnitDecl(),
5569 SourceLocation(), SourceLocation(),
5570 &Context->Idents.get("__builtin_va_list"),
5571 Context->getTrivialTypeSourceInfo(IntArrayType));
5572
5573 return VaListTypedefDecl;
5574}
5575
Logan Chien57086ce2012-10-10 06:56:20 +00005576static TypedefDecl *
5577CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5578 RecordDecl *VaListDecl;
5579 if (Context->getLangOpts().CPlusPlus) {
5580 // namespace std { struct __va_list {
5581 NamespaceDecl *NS;
5582 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5583 Context->getTranslationUnitDecl(),
5584 /*Inline*/false, SourceLocation(),
5585 SourceLocation(), &Context->Idents.get("std"),
5586 /*PrevDecl*/0);
5587
5588 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5589 Context->getTranslationUnitDecl(),
5590 SourceLocation(), SourceLocation(),
5591 &Context->Idents.get("__va_list"));
5592
5593 VaListDecl->setDeclContext(NS);
5594
5595 } else {
5596 // struct __va_list {
5597 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5598 Context->getTranslationUnitDecl(),
5599 &Context->Idents.get("__va_list"));
5600 }
5601
5602 VaListDecl->startDefinition();
5603
5604 // void * __ap;
5605 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5606 VaListDecl,
5607 SourceLocation(),
5608 SourceLocation(),
5609 &Context->Idents.get("__ap"),
5610 Context->getPointerType(Context->VoidTy),
5611 /*TInfo=*/0,
5612 /*BitWidth=*/0,
5613 /*Mutable=*/false,
5614 ICIS_NoInit);
5615 Field->setAccess(AS_public);
5616 VaListDecl->addDecl(Field);
5617
5618 // };
5619 VaListDecl->completeDefinition();
5620
5621 // typedef struct __va_list __builtin_va_list;
5622 TypeSourceInfo *TInfo
5623 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5624
5625 TypedefDecl *VaListTypeDecl
5626 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5627 Context->getTranslationUnitDecl(),
5628 SourceLocation(), SourceLocation(),
5629 &Context->Idents.get("__builtin_va_list"),
5630 TInfo);
5631
5632 return VaListTypeDecl;
5633}
5634
Meador Inge5d3fb222012-06-16 03:34:49 +00005635static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5636 TargetInfo::BuiltinVaListKind Kind) {
5637 switch (Kind) {
5638 case TargetInfo::CharPtrBuiltinVaList:
5639 return CreateCharPtrBuiltinVaListDecl(Context);
5640 case TargetInfo::VoidPtrBuiltinVaList:
5641 return CreateVoidPtrBuiltinVaListDecl(Context);
5642 case TargetInfo::PowerABIBuiltinVaList:
5643 return CreatePowerABIBuiltinVaListDecl(Context);
5644 case TargetInfo::X86_64ABIBuiltinVaList:
5645 return CreateX86_64ABIBuiltinVaListDecl(Context);
5646 case TargetInfo::PNaClABIBuiltinVaList:
5647 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00005648 case TargetInfo::AAPCSABIBuiltinVaList:
5649 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00005650 }
5651
5652 llvm_unreachable("Unhandled __builtin_va_list type kind");
5653}
5654
5655TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5656 if (!BuiltinVaListDecl)
5657 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5658
5659 return BuiltinVaListDecl;
5660}
5661
Meador Ingecfb60902012-07-01 15:57:25 +00005662QualType ASTContext::getVaListTagType() const {
5663 // Force the creation of VaListTagTy by building the __builtin_va_list
5664 // declaration.
5665 if (VaListTagTy.isNull())
5666 (void) getBuiltinVaListDecl();
5667
5668 return VaListTagTy;
5669}
5670
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005671void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005672 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005673 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005674
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005675 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005676}
5677
John McCalld28ae272009-12-02 08:04:21 +00005678/// \brief Retrieve the template name that corresponds to a non-empty
5679/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005680TemplateName
5681ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5682 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005683 unsigned size = End - Begin;
5684 assert(size > 1 && "set is not overloaded!");
5685
5686 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5687 size * sizeof(FunctionTemplateDecl*));
5688 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5689
5690 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005691 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005692 NamedDecl *D = *I;
5693 assert(isa<FunctionTemplateDecl>(D) ||
5694 (isa<UsingShadowDecl>(D) &&
5695 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5696 *Storage++ = D;
5697 }
5698
5699 return TemplateName(OT);
5700}
5701
Douglas Gregordc572a32009-03-30 22:58:21 +00005702/// \brief Retrieve the template name that represents a qualified
5703/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005704TemplateName
5705ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5706 bool TemplateKeyword,
5707 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005708 assert(NNS && "Missing nested-name-specifier in qualified template name");
5709
Douglas Gregorc42075a2010-02-04 18:10:26 +00005710 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005711 llvm::FoldingSetNodeID ID;
5712 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5713
5714 void *InsertPos = 0;
5715 QualifiedTemplateName *QTN =
5716 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5717 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00005718 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5719 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00005720 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5721 }
5722
5723 return TemplateName(QTN);
5724}
5725
5726/// \brief Retrieve the template name that represents a dependent
5727/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005728TemplateName
5729ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5730 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005731 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005732 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005733
5734 llvm::FoldingSetNodeID ID;
5735 DependentTemplateName::Profile(ID, NNS, Name);
5736
5737 void *InsertPos = 0;
5738 DependentTemplateName *QTN =
5739 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5740
5741 if (QTN)
5742 return TemplateName(QTN);
5743
5744 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5745 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005746 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5747 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00005748 } else {
5749 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00005750 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5751 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005752 DependentTemplateName *CheckQTN =
5753 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5754 assert(!CheckQTN && "Dependent type name canonicalization broken");
5755 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005756 }
5757
5758 DependentTemplateNames.InsertNode(QTN, InsertPos);
5759 return TemplateName(QTN);
5760}
5761
Douglas Gregor71395fa2009-11-04 00:56:37 +00005762/// \brief Retrieve the template name that represents a dependent
5763/// template name such as \c MetaFun::template operator+.
5764TemplateName
5765ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005766 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005767 assert((!NNS || NNS->isDependent()) &&
5768 "Nested name specifier must be dependent");
5769
5770 llvm::FoldingSetNodeID ID;
5771 DependentTemplateName::Profile(ID, NNS, Operator);
5772
5773 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005774 DependentTemplateName *QTN
5775 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005776
5777 if (QTN)
5778 return TemplateName(QTN);
5779
5780 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5781 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005782 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5783 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005784 } else {
5785 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00005786 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5787 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005788
5789 DependentTemplateName *CheckQTN
5790 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5791 assert(!CheckQTN && "Dependent template name canonicalization broken");
5792 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005793 }
5794
5795 DependentTemplateNames.InsertNode(QTN, InsertPos);
5796 return TemplateName(QTN);
5797}
5798
Douglas Gregor5590be02011-01-15 06:45:20 +00005799TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005800ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5801 TemplateName replacement) const {
5802 llvm::FoldingSetNodeID ID;
5803 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5804
5805 void *insertPos = 0;
5806 SubstTemplateTemplateParmStorage *subst
5807 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5808
5809 if (!subst) {
5810 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5811 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5812 }
5813
5814 return TemplateName(subst);
5815}
5816
5817TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005818ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5819 const TemplateArgument &ArgPack) const {
5820 ASTContext &Self = const_cast<ASTContext &>(*this);
5821 llvm::FoldingSetNodeID ID;
5822 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5823
5824 void *InsertPos = 0;
5825 SubstTemplateTemplateParmPackStorage *Subst
5826 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5827
5828 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005829 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005830 ArgPack.pack_size(),
5831 ArgPack.pack_begin());
5832 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5833 }
5834
5835 return TemplateName(Subst);
5836}
5837
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005838/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005839/// TargetInfo, produce the corresponding type. The unsigned @p Type
5840/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005841CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005842 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005843 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005844 case TargetInfo::SignedShort: return ShortTy;
5845 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5846 case TargetInfo::SignedInt: return IntTy;
5847 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5848 case TargetInfo::SignedLong: return LongTy;
5849 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5850 case TargetInfo::SignedLongLong: return LongLongTy;
5851 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5852 }
5853
David Blaikie83d382b2011-09-23 05:06:16 +00005854 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005855}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005856
5857//===----------------------------------------------------------------------===//
5858// Type Predicates.
5859//===----------------------------------------------------------------------===//
5860
Fariborz Jahanian96207692009-02-18 21:49:28 +00005861/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5862/// garbage collection attribute.
5863///
John McCall553d45a2011-01-12 00:34:59 +00005864Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005865 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005866 return Qualifiers::GCNone;
5867
David Blaikiebbafb8a2012-03-11 07:00:24 +00005868 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005869 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5870
5871 // Default behaviour under objective-C's gc is for ObjC pointers
5872 // (or pointers to them) be treated as though they were declared
5873 // as __strong.
5874 if (GCAttrs == Qualifiers::GCNone) {
5875 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5876 return Qualifiers::Strong;
5877 else if (Ty->isPointerType())
5878 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5879 } else {
5880 // It's not valid to set GC attributes on anything that isn't a
5881 // pointer.
5882#ifndef NDEBUG
5883 QualType CT = Ty->getCanonicalTypeInternal();
5884 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5885 CT = AT->getElementType();
5886 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5887#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005888 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005889 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005890}
5891
Chris Lattner49af6a42008-04-07 06:51:04 +00005892//===----------------------------------------------------------------------===//
5893// Type Compatibility Testing
5894//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005895
Mike Stump11289f42009-09-09 15:08:12 +00005896/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005897/// compatible.
5898static bool areCompatVectorTypes(const VectorType *LHS,
5899 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005900 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005901 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005902 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005903}
5904
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005905bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5906 QualType SecondVec) {
5907 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5908 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5909
5910 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5911 return true;
5912
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005913 // Treat Neon vector types and most AltiVec vector types as if they are the
5914 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005915 const VectorType *First = FirstVec->getAs<VectorType>();
5916 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005917 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005918 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005919 First->getVectorKind() != VectorType::AltiVecPixel &&
5920 First->getVectorKind() != VectorType::AltiVecBool &&
5921 Second->getVectorKind() != VectorType::AltiVecPixel &&
5922 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005923 return true;
5924
5925 return false;
5926}
5927
Steve Naroff8e6aee52009-07-23 01:01:38 +00005928//===----------------------------------------------------------------------===//
5929// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5930//===----------------------------------------------------------------------===//
5931
5932/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5933/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005934bool
5935ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5936 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005937 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005938 return true;
5939 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5940 E = rProto->protocol_end(); PI != E; ++PI)
5941 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5942 return true;
5943 return false;
5944}
5945
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00005946/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00005947/// return true if lhs's protocols conform to rhs's protocol; false
5948/// otherwise.
5949bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5950 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5951 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5952 return false;
5953}
5954
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00005955/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
5956/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005957bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5958 QualType rhs) {
5959 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5960 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5961 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5962
5963 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5964 E = lhsQID->qual_end(); I != E; ++I) {
5965 bool match = false;
5966 ObjCProtocolDecl *lhsProto = *I;
5967 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5968 E = rhsOPT->qual_end(); J != E; ++J) {
5969 ObjCProtocolDecl *rhsProto = *J;
5970 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5971 match = true;
5972 break;
5973 }
5974 }
5975 if (!match)
5976 return false;
5977 }
5978 return true;
5979}
5980
Steve Naroff8e6aee52009-07-23 01:01:38 +00005981/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5982/// ObjCQualifiedIDType.
5983bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5984 bool compare) {
5985 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005986 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005987 lhs->isObjCIdType() || lhs->isObjCClassType())
5988 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005989 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005990 rhs->isObjCIdType() || rhs->isObjCClassType())
5991 return true;
5992
5993 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005994 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005995
Steve Naroff8e6aee52009-07-23 01:01:38 +00005996 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005997
Steve Naroff8e6aee52009-07-23 01:01:38 +00005998 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005999 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006000 // make sure we check the class hierarchy.
6001 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6002 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6003 E = lhsQID->qual_end(); I != E; ++I) {
6004 // when comparing an id<P> on lhs with a static type on rhs,
6005 // see if static class implements all of id's protocols, directly or
6006 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006007 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006008 return false;
6009 }
6010 }
6011 // If there are no qualifiers and no interface, we have an 'id'.
6012 return true;
6013 }
Mike Stump11289f42009-09-09 15:08:12 +00006014 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006015 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6016 E = lhsQID->qual_end(); I != E; ++I) {
6017 ObjCProtocolDecl *lhsProto = *I;
6018 bool match = false;
6019
6020 // when comparing an id<P> on lhs with a static type on rhs,
6021 // see if static class implements all of id's protocols, directly or
6022 // through its super class and categories.
6023 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6024 E = rhsOPT->qual_end(); J != E; ++J) {
6025 ObjCProtocolDecl *rhsProto = *J;
6026 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6027 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6028 match = true;
6029 break;
6030 }
6031 }
Mike Stump11289f42009-09-09 15:08:12 +00006032 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006033 // make sure we check the class hierarchy.
6034 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6035 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6036 E = lhsQID->qual_end(); I != E; ++I) {
6037 // when comparing an id<P> on lhs with a static type on rhs,
6038 // see if static class implements all of id's protocols, directly or
6039 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006040 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006041 match = true;
6042 break;
6043 }
6044 }
6045 }
6046 if (!match)
6047 return false;
6048 }
Mike Stump11289f42009-09-09 15:08:12 +00006049
Steve Naroff8e6aee52009-07-23 01:01:38 +00006050 return true;
6051 }
Mike Stump11289f42009-09-09 15:08:12 +00006052
Steve Naroff8e6aee52009-07-23 01:01:38 +00006053 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6054 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6055
Mike Stump11289f42009-09-09 15:08:12 +00006056 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006057 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006058 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006059 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6060 E = lhsOPT->qual_end(); I != E; ++I) {
6061 ObjCProtocolDecl *lhsProto = *I;
6062 bool match = false;
6063
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006064 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006065 // see if static class implements all of id's protocols, directly or
6066 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006067 // First, lhs protocols in the qualifier list must be found, direct
6068 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006069 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6070 E = rhsQID->qual_end(); J != E; ++J) {
6071 ObjCProtocolDecl *rhsProto = *J;
6072 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6073 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6074 match = true;
6075 break;
6076 }
6077 }
6078 if (!match)
6079 return false;
6080 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006081
6082 // Static class's protocols, or its super class or category protocols
6083 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6084 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6085 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6086 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6087 // This is rather dubious but matches gcc's behavior. If lhs has
6088 // no type qualifier and its class has no static protocol(s)
6089 // assume that it is mismatch.
6090 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6091 return false;
6092 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6093 LHSInheritedProtocols.begin(),
6094 E = LHSInheritedProtocols.end(); I != E; ++I) {
6095 bool match = false;
6096 ObjCProtocolDecl *lhsProto = (*I);
6097 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6098 E = rhsQID->qual_end(); J != E; ++J) {
6099 ObjCProtocolDecl *rhsProto = *J;
6100 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6101 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6102 match = true;
6103 break;
6104 }
6105 }
6106 if (!match)
6107 return false;
6108 }
6109 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006110 return true;
6111 }
6112 return false;
6113}
6114
Eli Friedman47f77112008-08-22 00:56:42 +00006115/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006116/// compatible for assignment from RHS to LHS. This handles validation of any
6117/// protocol qualifiers on the LHS or RHS.
6118///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006119bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6120 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006121 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6122 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6123
Steve Naroff1329fa02009-07-15 18:40:39 +00006124 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006125 if (LHS->isObjCUnqualifiedIdOrClass() ||
6126 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006127 return true;
6128
John McCall8b07ec22010-05-15 11:32:37 +00006129 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006130 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6131 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006132 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006133
6134 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6135 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6136 QualType(RHSOPT,0));
6137
John McCall8b07ec22010-05-15 11:32:37 +00006138 // If we have 2 user-defined types, fall into that path.
6139 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006140 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006141
Steve Naroff8e6aee52009-07-23 01:01:38 +00006142 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006143}
6144
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006145/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006146/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006147/// arguments in block literals. When passed as arguments, passing 'A*' where
6148/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6149/// not OK. For the return type, the opposite is not OK.
6150bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6151 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006152 const ObjCObjectPointerType *RHSOPT,
6153 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006154 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006155 return true;
6156
6157 if (LHSOPT->isObjCBuiltinType()) {
6158 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6159 }
6160
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006161 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006162 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6163 QualType(RHSOPT,0),
6164 false);
6165
6166 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6167 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6168 if (LHS && RHS) { // We have 2 user-defined types.
6169 if (LHS != RHS) {
6170 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006171 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006172 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006173 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006174 }
6175 else
6176 return true;
6177 }
6178 return false;
6179}
6180
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006181/// getIntersectionOfProtocols - This routine finds the intersection of set
6182/// of protocols inherited from two distinct objective-c pointer objects.
6183/// It is used to build composite qualifier list of the composite type of
6184/// the conditional expression involving two objective-c pointer objects.
6185static
6186void getIntersectionOfProtocols(ASTContext &Context,
6187 const ObjCObjectPointerType *LHSOPT,
6188 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006189 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006190
John McCall8b07ec22010-05-15 11:32:37 +00006191 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6192 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6193 assert(LHS->getInterface() && "LHS must have an interface base");
6194 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006195
6196 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6197 unsigned LHSNumProtocols = LHS->getNumProtocols();
6198 if (LHSNumProtocols > 0)
6199 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6200 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006201 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006202 Context.CollectInheritedProtocols(LHS->getInterface(),
6203 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006204 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6205 LHSInheritedProtocols.end());
6206 }
6207
6208 unsigned RHSNumProtocols = RHS->getNumProtocols();
6209 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006210 ObjCProtocolDecl **RHSProtocols =
6211 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006212 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6213 if (InheritedProtocolSet.count(RHSProtocols[i]))
6214 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006215 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006216 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006217 Context.CollectInheritedProtocols(RHS->getInterface(),
6218 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006219 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6220 RHSInheritedProtocols.begin(),
6221 E = RHSInheritedProtocols.end(); I != E; ++I)
6222 if (InheritedProtocolSet.count((*I)))
6223 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006224 }
6225}
6226
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006227/// areCommonBaseCompatible - Returns common base class of the two classes if
6228/// one found. Note that this is O'2 algorithm. But it will be called as the
6229/// last type comparison in a ?-exp of ObjC pointer types before a
6230/// warning is issued. So, its invokation is extremely rare.
6231QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006232 const ObjCObjectPointerType *Lptr,
6233 const ObjCObjectPointerType *Rptr) {
6234 const ObjCObjectType *LHS = Lptr->getObjectType();
6235 const ObjCObjectType *RHS = Rptr->getObjectType();
6236 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6237 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006238 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006239 return QualType();
6240
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006241 do {
John McCall8b07ec22010-05-15 11:32:37 +00006242 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006243 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006244 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006245 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6246
6247 QualType Result = QualType(LHS, 0);
6248 if (!Protocols.empty())
6249 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6250 Result = getObjCObjectPointerType(Result);
6251 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006252 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006253 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006254
6255 return QualType();
6256}
6257
John McCall8b07ec22010-05-15 11:32:37 +00006258bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6259 const ObjCObjectType *RHS) {
6260 assert(LHS->getInterface() && "LHS is not an interface type");
6261 assert(RHS->getInterface() && "RHS is not an interface type");
6262
Chris Lattner49af6a42008-04-07 06:51:04 +00006263 // Verify that the base decls are compatible: the RHS must be a subclass of
6264 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006265 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006266 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006267
Chris Lattner49af6a42008-04-07 06:51:04 +00006268 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6269 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006270 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006271 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006272
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006273 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6274 // more detailed analysis is required.
6275 if (RHS->getNumProtocols() == 0) {
6276 // OK, if LHS is a superclass of RHS *and*
6277 // this superclass is assignment compatible with LHS.
6278 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006279 bool IsSuperClass =
6280 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6281 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006282 // OK if conversion of LHS to SuperClass results in narrowing of types
6283 // ; i.e., SuperClass may implement at least one of the protocols
6284 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6285 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6286 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006287 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006288 // If super class has no protocols, it is not a match.
6289 if (SuperClassInheritedProtocols.empty())
6290 return false;
6291
6292 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6293 LHSPE = LHS->qual_end();
6294 LHSPI != LHSPE; LHSPI++) {
6295 bool SuperImplementsProtocol = false;
6296 ObjCProtocolDecl *LHSProto = (*LHSPI);
6297
6298 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6299 SuperClassInheritedProtocols.begin(),
6300 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6301 ObjCProtocolDecl *SuperClassProto = (*I);
6302 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6303 SuperImplementsProtocol = true;
6304 break;
6305 }
6306 }
6307 if (!SuperImplementsProtocol)
6308 return false;
6309 }
6310 return true;
6311 }
6312 return false;
6313 }
Mike Stump11289f42009-09-09 15:08:12 +00006314
John McCall8b07ec22010-05-15 11:32:37 +00006315 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6316 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006317 LHSPI != LHSPE; LHSPI++) {
6318 bool RHSImplementsProtocol = false;
6319
6320 // If the RHS doesn't implement the protocol on the left, the types
6321 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006322 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6323 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006324 RHSPI != RHSPE; RHSPI++) {
6325 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006326 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006327 break;
6328 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006329 }
6330 // FIXME: For better diagnostics, consider passing back the protocol name.
6331 if (!RHSImplementsProtocol)
6332 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006333 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006334 // The RHS implements all protocols listed on the LHS.
6335 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006336}
6337
Steve Naroffb7605152009-02-12 17:52:19 +00006338bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6339 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006340 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6341 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006342
Steve Naroff7cae42b2009-07-10 23:34:53 +00006343 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006344 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006345
6346 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6347 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006348}
6349
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006350bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6351 return canAssignObjCInterfaces(
6352 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6353 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6354}
6355
Mike Stump11289f42009-09-09 15:08:12 +00006356/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006357/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006358/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006359/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006360bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6361 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006362 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006363 return hasSameType(LHS, RHS);
6364
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006365 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006366}
6367
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006368bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006369 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006370}
6371
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006372bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6373 return !mergeTypes(LHS, RHS, true).isNull();
6374}
6375
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006376/// mergeTransparentUnionType - if T is a transparent union type and a member
6377/// of T is compatible with SubType, return the merged type, else return
6378/// QualType()
6379QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6380 bool OfBlockPointer,
6381 bool Unqualified) {
6382 if (const RecordType *UT = T->getAsUnionType()) {
6383 RecordDecl *UD = UT->getDecl();
6384 if (UD->hasAttr<TransparentUnionAttr>()) {
6385 for (RecordDecl::field_iterator it = UD->field_begin(),
6386 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006387 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006388 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6389 if (!MT.isNull())
6390 return MT;
6391 }
6392 }
6393 }
6394
6395 return QualType();
6396}
6397
6398/// mergeFunctionArgumentTypes - merge two types which appear as function
6399/// argument types
6400QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6401 bool OfBlockPointer,
6402 bool Unqualified) {
6403 // GNU extension: two types are compatible if they appear as a function
6404 // argument, one of the types is a transparent union type and the other
6405 // type is compatible with a union member
6406 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6407 Unqualified);
6408 if (!lmerge.isNull())
6409 return lmerge;
6410
6411 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6412 Unqualified);
6413 if (!rmerge.isNull())
6414 return rmerge;
6415
6416 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6417}
6418
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006419QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006420 bool OfBlockPointer,
6421 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006422 const FunctionType *lbase = lhs->getAs<FunctionType>();
6423 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006424 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6425 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006426 bool allLTypes = true;
6427 bool allRTypes = true;
6428
6429 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006430 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006431 if (OfBlockPointer) {
6432 QualType RHS = rbase->getResultType();
6433 QualType LHS = lbase->getResultType();
6434 bool UnqualifiedResult = Unqualified;
6435 if (!UnqualifiedResult)
6436 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006437 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006438 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006439 else
John McCall8c6b56f2010-12-15 01:06:38 +00006440 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6441 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006442 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006443
6444 if (Unqualified)
6445 retType = retType.getUnqualifiedType();
6446
6447 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6448 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6449 if (Unqualified) {
6450 LRetType = LRetType.getUnqualifiedType();
6451 RRetType = RRetType.getUnqualifiedType();
6452 }
6453
6454 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006455 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006456 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006457 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006458
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006459 // FIXME: double check this
6460 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6461 // rbase->getRegParmAttr() != 0 &&
6462 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006463 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6464 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006465
Douglas Gregor8c940862010-01-18 17:14:39 +00006466 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006467 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006468 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006469
John McCall8c6b56f2010-12-15 01:06:38 +00006470 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006471 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6472 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006473 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6474 return QualType();
6475
John McCall31168b02011-06-15 23:02:42 +00006476 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6477 return QualType();
6478
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006479 // functypes which return are preferred over those that do not.
6480 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6481 allLTypes = false;
6482 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6483 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006484 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6485 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006486
John McCall31168b02011-06-15 23:02:42 +00006487 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006488
Eli Friedman47f77112008-08-22 00:56:42 +00006489 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006490 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6491 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006492 unsigned lproto_nargs = lproto->getNumArgs();
6493 unsigned rproto_nargs = rproto->getNumArgs();
6494
6495 // Compatible functions must have the same number of arguments
6496 if (lproto_nargs != rproto_nargs)
6497 return QualType();
6498
6499 // Variadic and non-variadic functions aren't compatible
6500 if (lproto->isVariadic() != rproto->isVariadic())
6501 return QualType();
6502
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006503 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6504 return QualType();
6505
Fariborz Jahanian97676972011-09-28 21:52:05 +00006506 if (LangOpts.ObjCAutoRefCount &&
6507 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6508 return QualType();
6509
Eli Friedman47f77112008-08-22 00:56:42 +00006510 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006511 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006512 for (unsigned i = 0; i < lproto_nargs; i++) {
6513 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6514 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006515 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6516 OfBlockPointer,
6517 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006518 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006519
6520 if (Unqualified)
6521 argtype = argtype.getUnqualifiedType();
6522
Eli Friedman47f77112008-08-22 00:56:42 +00006523 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006524 if (Unqualified) {
6525 largtype = largtype.getUnqualifiedType();
6526 rargtype = rargtype.getUnqualifiedType();
6527 }
6528
Chris Lattner465fa322008-10-05 17:34:18 +00006529 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6530 allLTypes = false;
6531 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6532 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006533 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006534
Eli Friedman47f77112008-08-22 00:56:42 +00006535 if (allLTypes) return lhs;
6536 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006537
6538 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6539 EPI.ExtInfo = einfo;
6540 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006541 }
6542
6543 if (lproto) allRTypes = false;
6544 if (rproto) allLTypes = false;
6545
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006546 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006547 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006548 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006549 if (proto->isVariadic()) return QualType();
6550 // Check that the types are compatible with the types that
6551 // would result from default argument promotions (C99 6.7.5.3p15).
6552 // The only types actually affected are promotable integer
6553 // types and floats, which would be passed as a different
6554 // type depending on whether the prototype is visible.
6555 unsigned proto_nargs = proto->getNumArgs();
6556 for (unsigned i = 0; i < proto_nargs; ++i) {
6557 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006558
Eli Friedman448ce402012-08-30 00:44:15 +00006559 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006560 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00006561 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6562 argTy = Enum->getDecl()->getIntegerType();
6563 if (argTy.isNull())
6564 return QualType();
6565 }
Douglas Gregor2973d402010-02-03 19:27:29 +00006566
Eli Friedman47f77112008-08-22 00:56:42 +00006567 if (argTy->isPromotableIntegerType() ||
6568 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6569 return QualType();
6570 }
6571
6572 if (allLTypes) return lhs;
6573 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006574
6575 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6576 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006577 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006578 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006579 }
6580
6581 if (allLTypes) return lhs;
6582 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006583 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006584}
6585
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006586QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006587 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006588 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006589 // C++ [expr]: If an expression initially has the type "reference to T", the
6590 // type is adjusted to "T" prior to any further analysis, the expression
6591 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006592 // expression is an lvalue unless the reference is an rvalue reference and
6593 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006594 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6595 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006596
6597 if (Unqualified) {
6598 LHS = LHS.getUnqualifiedType();
6599 RHS = RHS.getUnqualifiedType();
6600 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006601
Eli Friedman47f77112008-08-22 00:56:42 +00006602 QualType LHSCan = getCanonicalType(LHS),
6603 RHSCan = getCanonicalType(RHS);
6604
6605 // If two types are identical, they are compatible.
6606 if (LHSCan == RHSCan)
6607 return LHS;
6608
John McCall8ccfcb52009-09-24 19:53:00 +00006609 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006610 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6611 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006612 if (LQuals != RQuals) {
6613 // If any of these qualifiers are different, we have a type
6614 // mismatch.
6615 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006616 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6617 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006618 return QualType();
6619
6620 // Exactly one GC qualifier difference is allowed: __strong is
6621 // okay if the other type has no GC qualifier but is an Objective
6622 // C object pointer (i.e. implicitly strong by default). We fix
6623 // this by pretending that the unqualified type was actually
6624 // qualified __strong.
6625 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6626 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6627 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6628
6629 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6630 return QualType();
6631
6632 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6633 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6634 }
6635 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6636 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6637 }
Eli Friedman47f77112008-08-22 00:56:42 +00006638 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006639 }
6640
6641 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006642
Eli Friedmandcca6332009-06-01 01:22:52 +00006643 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6644 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006645
Chris Lattnerfd652912008-01-14 05:45:46 +00006646 // We want to consider the two function types to be the same for these
6647 // comparisons, just force one to the other.
6648 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6649 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006650
6651 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006652 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6653 LHSClass = Type::ConstantArray;
6654 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6655 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006656
John McCall8b07ec22010-05-15 11:32:37 +00006657 // ObjCInterfaces are just specialized ObjCObjects.
6658 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6659 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6660
Nate Begemance4d7fc2008-04-18 23:10:10 +00006661 // Canonicalize ExtVector -> Vector.
6662 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6663 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006664
Chris Lattner95554662008-04-07 05:43:21 +00006665 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006666 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006667 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006668 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006669 // Compatibility is based on the underlying type, not the promotion
6670 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006671 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006672 QualType TINT = ETy->getDecl()->getIntegerType();
6673 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006674 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006675 }
John McCall9dd450b2009-09-21 23:43:11 +00006676 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006677 QualType TINT = ETy->getDecl()->getIntegerType();
6678 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006679 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006680 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006681 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006682 if (OfBlockPointer && !BlockReturnType) {
6683 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6684 return LHS;
6685 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6686 return RHS;
6687 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006688
Eli Friedman47f77112008-08-22 00:56:42 +00006689 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006690 }
Eli Friedman47f77112008-08-22 00:56:42 +00006691
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006692 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006693 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006694#define TYPE(Class, Base)
6695#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006696#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006697#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6698#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6699#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006700 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006701
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006702 case Type::LValueReference:
6703 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006704 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006705 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006706
John McCall8b07ec22010-05-15 11:32:37 +00006707 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006708 case Type::IncompleteArray:
6709 case Type::VariableArray:
6710 case Type::FunctionProto:
6711 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006712 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006713
Chris Lattnerfd652912008-01-14 05:45:46 +00006714 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006715 {
6716 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006717 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6718 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006719 if (Unqualified) {
6720 LHSPointee = LHSPointee.getUnqualifiedType();
6721 RHSPointee = RHSPointee.getUnqualifiedType();
6722 }
6723 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6724 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006725 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006726 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006727 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006728 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006729 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006730 return getPointerType(ResultType);
6731 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006732 case Type::BlockPointer:
6733 {
6734 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006735 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6736 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006737 if (Unqualified) {
6738 LHSPointee = LHSPointee.getUnqualifiedType();
6739 RHSPointee = RHSPointee.getUnqualifiedType();
6740 }
6741 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6742 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006743 if (ResultType.isNull()) return QualType();
6744 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6745 return LHS;
6746 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6747 return RHS;
6748 return getBlockPointerType(ResultType);
6749 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006750 case Type::Atomic:
6751 {
6752 // Merge two pointer types, while trying to preserve typedef info
6753 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6754 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6755 if (Unqualified) {
6756 LHSValue = LHSValue.getUnqualifiedType();
6757 RHSValue = RHSValue.getUnqualifiedType();
6758 }
6759 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6760 Unqualified);
6761 if (ResultType.isNull()) return QualType();
6762 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6763 return LHS;
6764 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6765 return RHS;
6766 return getAtomicType(ResultType);
6767 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006768 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006769 {
6770 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6771 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6772 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6773 return QualType();
6774
6775 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6776 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006777 if (Unqualified) {
6778 LHSElem = LHSElem.getUnqualifiedType();
6779 RHSElem = RHSElem.getUnqualifiedType();
6780 }
6781
6782 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006783 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006784 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6785 return LHS;
6786 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6787 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006788 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6789 ArrayType::ArraySizeModifier(), 0);
6790 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6791 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006792 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6793 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006794 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6795 return LHS;
6796 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6797 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006798 if (LVAT) {
6799 // FIXME: This isn't correct! But tricky to implement because
6800 // the array's size has to be the size of LHS, but the type
6801 // has to be different.
6802 return LHS;
6803 }
6804 if (RVAT) {
6805 // FIXME: This isn't correct! But tricky to implement because
6806 // the array's size has to be the size of RHS, but the type
6807 // has to be different.
6808 return RHS;
6809 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006810 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6811 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006812 return getIncompleteArrayType(ResultType,
6813 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006814 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006815 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006816 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006817 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006818 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006819 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006820 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006821 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006822 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006823 case Type::Complex:
6824 // Distinct complex types are incompatible.
6825 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006826 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006827 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006828 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6829 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006830 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006831 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006832 case Type::ObjCObject: {
6833 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006834 // FIXME: This should be type compatibility, e.g. whether
6835 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006836 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6837 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6838 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006839 return LHS;
6840
Eli Friedman47f77112008-08-22 00:56:42 +00006841 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006842 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006843 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006844 if (OfBlockPointer) {
6845 if (canAssignObjCInterfacesInBlockPointer(
6846 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006847 RHS->getAs<ObjCObjectPointerType>(),
6848 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006849 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006850 return QualType();
6851 }
John McCall9dd450b2009-09-21 23:43:11 +00006852 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6853 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006854 return LHS;
6855
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006856 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006857 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006858 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006859
David Blaikie8a40f702012-01-17 06:56:22 +00006860 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006861}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006862
Fariborz Jahanian97676972011-09-28 21:52:05 +00006863bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6864 const FunctionProtoType *FromFunctionType,
6865 const FunctionProtoType *ToFunctionType) {
6866 if (FromFunctionType->hasAnyConsumedArgs() !=
6867 ToFunctionType->hasAnyConsumedArgs())
6868 return false;
6869 FunctionProtoType::ExtProtoInfo FromEPI =
6870 FromFunctionType->getExtProtoInfo();
6871 FunctionProtoType::ExtProtoInfo ToEPI =
6872 ToFunctionType->getExtProtoInfo();
6873 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6874 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6875 ArgIdx != NumArgs; ++ArgIdx) {
6876 if (FromEPI.ConsumedArguments[ArgIdx] !=
6877 ToEPI.ConsumedArguments[ArgIdx])
6878 return false;
6879 }
6880 return true;
6881}
6882
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006883/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6884/// 'RHS' attributes and returns the merged version; including for function
6885/// return types.
6886QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6887 QualType LHSCan = getCanonicalType(LHS),
6888 RHSCan = getCanonicalType(RHS);
6889 // If two types are identical, they are compatible.
6890 if (LHSCan == RHSCan)
6891 return LHS;
6892 if (RHSCan->isFunctionType()) {
6893 if (!LHSCan->isFunctionType())
6894 return QualType();
6895 QualType OldReturnType =
6896 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6897 QualType NewReturnType =
6898 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6899 QualType ResReturnType =
6900 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6901 if (ResReturnType.isNull())
6902 return QualType();
6903 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6904 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6905 // In either case, use OldReturnType to build the new function type.
6906 const FunctionType *F = LHS->getAs<FunctionType>();
6907 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006908 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6909 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006910 QualType ResultType
6911 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006912 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006913 return ResultType;
6914 }
6915 }
6916 return QualType();
6917 }
6918
6919 // If the qualifiers are different, the types can still be merged.
6920 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6921 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6922 if (LQuals != RQuals) {
6923 // If any of these qualifiers are different, we have a type mismatch.
6924 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6925 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6926 return QualType();
6927
6928 // Exactly one GC qualifier difference is allowed: __strong is
6929 // okay if the other type has no GC qualifier but is an Objective
6930 // C object pointer (i.e. implicitly strong by default). We fix
6931 // this by pretending that the unqualified type was actually
6932 // qualified __strong.
6933 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6934 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6935 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6936
6937 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6938 return QualType();
6939
6940 if (GC_L == Qualifiers::Strong)
6941 return LHS;
6942 if (GC_R == Qualifiers::Strong)
6943 return RHS;
6944 return QualType();
6945 }
6946
6947 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6948 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6949 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6950 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6951 if (ResQT == LHSBaseQT)
6952 return LHS;
6953 if (ResQT == RHSBaseQT)
6954 return RHS;
6955 }
6956 return QualType();
6957}
6958
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006959//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006960// Integer Predicates
6961//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006962
Jay Foad39c79802011-01-12 09:06:06 +00006963unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006964 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006965 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006966 if (T->isBooleanType())
6967 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006968 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006969 return (unsigned)getTypeSize(T);
6970}
6971
Abramo Bagnara13640492012-09-09 10:21:24 +00006972QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006973 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006974
6975 // Turn <4 x signed int> -> <4 x unsigned int>
6976 if (const VectorType *VTy = T->getAs<VectorType>())
6977 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006978 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006979
6980 // For enums, we return the unsigned version of the base type.
6981 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006982 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006983
6984 const BuiltinType *BTy = T->getAs<BuiltinType>();
6985 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006986 switch (BTy->getKind()) {
6987 case BuiltinType::Char_S:
6988 case BuiltinType::SChar:
6989 return UnsignedCharTy;
6990 case BuiltinType::Short:
6991 return UnsignedShortTy;
6992 case BuiltinType::Int:
6993 return UnsignedIntTy;
6994 case BuiltinType::Long:
6995 return UnsignedLongTy;
6996 case BuiltinType::LongLong:
6997 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006998 case BuiltinType::Int128:
6999 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007000 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007001 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007002 }
7003}
7004
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007005ASTMutationListener::~ASTMutationListener() { }
7006
Chris Lattnerecd79c62009-06-14 00:45:47 +00007007
7008//===----------------------------------------------------------------------===//
7009// Builtin Type Computation
7010//===----------------------------------------------------------------------===//
7011
7012/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007013/// pointer over the consumed characters. This returns the resultant type. If
7014/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7015/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7016/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007017///
7018/// RequiresICE is filled in on return to indicate whether the value is required
7019/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007020static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007021 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007022 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007023 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007024 // Modifiers.
7025 int HowLong = 0;
7026 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007027 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007028
Chris Lattnerdc226c22010-10-01 22:42:38 +00007029 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007030 bool Done = false;
7031 while (!Done) {
7032 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007033 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007034 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007035 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007036 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007037 case 'S':
7038 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7039 assert(!Signed && "Can't use 'S' modifier multiple times!");
7040 Signed = true;
7041 break;
7042 case 'U':
7043 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7044 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7045 Unsigned = true;
7046 break;
7047 case 'L':
7048 assert(HowLong <= 2 && "Can't have LLLL modifier");
7049 ++HowLong;
7050 break;
7051 }
7052 }
7053
7054 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007055
Chris Lattnerecd79c62009-06-14 00:45:47 +00007056 // Read the base type.
7057 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007058 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007059 case 'v':
7060 assert(HowLong == 0 && !Signed && !Unsigned &&
7061 "Bad modifiers used with 'v'!");
7062 Type = Context.VoidTy;
7063 break;
7064 case 'f':
7065 assert(HowLong == 0 && !Signed && !Unsigned &&
7066 "Bad modifiers used with 'f'!");
7067 Type = Context.FloatTy;
7068 break;
7069 case 'd':
7070 assert(HowLong < 2 && !Signed && !Unsigned &&
7071 "Bad modifiers used with 'd'!");
7072 if (HowLong)
7073 Type = Context.LongDoubleTy;
7074 else
7075 Type = Context.DoubleTy;
7076 break;
7077 case 's':
7078 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7079 if (Unsigned)
7080 Type = Context.UnsignedShortTy;
7081 else
7082 Type = Context.ShortTy;
7083 break;
7084 case 'i':
7085 if (HowLong == 3)
7086 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7087 else if (HowLong == 2)
7088 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7089 else if (HowLong == 1)
7090 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7091 else
7092 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7093 break;
7094 case 'c':
7095 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7096 if (Signed)
7097 Type = Context.SignedCharTy;
7098 else if (Unsigned)
7099 Type = Context.UnsignedCharTy;
7100 else
7101 Type = Context.CharTy;
7102 break;
7103 case 'b': // boolean
7104 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7105 Type = Context.BoolTy;
7106 break;
7107 case 'z': // size_t.
7108 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7109 Type = Context.getSizeType();
7110 break;
7111 case 'F':
7112 Type = Context.getCFConstantStringType();
7113 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007114 case 'G':
7115 Type = Context.getObjCIdType();
7116 break;
7117 case 'H':
7118 Type = Context.getObjCSelType();
7119 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007120 case 'a':
7121 Type = Context.getBuiltinVaListType();
7122 assert(!Type.isNull() && "builtin va list type not initialized!");
7123 break;
7124 case 'A':
7125 // This is a "reference" to a va_list; however, what exactly
7126 // this means depends on how va_list is defined. There are two
7127 // different kinds of va_list: ones passed by value, and ones
7128 // passed by reference. An example of a by-value va_list is
7129 // x86, where va_list is a char*. An example of by-ref va_list
7130 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7131 // we want this argument to be a char*&; for x86-64, we want
7132 // it to be a __va_list_tag*.
7133 Type = Context.getBuiltinVaListType();
7134 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007135 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007136 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007137 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007138 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007139 break;
7140 case 'V': {
7141 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007142 unsigned NumElements = strtoul(Str, &End, 10);
7143 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007144 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007145
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007146 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7147 RequiresICE, false);
7148 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007149
7150 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007151 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007152 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007153 break;
7154 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007155 case 'E': {
7156 char *End;
7157
7158 unsigned NumElements = strtoul(Str, &End, 10);
7159 assert(End != Str && "Missing vector size");
7160
7161 Str = End;
7162
7163 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7164 false);
7165 Type = Context.getExtVectorType(ElementType, NumElements);
7166 break;
7167 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007168 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007169 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7170 false);
7171 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007172 Type = Context.getComplexType(ElementType);
7173 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007174 }
7175 case 'Y' : {
7176 Type = Context.getPointerDiffType();
7177 break;
7178 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007179 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007180 Type = Context.getFILEType();
7181 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007182 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007183 return QualType();
7184 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007185 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007186 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007187 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007188 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007189 else
7190 Type = Context.getjmp_bufType();
7191
Mike Stump2adb4da2009-07-28 23:47:15 +00007192 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007193 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007194 return QualType();
7195 }
7196 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007197 case 'K':
7198 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7199 Type = Context.getucontext_tType();
7200
7201 if (Type.isNull()) {
7202 Error = ASTContext::GE_Missing_ucontext;
7203 return QualType();
7204 }
7205 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007206 }
Mike Stump11289f42009-09-09 15:08:12 +00007207
Chris Lattnerdc226c22010-10-01 22:42:38 +00007208 // If there are modifiers and if we're allowed to parse them, go for it.
7209 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007210 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007211 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007212 default: Done = true; --Str; break;
7213 case '*':
7214 case '&': {
7215 // Both pointers and references can have their pointee types
7216 // qualified with an address space.
7217 char *End;
7218 unsigned AddrSpace = strtoul(Str, &End, 10);
7219 if (End != Str && AddrSpace != 0) {
7220 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7221 Str = End;
7222 }
7223 if (c == '*')
7224 Type = Context.getPointerType(Type);
7225 else
7226 Type = Context.getLValueReferenceType(Type);
7227 break;
7228 }
7229 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7230 case 'C':
7231 Type = Type.withConst();
7232 break;
7233 case 'D':
7234 Type = Context.getVolatileType(Type);
7235 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007236 case 'R':
7237 Type = Type.withRestrict();
7238 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007239 }
7240 }
Chris Lattner84733392010-10-01 07:13:18 +00007241
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007242 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007243 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007244
Chris Lattnerecd79c62009-06-14 00:45:47 +00007245 return Type;
7246}
7247
7248/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007249QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007250 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007251 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007252 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007253
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007254 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007255
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007256 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007257 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007258 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7259 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007260 if (Error != GE_None)
7261 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007262
7263 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7264
Chris Lattnerecd79c62009-06-14 00:45:47 +00007265 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007266 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007267 if (Error != GE_None)
7268 return QualType();
7269
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007270 // If this argument is required to be an IntegerConstantExpression and the
7271 // caller cares, fill in the bitmask we return.
7272 if (RequiresICE && IntegerConstantArgs)
7273 *IntegerConstantArgs |= 1 << ArgTypes.size();
7274
Chris Lattnerecd79c62009-06-14 00:45:47 +00007275 // Do array -> pointer decay. The builtin should use the decayed type.
7276 if (Ty->isArrayType())
7277 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007278
Chris Lattnerecd79c62009-06-14 00:45:47 +00007279 ArgTypes.push_back(Ty);
7280 }
7281
7282 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7283 "'.' should only occur at end of builtin type list!");
7284
John McCall991eb4b2010-12-21 00:44:39 +00007285 FunctionType::ExtInfo EI;
7286 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7287
7288 bool Variadic = (TypeStr[0] == '.');
7289
7290 // We really shouldn't be making a no-proto type here, especially in C++.
7291 if (ArgTypes.empty() && Variadic)
7292 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007293
John McCalldb40c7f2010-12-14 08:05:40 +00007294 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007295 EPI.ExtInfo = EI;
7296 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007297
7298 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007299}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007300
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007301GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7302 GVALinkage External = GVA_StrongExternal;
7303
7304 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007305 switch (L) {
7306 case NoLinkage:
7307 case InternalLinkage:
7308 case UniqueExternalLinkage:
7309 return GVA_Internal;
7310
7311 case ExternalLinkage:
7312 switch (FD->getTemplateSpecializationKind()) {
7313 case TSK_Undeclared:
7314 case TSK_ExplicitSpecialization:
7315 External = GVA_StrongExternal;
7316 break;
7317
7318 case TSK_ExplicitInstantiationDefinition:
7319 return GVA_ExplicitTemplateInstantiation;
7320
7321 case TSK_ExplicitInstantiationDeclaration:
7322 case TSK_ImplicitInstantiation:
7323 External = GVA_TemplateInstantiation;
7324 break;
7325 }
7326 }
7327
7328 if (!FD->isInlined())
7329 return External;
7330
David Blaikiebbafb8a2012-03-11 07:00:24 +00007331 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007332 // GNU or C99 inline semantics. Determine whether this symbol should be
7333 // externally visible.
7334 if (FD->isInlineDefinitionExternallyVisible())
7335 return External;
7336
7337 // C99 inline semantics, where the symbol is not externally visible.
7338 return GVA_C99Inline;
7339 }
7340
7341 // C++0x [temp.explicit]p9:
7342 // [ Note: The intent is that an inline function that is the subject of
7343 // an explicit instantiation declaration will still be implicitly
7344 // instantiated when used so that the body can be considered for
7345 // inlining, but that no out-of-line copy of the inline function would be
7346 // generated in the translation unit. -- end note ]
7347 if (FD->getTemplateSpecializationKind()
7348 == TSK_ExplicitInstantiationDeclaration)
7349 return GVA_C99Inline;
7350
7351 return GVA_CXXInline;
7352}
7353
7354GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7355 // If this is a static data member, compute the kind of template
7356 // specialization. Otherwise, this variable is not part of a
7357 // template.
7358 TemplateSpecializationKind TSK = TSK_Undeclared;
7359 if (VD->isStaticDataMember())
7360 TSK = VD->getTemplateSpecializationKind();
7361
7362 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007363 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007364 VD->getType()->getLinkage() == UniqueExternalLinkage)
7365 L = UniqueExternalLinkage;
7366
7367 switch (L) {
7368 case NoLinkage:
7369 case InternalLinkage:
7370 case UniqueExternalLinkage:
7371 return GVA_Internal;
7372
7373 case ExternalLinkage:
7374 switch (TSK) {
7375 case TSK_Undeclared:
7376 case TSK_ExplicitSpecialization:
7377 return GVA_StrongExternal;
7378
7379 case TSK_ExplicitInstantiationDeclaration:
7380 llvm_unreachable("Variable should not be instantiated");
7381 // Fall through to treat this like any other instantiation.
7382
7383 case TSK_ExplicitInstantiationDefinition:
7384 return GVA_ExplicitTemplateInstantiation;
7385
7386 case TSK_ImplicitInstantiation:
7387 return GVA_TemplateInstantiation;
7388 }
7389 }
7390
David Blaikie8a40f702012-01-17 06:56:22 +00007391 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007392}
7393
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007394bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007395 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7396 if (!VD->isFileVarDecl())
7397 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007398 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007399 return false;
7400
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007401 // Weak references don't produce any output by themselves.
7402 if (D->hasAttr<WeakRefAttr>())
7403 return false;
7404
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007405 // Aliases and used decls are required.
7406 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7407 return true;
7408
7409 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7410 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007411 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007412 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007413
7414 // Constructors and destructors are required.
7415 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7416 return true;
7417
7418 // The key function for a class is required.
7419 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7420 const CXXRecordDecl *RD = MD->getParent();
7421 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7422 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7423 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7424 return true;
7425 }
7426 }
7427
7428 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7429
7430 // static, static inline, always_inline, and extern inline functions can
7431 // always be deferred. Normal inline functions can be deferred in C99/C++.
7432 // Implicit template instantiations can also be deferred in C++.
7433 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007434 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007435 return false;
7436 return true;
7437 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007438
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007439 const VarDecl *VD = cast<VarDecl>(D);
7440 assert(VD->isFileVarDecl() && "Expected file scoped var");
7441
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007442 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7443 return false;
7444
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007445 // Structs that have non-trivial constructors or destructors are required.
7446
7447 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007448 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007449 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7450 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007451 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7452 RD->hasTrivialCopyConstructor() &&
7453 RD->hasTrivialMoveConstructor() &&
7454 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007455 return true;
7456 }
7457 }
7458
7459 GVALinkage L = GetGVALinkageForVariable(VD);
7460 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7461 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7462 return false;
7463 }
7464
7465 return true;
7466}
Charles Davis53c59df2010-08-16 03:33:14 +00007467
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007468CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007469 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007470 return ABI->getDefaultMethodCallConv(isVariadic);
7471}
7472
7473CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7474 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7475 return CC_Default;
7476 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007477}
7478
Jay Foad39c79802011-01-12 09:06:06 +00007479bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007480 // Pass through to the C++ ABI object
7481 return ABI->isNearlyEmpty(RD);
7482}
7483
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007484MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007485 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007486 case CXXABI_ARM:
7487 case CXXABI_Itanium:
7488 return createItaniumMangleContext(*this, getDiagnostics());
7489 case CXXABI_Microsoft:
7490 return createMicrosoftMangleContext(*this, getDiagnostics());
7491 }
David Blaikie83d382b2011-09-23 05:06:16 +00007492 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007493}
7494
Charles Davis53c59df2010-08-16 03:33:14 +00007495CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007496
7497size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007498 return ASTRecordLayouts.getMemorySize()
7499 + llvm::capacity_in_bytes(ObjCLayouts)
7500 + llvm::capacity_in_bytes(KeyFunctions)
7501 + llvm::capacity_in_bytes(ObjCImpls)
7502 + llvm::capacity_in_bytes(BlockVarCopyInits)
7503 + llvm::capacity_in_bytes(DeclAttrs)
7504 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7505 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7506 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7507 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7508 + llvm::capacity_in_bytes(OverriddenMethods)
7509 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007510 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007511 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007512}
Ted Kremenek540017e2011-10-06 05:00:56 +00007513
Douglas Gregor63798542012-02-20 19:44:39 +00007514unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7515 CXXRecordDecl *Lambda = CallOperator->getParent();
7516 return LambdaMangleContexts[Lambda->getDeclContext()]
7517 .getManglingNumber(CallOperator);
7518}
7519
7520
Ted Kremenek540017e2011-10-06 05:00:56 +00007521void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7522 ParamIndices[D] = index;
7523}
7524
7525unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7526 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7527 assert(I != ParamIndices.end() &&
7528 "ParmIndices lacks entry set by ParmVarDecl");
7529 return I->second;
7530}