blob: 5b57ce45577e0b48931163bc0c65178234e8e683 [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 Gribenkoec925312012-07-06 00:28:32 +000016#include "clang/AST/CommentLexer.h"
17#include "clang/AST/CommentSema.h"
18#include "clang/AST/CommentParser.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000019#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000021#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000022#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000023#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000024#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000025#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000026#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000027#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000029#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000031#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000033#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000034#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000035#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000036#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000037#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000038#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000039
Chris Lattnerddc135e2006-11-10 06:34:16 +000040using namespace clang;
41
Douglas Gregor9672f922010-07-03 00:47:00 +000042unsigned ASTContext::NumImplicitDefaultConstructors;
43unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000044unsigned ASTContext::NumImplicitCopyConstructors;
45unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveConstructors;
47unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000048unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000052unsigned ASTContext::NumImplicitDestructors;
53unsigned ASTContext::NumImplicitDestructorsDeclared;
54
Steve Naroff0af91202007-04-27 21:51:21 +000055enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000056 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000057};
58
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000059RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000060 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
63 }
64
65 assert(D);
66
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000067 // User can not attach documentation to implicit declarations.
68 if (D->isImplicit())
69 return NULL;
70
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000071 // TODO: handle comments for function parameters properly.
72 if (isa<ParmVarDecl>(D))
73 return NULL;
74
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +000075 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000076
77 // If there are no comments anywhere, we won't find anything.
78 if (RawComments.empty())
79 return NULL;
80
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +000081 // Find declaration location.
82 // For Objective-C declarations we generally don't expect to have multiple
83 // declarators, thus use declaration starting location as the "declaration
84 // location".
85 // For all other declarations multiple declarators are used quite frequently,
86 // so we use the location of the identifier as the "declaration location".
87 SourceLocation DeclLoc;
88 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
89 isa<ObjCPropertyDecl>(D))
90 DeclLoc = D->getLocStart();
91 else
92 DeclLoc = D->getLocation();
93
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000094 // If the declaration doesn't map directly to a location in a file, we
95 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000096 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
97 return NULL;
98
99 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000100 ArrayRef<RawComment *>::iterator Comment;
101 {
102 // When searching for comments during parsing, the comment we are looking
103 // for is usually among the last two comments we parsed -- check them
104 // first.
105 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
106 BeforeThanCompare<RawComment> Compare(SourceMgr);
107 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
108 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
109 if (!Found && RawComments.size() >= 2) {
110 MaybeBeforeDecl--;
111 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
112 }
113
114 if (Found) {
115 Comment = MaybeBeforeDecl + 1;
116 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
117 &CommentAtDeclLoc, Compare));
118 } else {
119 // Slow path.
120 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
121 &CommentAtDeclLoc, Compare);
122 }
123 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000124
125 // Decompose the location for the declaration and find the beginning of the
126 // file buffer.
127 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
128
129 // First check whether we have a trailing comment.
130 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000131 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000132 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000133 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000134 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000135 // Check that Doxygen trailing comment comes after the declaration, starts
136 // on the same line and in the same file as the declaration.
137 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
138 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
139 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
140 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000141 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000142 }
143 }
144
145 // The comment just after the declaration was not a trailing comment.
146 // Let's look at the previous comment.
147 if (Comment == RawComments.begin())
148 return NULL;
149 --Comment;
150
151 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000152 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000153 return NULL;
154
155 // Decompose the end of the comment.
156 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000157 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000158
159 // If the comment and the declaration aren't in the same file, then they
160 // aren't related.
161 if (DeclLocDecomp.first != CommentEndDecomp.first)
162 return NULL;
163
164 // Get the corresponding buffer.
165 bool Invalid = false;
166 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
167 &Invalid).data();
168 if (Invalid)
169 return NULL;
170
171 // Extract text between the comment and declaration.
172 StringRef Text(Buffer + CommentEndDecomp.second,
173 DeclLocDecomp.second - CommentEndDecomp.second);
174
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000175 // There should be no other declarations or preprocessor directives between
176 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000177 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000178 return NULL;
179
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000180 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000181}
182
183const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const {
184 // Check whether we have cached a comment string for this declaration
185 // already.
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000186 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000187 = DeclComments.find(D);
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000188 if (Pos != DeclComments.end()) {
189 RawAndParsedComment C = Pos->second;
190 return C.first;
191 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000192
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000193 RawComment *RC = getRawCommentForDeclNoCache(D);
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000194 // If we found a comment, it should be a documentation comment.
195 assert(!RC || RC->isDocumentation());
Dmitri Gribenko08630052012-07-06 15:40:08 +0000196 DeclComments[D] =
197 RawAndParsedComment(RC, static_cast<comments::FullComment *>(NULL));
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000198 if (RC)
199 RC->setAttached();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000200 return RC;
201}
202
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000203comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const {
204 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
205 = DeclComments.find(D);
206 const RawComment *RC;
207 if (Pos != DeclComments.end()) {
208 RawAndParsedComment C = Pos->second;
209 if (comments::FullComment *FC = C.second)
210 return FC;
211 RC = C.first;
212 } else
213 RC = getRawCommentForDecl(D);
214
215 if (!RC)
216 return NULL;
217
218 const StringRef RawText = RC->getRawText(SourceMgr);
219 comments::Lexer L(RC->getSourceRange().getBegin(), comments::CommentOptions(),
220 RawText.begin(), RawText.end());
221
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000222 comments::Sema S(getAllocator(), getSourceManager(), getDiagnostics());
223 S.setDecl(D);
224 comments::Parser P(L, S, getAllocator(), getSourceManager(),
225 getDiagnostics());
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000226
227 comments::FullComment *FC = P.parseFullComment();
228 DeclComments[D].second = FC;
229 return FC;
230}
231
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000232void
233ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
234 TemplateTemplateParmDecl *Parm) {
235 ID.AddInteger(Parm->getDepth());
236 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000237 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000238
239 TemplateParameterList *Params = Parm->getTemplateParameters();
240 ID.AddInteger(Params->size());
241 for (TemplateParameterList::const_iterator P = Params->begin(),
242 PEnd = Params->end();
243 P != PEnd; ++P) {
244 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
245 ID.AddInteger(0);
246 ID.AddBoolean(TTP->isParameterPack());
247 continue;
248 }
249
250 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
251 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000252 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000253 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000254 if (NTTP->isExpandedParameterPack()) {
255 ID.AddBoolean(true);
256 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000257 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
258 QualType T = NTTP->getExpansionType(I);
259 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
260 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000261 } else
262 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000263 continue;
264 }
265
266 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
267 ID.AddInteger(2);
268 Profile(ID, TTP);
269 }
270}
271
272TemplateTemplateParmDecl *
273ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000274 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000275 // Check if we already have a canonical template template parameter.
276 llvm::FoldingSetNodeID ID;
277 CanonicalTemplateTemplateParm::Profile(ID, TTP);
278 void *InsertPos = 0;
279 CanonicalTemplateTemplateParm *Canonical
280 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
281 if (Canonical)
282 return Canonical->getParam();
283
284 // Build a canonical template parameter list.
285 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000286 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000287 CanonParams.reserve(Params->size());
288 for (TemplateParameterList::const_iterator P = Params->begin(),
289 PEnd = Params->end();
290 P != PEnd; ++P) {
291 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
292 CanonParams.push_back(
293 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000294 SourceLocation(),
295 SourceLocation(),
296 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000297 TTP->getIndex(), 0, false,
298 TTP->isParameterPack()));
299 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000300 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
301 QualType T = getCanonicalType(NTTP->getType());
302 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
303 NonTypeTemplateParmDecl *Param;
304 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000305 SmallVector<QualType, 2> ExpandedTypes;
306 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000307 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
308 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
309 ExpandedTInfos.push_back(
310 getTrivialTypeSourceInfo(ExpandedTypes.back()));
311 }
312
313 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000314 SourceLocation(),
315 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000316 NTTP->getDepth(),
317 NTTP->getPosition(), 0,
318 T,
319 TInfo,
320 ExpandedTypes.data(),
321 ExpandedTypes.size(),
322 ExpandedTInfos.data());
323 } else {
324 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000325 SourceLocation(),
326 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000327 NTTP->getDepth(),
328 NTTP->getPosition(), 0,
329 T,
330 NTTP->isParameterPack(),
331 TInfo);
332 }
333 CanonParams.push_back(Param);
334
335 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000336 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
337 cast<TemplateTemplateParmDecl>(*P)));
338 }
339
340 TemplateTemplateParmDecl *CanonTTP
341 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
342 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000343 TTP->getPosition(),
344 TTP->isParameterPack(),
345 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000346 TemplateParameterList::Create(*this, SourceLocation(),
347 SourceLocation(),
348 CanonParams.data(),
349 CanonParams.size(),
350 SourceLocation()));
351
352 // Get the new insert position for the node we care about.
353 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
354 assert(Canonical == 0 && "Shouldn't be in the map!");
355 (void)Canonical;
356
357 // Create the canonical template template parameter entry.
358 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
359 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
360 return CanonTTP;
361}
362
Charles Davis53c59df2010-08-16 03:33:14 +0000363CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000364 if (!LangOpts.CPlusPlus) return 0;
365
Charles Davis6bcb07a2010-08-19 02:18:14 +0000366 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000367 case CXXABI_ARM:
368 return CreateARMCXXABI(*this);
369 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000370 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000371 case CXXABI_Microsoft:
372 return CreateMicrosoftCXXABI(*this);
373 }
David Blaikie8a40f702012-01-17 06:56:22 +0000374 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000375}
376
Douglas Gregore8bbc122011-09-02 00:18:52 +0000377static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000378 const LangOptions &LOpts) {
379 if (LOpts.FakeAddressSpaceMap) {
380 // The fake address space map must have a distinct entry for each
381 // language-specific address space.
382 static const unsigned FakeAddrSpaceMap[] = {
383 1, // opencl_global
384 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000385 3, // opencl_constant
386 4, // cuda_device
387 5, // cuda_constant
388 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000389 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000390 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000391 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000392 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000393 }
394}
395
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000396ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000397 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000398 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000399 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000400 unsigned size_reserve,
401 bool DelayInitialization)
402 : FunctionProtoTypes(this_()),
403 TemplateSpecializationTypes(this_()),
404 DependentTemplateSpecializationTypes(this_()),
405 SubstTemplateTemplateParmPacks(this_()),
406 GlobalNestedNameSpecifier(0),
407 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000408 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000409 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000410 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000411 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000412 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
413 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
414 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000415 NullTypeSourceInfo(QualType()),
416 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000417 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000418 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000419 Idents(idents), Selectors(sels),
420 BuiltinInfo(builtins),
421 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000422 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000423 Comments(SM), CommentsLoaded(false),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000424 LastSDM(0, 0),
425 UniqueBlockByRefTypeID(0)
426{
Mike Stump11289f42009-09-09 15:08:12 +0000427 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000428 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000429
430 if (!DelayInitialization) {
431 assert(t && "No target supplied for ASTContext initialization");
432 InitBuiltinTypes(*t);
433 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000434}
435
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000436ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000437 // Release the DenseMaps associated with DeclContext objects.
438 // FIXME: Is this the ideal solution?
439 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000440
Douglas Gregor5b11d492010-07-25 17:53:33 +0000441 // Call all of the deallocation functions.
442 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
443 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000444
Ted Kremenek076baeb2010-06-08 23:00:58 +0000445 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000446 // because they can contain DenseMaps.
447 for (llvm::DenseMap<const ObjCContainerDecl*,
448 const ASTRecordLayout*>::iterator
449 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
450 // Increment in loop to prevent using deallocated memory.
451 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
452 R->Destroy(*this);
453
Ted Kremenek076baeb2010-06-08 23:00:58 +0000454 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
455 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
456 // Increment in loop to prevent using deallocated memory.
457 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
458 R->Destroy(*this);
459 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000460
461 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
462 AEnd = DeclAttrs.end();
463 A != AEnd; ++A)
464 A->second->~AttrVec();
465}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000466
Douglas Gregor1a809332010-05-23 18:26:36 +0000467void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
468 Deallocations.push_back(std::make_pair(Callback, Data));
469}
470
Mike Stump11289f42009-09-09 15:08:12 +0000471void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000472ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000473 ExternalSource.reset(Source.take());
474}
475
Chris Lattner4eb445d2007-01-26 01:27:23 +0000476void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000477 llvm::errs() << "\n*** AST Context Stats:\n";
478 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000479
Douglas Gregora30d0462009-05-26 14:40:08 +0000480 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000481#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000482#define ABSTRACT_TYPE(Name, Parent)
483#include "clang/AST/TypeNodes.def"
484 0 // Extra
485 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000486
Chris Lattner4eb445d2007-01-26 01:27:23 +0000487 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
488 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000489 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000490 }
491
Douglas Gregora30d0462009-05-26 14:40:08 +0000492 unsigned Idx = 0;
493 unsigned TotalBytes = 0;
494#define TYPE(Name, Parent) \
495 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000496 llvm::errs() << " " << counts[Idx] << " " << #Name \
497 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000498 TotalBytes += counts[Idx] * sizeof(Name##Type); \
499 ++Idx;
500#define ABSTRACT_TYPE(Name, Parent)
501#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000502
Chandler Carruth3c147a72011-07-04 05:32:14 +0000503 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
504
Douglas Gregor7454c562010-07-02 20:37:36 +0000505 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000506 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
507 << NumImplicitDefaultConstructors
508 << " implicit default constructors created\n";
509 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
510 << NumImplicitCopyConstructors
511 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000512 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000513 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
514 << NumImplicitMoveConstructors
515 << " implicit move constructors created\n";
516 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
517 << NumImplicitCopyAssignmentOperators
518 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000519 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000520 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
521 << NumImplicitMoveAssignmentOperators
522 << " implicit move assignment operators created\n";
523 llvm::errs() << NumImplicitDestructorsDeclared << "/"
524 << NumImplicitDestructors
525 << " implicit destructors created\n";
526
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000527 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000528 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000529 ExternalSource->PrintStats();
530 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000531
Douglas Gregor5b11d492010-07-25 17:53:33 +0000532 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000533}
534
Douglas Gregor801c99d2011-08-12 06:49:56 +0000535TypedefDecl *ASTContext::getInt128Decl() const {
536 if (!Int128Decl) {
537 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
538 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
539 getTranslationUnitDecl(),
540 SourceLocation(),
541 SourceLocation(),
542 &Idents.get("__int128_t"),
543 TInfo);
544 }
545
546 return Int128Decl;
547}
548
549TypedefDecl *ASTContext::getUInt128Decl() const {
550 if (!UInt128Decl) {
551 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
552 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
553 getTranslationUnitDecl(),
554 SourceLocation(),
555 SourceLocation(),
556 &Idents.get("__uint128_t"),
557 TInfo);
558 }
559
560 return UInt128Decl;
561}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000562
John McCall48f2d582009-10-23 23:03:21 +0000563void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000564 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000565 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000566 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000567}
568
Douglas Gregore8bbc122011-09-02 00:18:52 +0000569void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
570 assert((!this->Target || this->Target == &Target) &&
571 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000572 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000573
Douglas Gregore8bbc122011-09-02 00:18:52 +0000574 this->Target = &Target;
575
576 ABI.reset(createCXXABI(Target));
577 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
578
Chris Lattner970e54e2006-11-12 00:37:36 +0000579 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000580 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000581
Chris Lattner970e54e2006-11-12 00:37:36 +0000582 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000583 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000584 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000585 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000586 InitBuiltinType(CharTy, BuiltinType::Char_S);
587 else
588 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000589 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000590 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
591 InitBuiltinType(ShortTy, BuiltinType::Short);
592 InitBuiltinType(IntTy, BuiltinType::Int);
593 InitBuiltinType(LongTy, BuiltinType::Long);
594 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000595
Chris Lattner970e54e2006-11-12 00:37:36 +0000596 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000597 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
598 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
599 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
600 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
601 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000602
Chris Lattner970e54e2006-11-12 00:37:36 +0000603 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000604 InitBuiltinType(FloatTy, BuiltinType::Float);
605 InitBuiltinType(DoubleTy, BuiltinType::Double);
606 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000607
Chris Lattnerf122cef2009-04-30 02:43:43 +0000608 // GNU extension, 128-bit integers.
609 InitBuiltinType(Int128Ty, BuiltinType::Int128);
610 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
611
Chris Lattnerad3467e2010-12-25 23:25:43 +0000612 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000613 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000614 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
615 else // -fshort-wchar makes wchar_t be unsigned.
616 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
617 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000618 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000619
James Molloy36365542012-05-04 10:55:22 +0000620 WIntTy = getFromTargetType(Target.getWIntType());
621
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000622 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
623 InitBuiltinType(Char16Ty, BuiltinType::Char16);
624 else // C99
625 Char16Ty = getFromTargetType(Target.getChar16Type());
626
627 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
628 InitBuiltinType(Char32Ty, BuiltinType::Char32);
629 else // C99
630 Char32Ty = getFromTargetType(Target.getChar32Type());
631
Douglas Gregor4619e432008-12-05 23:32:09 +0000632 // Placeholder type for type-dependent expressions whose type is
633 // completely unknown. No code should ever check a type against
634 // DependentTy and users should never see it; however, it is here to
635 // help diagnose failures to properly check for type-dependent
636 // expressions.
637 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000638
John McCall36e7fe32010-10-12 00:20:44 +0000639 // Placeholder type for functions.
640 InitBuiltinType(OverloadTy, BuiltinType::Overload);
641
John McCall0009fcc2011-04-26 20:42:42 +0000642 // Placeholder type for bound members.
643 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
644
John McCall526ab472011-10-25 17:37:35 +0000645 // Placeholder type for pseudo-objects.
646 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
647
John McCall31996342011-04-07 08:22:57 +0000648 // "any" type; useful for debugger-like clients.
649 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
650
John McCall8a6b59a2011-10-17 18:09:15 +0000651 // Placeholder type for unbridged ARC casts.
652 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
653
Chris Lattner970e54e2006-11-12 00:37:36 +0000654 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000655 FloatComplexTy = getComplexType(FloatTy);
656 DoubleComplexTy = getComplexType(DoubleTy);
657 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000658
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000659 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000660 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
661 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000662 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000663
664 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000665 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
666 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000667
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000668 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000669
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000670 // void * type
671 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000672
673 // nullptr type (C++0x 2.14.7)
674 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000675
676 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
677 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000678
679 // Builtin type used to help define __builtin_va_list.
680 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000681}
682
David Blaikie9c902b52011-09-25 23:23:43 +0000683DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000684 return SourceMgr.getDiagnostics();
685}
686
Douglas Gregor561eceb2010-08-30 16:49:28 +0000687AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
688 AttrVec *&Result = DeclAttrs[D];
689 if (!Result) {
690 void *Mem = Allocate(sizeof(AttrVec));
691 Result = new (Mem) AttrVec;
692 }
693
694 return *Result;
695}
696
697/// \brief Erase the attributes corresponding to the given declaration.
698void ASTContext::eraseDeclAttrs(const Decl *D) {
699 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
700 if (Pos != DeclAttrs.end()) {
701 Pos->second->~AttrVec();
702 DeclAttrs.erase(Pos);
703 }
704}
705
Douglas Gregor86d142a2009-10-08 07:24:58 +0000706MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000707ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000708 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000709 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000710 = InstantiatedFromStaticDataMember.find(Var);
711 if (Pos == InstantiatedFromStaticDataMember.end())
712 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000713
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000714 return Pos->second;
715}
716
Mike Stump11289f42009-09-09 15:08:12 +0000717void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000718ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000719 TemplateSpecializationKind TSK,
720 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000721 assert(Inst->isStaticDataMember() && "Not a static data member");
722 assert(Tmpl->isStaticDataMember() && "Not a static data member");
723 assert(!InstantiatedFromStaticDataMember[Inst] &&
724 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000725 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000726 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000727}
728
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000729FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
730 const FunctionDecl *FD){
731 assert(FD && "Specialization is 0");
732 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000733 = ClassScopeSpecializationPattern.find(FD);
734 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000735 return 0;
736
737 return Pos->second;
738}
739
740void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
741 FunctionDecl *Pattern) {
742 assert(FD && "Specialization is 0");
743 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000744 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000745}
746
John McCalle61f2ba2009-11-18 02:36:19 +0000747NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000748ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000749 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000750 = InstantiatedFromUsingDecl.find(UUD);
751 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000752 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000753
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000754 return Pos->second;
755}
756
757void
John McCallb96ec562009-12-04 22:46:56 +0000758ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
759 assert((isa<UsingDecl>(Pattern) ||
760 isa<UnresolvedUsingValueDecl>(Pattern) ||
761 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
762 "pattern decl is not a using decl");
763 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
764 InstantiatedFromUsingDecl[Inst] = Pattern;
765}
766
767UsingShadowDecl *
768ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
769 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
770 = InstantiatedFromUsingShadowDecl.find(Inst);
771 if (Pos == InstantiatedFromUsingShadowDecl.end())
772 return 0;
773
774 return Pos->second;
775}
776
777void
778ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
779 UsingShadowDecl *Pattern) {
780 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
781 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000782}
783
Anders Carlsson5da84842009-09-01 04:26:58 +0000784FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
785 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
786 = InstantiatedFromUnnamedFieldDecl.find(Field);
787 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
788 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000789
Anders Carlsson5da84842009-09-01 04:26:58 +0000790 return Pos->second;
791}
792
793void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
794 FieldDecl *Tmpl) {
795 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
796 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
797 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
798 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000799
Anders Carlsson5da84842009-09-01 04:26:58 +0000800 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
801}
802
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000803bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
804 const FieldDecl *LastFD) const {
805 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000806 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000807}
808
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000809bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
810 const FieldDecl *LastFD) const {
811 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000812 FD->getBitWidthValue(*this) == 0 &&
813 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000814}
815
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000816bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
817 const FieldDecl *LastFD) const {
818 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000819 FD->getBitWidthValue(*this) &&
820 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000821}
822
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000823bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000824 const FieldDecl *LastFD) const {
825 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000826 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000827}
828
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000829bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000830 const FieldDecl *LastFD) const {
831 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000832 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000833}
834
Douglas Gregor832940b2010-03-02 23:58:15 +0000835ASTContext::overridden_cxx_method_iterator
836ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
837 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
838 = OverriddenMethods.find(Method);
839 if (Pos == OverriddenMethods.end())
840 return 0;
841
842 return Pos->second.begin();
843}
844
845ASTContext::overridden_cxx_method_iterator
846ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
847 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
848 = OverriddenMethods.find(Method);
849 if (Pos == OverriddenMethods.end())
850 return 0;
851
852 return Pos->second.end();
853}
854
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000855unsigned
856ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
857 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
858 = OverriddenMethods.find(Method);
859 if (Pos == OverriddenMethods.end())
860 return 0;
861
862 return Pos->second.size();
863}
864
Douglas Gregor832940b2010-03-02 23:58:15 +0000865void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
866 const CXXMethodDecl *Overridden) {
867 OverriddenMethods[Method].push_back(Overridden);
868}
869
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000870void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
871 assert(!Import->NextLocalImport && "Import declaration already in the chain");
872 assert(!Import->isFromASTFile() && "Non-local import declaration");
873 if (!FirstLocalImport) {
874 FirstLocalImport = Import;
875 LastLocalImport = Import;
876 return;
877 }
878
879 LastLocalImport->NextLocalImport = Import;
880 LastLocalImport = Import;
881}
882
Chris Lattner53cfe802007-07-18 17:52:12 +0000883//===----------------------------------------------------------------------===//
884// Type Sizing and Analysis
885//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000886
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000887/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
888/// scalar floating point type.
889const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000890 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000891 assert(BT && "Not a floating point type!");
892 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000893 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000894 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000895 case BuiltinType::Float: return Target->getFloatFormat();
896 case BuiltinType::Double: return Target->getDoubleFormat();
897 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000898 }
899}
900
Ken Dyck160146e2010-01-27 17:10:57 +0000901/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000902/// specified decl. Note that bitfields do not have a valid alignment, so
903/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000904/// If @p RefAsPointee, references are treated like their underlying type
905/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000906CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000907 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000908
John McCall94268702010-10-08 18:24:19 +0000909 bool UseAlignAttrOnly = false;
910 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
911 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000912
John McCall94268702010-10-08 18:24:19 +0000913 // __attribute__((aligned)) can increase or decrease alignment
914 // *except* on a struct or struct member, where it only increases
915 // alignment unless 'packed' is also specified.
916 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000917 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000918 // ignore that possibility; Sema should diagnose it.
919 if (isa<FieldDecl>(D)) {
920 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
921 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
922 } else {
923 UseAlignAttrOnly = true;
924 }
925 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000926 else if (isa<FieldDecl>(D))
927 UseAlignAttrOnly =
928 D->hasAttr<PackedAttr>() ||
929 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000930
John McCall4e819612011-01-20 07:57:12 +0000931 // If we're using the align attribute only, just ignore everything
932 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000933 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000934 // do nothing
935
John McCall94268702010-10-08 18:24:19 +0000936 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000937 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000938 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000939 if (RefAsPointee)
940 T = RT->getPointeeType();
941 else
942 T = getPointerType(RT->getPointeeType());
943 }
944 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000945 // Adjust alignments of declarations with array type by the
946 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000947 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000948 const ArrayType *arrayType;
949 if (MinWidth && (arrayType = getAsArrayType(T))) {
950 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000951 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000952 else if (isa<ConstantArrayType>(arrayType) &&
953 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000954 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000955
John McCall33ddac02011-01-19 10:06:00 +0000956 // Walk through any array types while we're at it.
957 T = getBaseElementType(arrayType);
958 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000959 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000960 }
John McCall4e819612011-01-20 07:57:12 +0000961
962 // Fields can be subject to extra alignment constraints, like if
963 // the field is packed, the struct is packed, or the struct has a
964 // a max-field-alignment constraint (#pragma pack). So calculate
965 // the actual alignment of the field within the struct, and then
966 // (as we're expected to) constrain that by the alignment of the type.
967 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
968 // So calculate the alignment of the field.
969 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
970
971 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000972 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000973
974 // Use the GCD of that and the offset within the record.
975 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
976 if (offset > 0) {
977 // Alignment is always a power of 2, so the GCD will be a power of 2,
978 // which means we get to do this crazy thing instead of Euclid's.
979 uint64_t lowBitOfOffset = offset & (~offset + 1);
980 if (lowBitOfOffset < fieldAlign)
981 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
982 }
983
984 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000985 }
Chris Lattner68061312009-01-24 21:53:27 +0000986 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000987
Ken Dyckcc56c542011-01-15 18:38:59 +0000988 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000989}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000990
John McCall87fe5d52010-05-20 01:18:31 +0000991std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000992ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000993 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000994 return std::make_pair(toCharUnitsFromBits(Info.first),
995 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000996}
997
998std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000999ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001000 return getTypeInfoInChars(T.getTypePtr());
1001}
1002
Daniel Dunbarc6475872012-03-09 04:12:54 +00001003std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1004 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1005 if (it != MemoizedTypeInfo.end())
1006 return it->second;
1007
1008 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1009 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1010 return Info;
1011}
1012
1013/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1014/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001015///
1016/// FIXME: Pointers into different addr spaces could have different sizes and
1017/// alignment requirements: getPointerInfo should take an AddrSpace, this
1018/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001019std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001020ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001021 uint64_t Width=0;
1022 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001023 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001024#define TYPE(Class, Base)
1025#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001026#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001027#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1028#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001029 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001030
Chris Lattner355332d2007-07-13 22:27:08 +00001031 case Type::FunctionNoProto:
1032 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001033 // GCC extension: alignof(function) = 32 bits
1034 Width = 0;
1035 Align = 32;
1036 break;
1037
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001038 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001039 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001040 Width = 0;
1041 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1042 break;
1043
Steve Naroff5c131802007-08-30 01:06:46 +00001044 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001045 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001046
Chris Lattner37e05872008-03-05 18:54:05 +00001047 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001048 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001049 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1050 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001051 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001052 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001053 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001054 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001055 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001056 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001057 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001058 const VectorType *VT = cast<VectorType>(T);
1059 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1060 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001061 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001062 // If the alignment is not a power of 2, round up to the next power of 2.
1063 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001064 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001065 Align = llvm::NextPowerOf2(Align);
1066 Width = llvm::RoundUpToAlignment(Width, Align);
1067 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001068 // Adjust the alignment based on the target max.
1069 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1070 if (TargetVectorAlign && TargetVectorAlign < Align)
1071 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001072 break;
1073 }
Chris Lattner647fb222007-07-18 18:26:58 +00001074
Chris Lattner7570e9c2008-03-08 08:52:55 +00001075 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001076 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001077 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001078 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001079 // GCC extension: alignof(void) = 8 bits.
1080 Width = 0;
1081 Align = 8;
1082 break;
1083
Chris Lattner6a4f7452007-12-19 19:23:28 +00001084 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001085 Width = Target->getBoolWidth();
1086 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001087 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001088 case BuiltinType::Char_S:
1089 case BuiltinType::Char_U:
1090 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001091 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001092 Width = Target->getCharWidth();
1093 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001094 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001095 case BuiltinType::WChar_S:
1096 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001097 Width = Target->getWCharWidth();
1098 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001099 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001100 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001101 Width = Target->getChar16Width();
1102 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001103 break;
1104 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001105 Width = Target->getChar32Width();
1106 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001107 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001108 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001109 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001110 Width = Target->getShortWidth();
1111 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001112 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001113 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001114 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001115 Width = Target->getIntWidth();
1116 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001117 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001118 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001119 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001120 Width = Target->getLongWidth();
1121 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001122 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001123 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001124 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001125 Width = Target->getLongLongWidth();
1126 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001127 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001128 case BuiltinType::Int128:
1129 case BuiltinType::UInt128:
1130 Width = 128;
1131 Align = 128; // int128_t is 128-bit aligned on all targets.
1132 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001133 case BuiltinType::Half:
1134 Width = Target->getHalfWidth();
1135 Align = Target->getHalfAlign();
1136 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001137 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001138 Width = Target->getFloatWidth();
1139 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001140 break;
1141 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001142 Width = Target->getDoubleWidth();
1143 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001144 break;
1145 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001146 Width = Target->getLongDoubleWidth();
1147 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001148 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001149 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001150 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1151 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001152 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001153 case BuiltinType::ObjCId:
1154 case BuiltinType::ObjCClass:
1155 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001156 Width = Target->getPointerWidth(0);
1157 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001158 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001159 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001160 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001161 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001162 Width = Target->getPointerWidth(0);
1163 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001164 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001165 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001166 unsigned AS = getTargetAddressSpace(
1167 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001168 Width = Target->getPointerWidth(AS);
1169 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001170 break;
1171 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001172 case Type::LValueReference:
1173 case Type::RValueReference: {
1174 // alignof and sizeof should never enter this code path here, so we go
1175 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001176 unsigned AS = getTargetAddressSpace(
1177 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001178 Width = Target->getPointerWidth(AS);
1179 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001180 break;
1181 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001182 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001183 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001184 Width = Target->getPointerWidth(AS);
1185 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001186 break;
1187 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001188 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001189 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001190 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001191 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001192 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001193 Align = PtrDiffInfo.second;
1194 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001195 }
Chris Lattner647fb222007-07-18 18:26:58 +00001196 case Type::Complex: {
1197 // Complex types have the same alignment as their elements, but twice the
1198 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001199 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001200 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001201 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001202 Align = EltInfo.second;
1203 break;
1204 }
John McCall8b07ec22010-05-15 11:32:37 +00001205 case Type::ObjCObject:
1206 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001207 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001208 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001209 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001210 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001211 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001212 break;
1213 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001214 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001215 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001216 const TagType *TT = cast<TagType>(T);
1217
1218 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001219 Width = 8;
1220 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001221 break;
1222 }
Mike Stump11289f42009-09-09 15:08:12 +00001223
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001224 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001225 return getTypeInfo(ET->getDecl()->getIntegerType());
1226
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001227 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001228 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001229 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001230 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001231 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001232 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001233
Chris Lattner63d2b362009-10-22 05:17:15 +00001234 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001235 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1236 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001237
Richard Smith30482bc2011-02-20 03:19:35 +00001238 case Type::Auto: {
1239 const AutoType *A = cast<AutoType>(T);
1240 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001241 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001242 }
1243
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001244 case Type::Paren:
1245 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1246
Douglas Gregoref462e62009-04-30 17:32:17 +00001247 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001248 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001249 std::pair<uint64_t, unsigned> Info
1250 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001251 // If the typedef has an aligned attribute on it, it overrides any computed
1252 // alignment we have. This violates the GCC documentation (which says that
1253 // attribute(aligned) can only round up) but matches its implementation.
1254 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1255 Align = AttrAlign;
1256 else
1257 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001258 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001259 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001260 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001261
1262 case Type::TypeOfExpr:
1263 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1264 .getTypePtr());
1265
1266 case Type::TypeOf:
1267 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1268
Anders Carlsson81df7b82009-06-24 19:06:50 +00001269 case Type::Decltype:
1270 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1271 .getTypePtr());
1272
Alexis Hunte852b102011-05-24 22:41:36 +00001273 case Type::UnaryTransform:
1274 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1275
Abramo Bagnara6150c882010-05-11 21:36:43 +00001276 case Type::Elaborated:
1277 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001278
John McCall81904512011-01-06 01:58:22 +00001279 case Type::Attributed:
1280 return getTypeInfo(
1281 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1282
Richard Smith3f1b5d02011-05-05 21:57:07 +00001283 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001284 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001285 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001286 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1287 // A type alias template specialization may refer to a typedef with the
1288 // aligned attribute on it.
1289 if (TST->isTypeAlias())
1290 return getTypeInfo(TST->getAliasedType().getTypePtr());
1291 else
1292 return getTypeInfo(getCanonicalType(T));
1293 }
1294
Eli Friedman0dfb8892011-10-06 23:00:33 +00001295 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001296 std::pair<uint64_t, unsigned> Info
1297 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1298 Width = Info.first;
1299 Align = Info.second;
1300 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1301 llvm::isPowerOf2_64(Width)) {
1302 // We can potentially perform lock-free atomic operations for this
1303 // type; promote the alignment appropriately.
1304 // FIXME: We could potentially promote the width here as well...
1305 // is that worthwhile? (Non-struct atomic types generally have
1306 // power-of-two size anyway, but structs might not. Requires a bit
1307 // of implementation work to make sure we zero out the extra bits.)
1308 Align = static_cast<unsigned>(Width);
1309 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001310 }
1311
Douglas Gregoref462e62009-04-30 17:32:17 +00001312 }
Mike Stump11289f42009-09-09 15:08:12 +00001313
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001314 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001315 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001316}
1317
Ken Dyckcc56c542011-01-15 18:38:59 +00001318/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1319CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1320 return CharUnits::fromQuantity(BitSize / getCharWidth());
1321}
1322
Ken Dyckb0fcc592011-02-11 01:54:29 +00001323/// toBits - Convert a size in characters to a size in characters.
1324int64_t ASTContext::toBits(CharUnits CharSize) const {
1325 return CharSize.getQuantity() * getCharWidth();
1326}
1327
Ken Dyck8c89d592009-12-22 14:23:30 +00001328/// getTypeSizeInChars - Return the size of the specified type, in characters.
1329/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001330CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001331 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001332}
Jay Foad39c79802011-01-12 09:06:06 +00001333CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001334 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001335}
1336
Ken Dycka6046ab2010-01-26 17:25:18 +00001337/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001338/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001339CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001340 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001341}
Jay Foad39c79802011-01-12 09:06:06 +00001342CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001343 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001344}
1345
Chris Lattnera3402cd2009-01-27 18:08:34 +00001346/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1347/// type for the current target in bits. This can be different than the ABI
1348/// alignment in cases where it is beneficial for performance to overalign
1349/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001350unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001351 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001352
1353 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001354 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001355 T = CT->getElementType().getTypePtr();
1356 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001357 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1358 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001359 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1360
Chris Lattnera3402cd2009-01-27 18:08:34 +00001361 return ABIAlign;
1362}
1363
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001364/// DeepCollectObjCIvars -
1365/// This routine first collects all declared, but not synthesized, ivars in
1366/// super class and then collects all ivars, including those synthesized for
1367/// current class. This routine is used for implementation of current class
1368/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001369///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001370void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1371 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001372 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001373 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1374 DeepCollectObjCIvars(SuperClass, false, Ivars);
1375 if (!leafClass) {
1376 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1377 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001378 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001379 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001380 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001381 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001382 Iv= Iv->getNextIvar())
1383 Ivars.push_back(Iv);
1384 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001385}
1386
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001387/// CollectInheritedProtocols - Collect all protocols in current class and
1388/// those inherited by it.
1389void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001390 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001391 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001392 // We can use protocol_iterator here instead of
1393 // all_referenced_protocol_iterator since we are walking all categories.
1394 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1395 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001396 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001397 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001398 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001399 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001400 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001401 CollectInheritedProtocols(*P, Protocols);
1402 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001403 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001404
1405 // Categories of this Interface.
1406 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1407 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1408 CollectInheritedProtocols(CDeclChain, Protocols);
1409 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1410 while (SD) {
1411 CollectInheritedProtocols(SD, Protocols);
1412 SD = SD->getSuperClass();
1413 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001414 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001415 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001416 PE = OC->protocol_end(); P != PE; ++P) {
1417 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001418 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001419 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1420 PE = Proto->protocol_end(); P != PE; ++P)
1421 CollectInheritedProtocols(*P, Protocols);
1422 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001423 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001424 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1425 PE = OP->protocol_end(); P != PE; ++P) {
1426 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001427 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001428 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1429 PE = Proto->protocol_end(); P != PE; ++P)
1430 CollectInheritedProtocols(*P, Protocols);
1431 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001432 }
1433}
1434
Jay Foad39c79802011-01-12 09:06:06 +00001435unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001436 unsigned count = 0;
1437 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001438 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1439 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001440 count += CDecl->ivar_size();
1441
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001442 // Count ivar defined in this class's implementation. This
1443 // includes synthesized ivars.
1444 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001445 count += ImplDecl->ivar_size();
1446
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001447 return count;
1448}
1449
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001450bool ASTContext::isSentinelNullExpr(const Expr *E) {
1451 if (!E)
1452 return false;
1453
1454 // nullptr_t is always treated as null.
1455 if (E->getType()->isNullPtrType()) return true;
1456
1457 if (E->getType()->isAnyPointerType() &&
1458 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1459 Expr::NPC_ValueDependentIsNull))
1460 return true;
1461
1462 // Unfortunately, __null has type 'int'.
1463 if (isa<GNUNullExpr>(E)) return true;
1464
1465 return false;
1466}
1467
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001468/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1469ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1470 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1471 I = ObjCImpls.find(D);
1472 if (I != ObjCImpls.end())
1473 return cast<ObjCImplementationDecl>(I->second);
1474 return 0;
1475}
1476/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1477ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1478 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1479 I = ObjCImpls.find(D);
1480 if (I != ObjCImpls.end())
1481 return cast<ObjCCategoryImplDecl>(I->second);
1482 return 0;
1483}
1484
1485/// \brief Set the implementation of ObjCInterfaceDecl.
1486void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1487 ObjCImplementationDecl *ImplD) {
1488 assert(IFaceD && ImplD && "Passed null params");
1489 ObjCImpls[IFaceD] = ImplD;
1490}
1491/// \brief Set the implementation of ObjCCategoryDecl.
1492void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1493 ObjCCategoryImplDecl *ImplD) {
1494 assert(CatD && ImplD && "Passed null params");
1495 ObjCImpls[CatD] = ImplD;
1496}
1497
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001498ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1499 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1500 return ID;
1501 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1502 return CD->getClassInterface();
1503 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1504 return IMD->getClassInterface();
1505
1506 return 0;
1507}
1508
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001509/// \brief Get the copy initialization expression of VarDecl,or NULL if
1510/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001511Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001512 assert(VD && "Passed null params");
1513 assert(VD->hasAttr<BlocksAttr>() &&
1514 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001515 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001516 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001517 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1518}
1519
1520/// \brief Set the copy inialization expression of a block var decl.
1521void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1522 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001523 assert(VD->hasAttr<BlocksAttr>() &&
1524 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001525 BlockVarCopyInits[VD] = Init;
1526}
1527
John McCallbcd03502009-12-07 02:54:59 +00001528TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001529 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001530 if (!DataSize)
1531 DataSize = TypeLoc::getFullDataSizeForType(T);
1532 else
1533 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001534 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001535
John McCallbcd03502009-12-07 02:54:59 +00001536 TypeSourceInfo *TInfo =
1537 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1538 new (TInfo) TypeSourceInfo(T);
1539 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001540}
1541
John McCallbcd03502009-12-07 02:54:59 +00001542TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001543 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001544 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001545 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001546 return DI;
1547}
1548
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001549const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001550ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001551 return getObjCLayout(D, 0);
1552}
1553
1554const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001555ASTContext::getASTObjCImplementationLayout(
1556 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001557 return getObjCLayout(D->getClassInterface(), D);
1558}
1559
Chris Lattner983a8bb2007-07-13 22:13:22 +00001560//===----------------------------------------------------------------------===//
1561// Type creation/memoization methods
1562//===----------------------------------------------------------------------===//
1563
Jay Foad39c79802011-01-12 09:06:06 +00001564QualType
John McCall33ddac02011-01-19 10:06:00 +00001565ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1566 unsigned fastQuals = quals.getFastQualifiers();
1567 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001568
1569 // Check if we've already instantiated this type.
1570 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001571 ExtQuals::Profile(ID, baseType, quals);
1572 void *insertPos = 0;
1573 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1574 assert(eq->getQualifiers() == quals);
1575 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001576 }
1577
John McCall33ddac02011-01-19 10:06:00 +00001578 // If the base type is not canonical, make the appropriate canonical type.
1579 QualType canon;
1580 if (!baseType->isCanonicalUnqualified()) {
1581 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001582 canonSplit.Quals.addConsistentQualifiers(quals);
1583 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001584
1585 // Re-find the insert position.
1586 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1587 }
1588
1589 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1590 ExtQualNodes.InsertNode(eq, insertPos);
1591 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001592}
1593
Jay Foad39c79802011-01-12 09:06:06 +00001594QualType
1595ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001596 QualType CanT = getCanonicalType(T);
1597 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001598 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001599
John McCall8ccfcb52009-09-24 19:53:00 +00001600 // If we are composing extended qualifiers together, merge together
1601 // into one ExtQuals node.
1602 QualifierCollector Quals;
1603 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001604
John McCall8ccfcb52009-09-24 19:53:00 +00001605 // If this type already has an address space specified, it cannot get
1606 // another one.
1607 assert(!Quals.hasAddressSpace() &&
1608 "Type cannot be in multiple addr spaces!");
1609 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001610
John McCall8ccfcb52009-09-24 19:53:00 +00001611 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001612}
1613
Chris Lattnerd60183d2009-02-18 22:53:11 +00001614QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001615 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001616 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001617 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001618 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001619
John McCall53fa7142010-12-24 02:08:15 +00001620 if (const PointerType *ptr = T->getAs<PointerType>()) {
1621 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001622 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001623 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1624 return getPointerType(ResultType);
1625 }
1626 }
Mike Stump11289f42009-09-09 15:08:12 +00001627
John McCall8ccfcb52009-09-24 19:53:00 +00001628 // If we are composing extended qualifiers together, merge together
1629 // into one ExtQuals node.
1630 QualifierCollector Quals;
1631 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001632
John McCall8ccfcb52009-09-24 19:53:00 +00001633 // If this type already has an ObjCGC specified, it cannot get
1634 // another one.
1635 assert(!Quals.hasObjCGCAttr() &&
1636 "Type cannot have multiple ObjCGCs!");
1637 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001638
John McCall8ccfcb52009-09-24 19:53:00 +00001639 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001640}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001641
John McCall4f5019e2010-12-19 02:44:49 +00001642const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1643 FunctionType::ExtInfo Info) {
1644 if (T->getExtInfo() == Info)
1645 return T;
1646
1647 QualType Result;
1648 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1649 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1650 } else {
1651 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1652 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1653 EPI.ExtInfo = Info;
1654 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1655 FPT->getNumArgs(), EPI);
1656 }
1657
1658 return cast<FunctionType>(Result.getTypePtr());
1659}
1660
Chris Lattnerc6395932007-06-22 20:56:16 +00001661/// getComplexType - Return the uniqued reference to the type for a complex
1662/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001663QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001664 // Unique pointers, to guarantee there is only one pointer of a particular
1665 // structure.
1666 llvm::FoldingSetNodeID ID;
1667 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001668
Chris Lattnerc6395932007-06-22 20:56:16 +00001669 void *InsertPos = 0;
1670 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1671 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001672
Chris Lattnerc6395932007-06-22 20:56:16 +00001673 // If the pointee type isn't canonical, this won't be a canonical type either,
1674 // so fill in the canonical type field.
1675 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001676 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001677 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001678
Chris Lattnerc6395932007-06-22 20:56:16 +00001679 // Get the new insert position for the node we care about.
1680 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001681 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001682 }
John McCall90d1c2d2009-09-24 23:30:46 +00001683 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001684 Types.push_back(New);
1685 ComplexTypes.InsertNode(New, InsertPos);
1686 return QualType(New, 0);
1687}
1688
Chris Lattner970e54e2006-11-12 00:37:36 +00001689/// getPointerType - Return the uniqued reference to the type for a pointer to
1690/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001691QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001692 // Unique pointers, to guarantee there is only one pointer of a particular
1693 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001694 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001695 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001696
Chris Lattner67521df2007-01-27 01:29:36 +00001697 void *InsertPos = 0;
1698 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001699 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001700
Chris Lattner7ccecb92006-11-12 08:50:50 +00001701 // If the pointee type isn't canonical, this won't be a canonical type either,
1702 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001703 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001704 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001705 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001706
Chris Lattner67521df2007-01-27 01:29:36 +00001707 // Get the new insert position for the node we care about.
1708 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001709 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001710 }
John McCall90d1c2d2009-09-24 23:30:46 +00001711 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001712 Types.push_back(New);
1713 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001714 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001715}
1716
Mike Stump11289f42009-09-09 15:08:12 +00001717/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001718/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001719QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001720 assert(T->isFunctionType() && "block of function types only");
1721 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001722 // structure.
1723 llvm::FoldingSetNodeID ID;
1724 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001725
Steve Naroffec33ed92008-08-27 16:04:49 +00001726 void *InsertPos = 0;
1727 if (BlockPointerType *PT =
1728 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1729 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001730
1731 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001732 // type either so fill in the canonical type field.
1733 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001734 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001735 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001736
Steve Naroffec33ed92008-08-27 16:04:49 +00001737 // Get the new insert position for the node we care about.
1738 BlockPointerType *NewIP =
1739 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001740 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001741 }
John McCall90d1c2d2009-09-24 23:30:46 +00001742 BlockPointerType *New
1743 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001744 Types.push_back(New);
1745 BlockPointerTypes.InsertNode(New, InsertPos);
1746 return QualType(New, 0);
1747}
1748
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001749/// getLValueReferenceType - Return the uniqued reference to the type for an
1750/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001751QualType
1752ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001753 assert(getCanonicalType(T) != OverloadTy &&
1754 "Unresolved overloaded function type");
1755
Bill Wendling3708c182007-05-27 10:15:43 +00001756 // Unique pointers, to guarantee there is only one pointer of a particular
1757 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001758 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001759 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001760
1761 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001762 if (LValueReferenceType *RT =
1763 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001764 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001765
John McCallfc93cf92009-10-22 22:37:11 +00001766 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1767
Bill Wendling3708c182007-05-27 10:15:43 +00001768 // If the referencee type isn't canonical, this won't be a canonical type
1769 // either, so fill in the canonical type field.
1770 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001771 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1772 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1773 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001774
Bill Wendling3708c182007-05-27 10:15:43 +00001775 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001776 LValueReferenceType *NewIP =
1777 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001778 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001779 }
1780
John McCall90d1c2d2009-09-24 23:30:46 +00001781 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001782 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1783 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001784 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001785 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001786
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001787 return QualType(New, 0);
1788}
1789
1790/// getRValueReferenceType - Return the uniqued reference to the type for an
1791/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001792QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001793 // Unique pointers, to guarantee there is only one pointer of a particular
1794 // structure.
1795 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001796 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001797
1798 void *InsertPos = 0;
1799 if (RValueReferenceType *RT =
1800 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1801 return QualType(RT, 0);
1802
John McCallfc93cf92009-10-22 22:37:11 +00001803 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1804
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001805 // If the referencee type isn't canonical, this won't be a canonical type
1806 // either, so fill in the canonical type field.
1807 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001808 if (InnerRef || !T.isCanonical()) {
1809 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1810 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001811
1812 // Get the new insert position for the node we care about.
1813 RValueReferenceType *NewIP =
1814 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001815 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001816 }
1817
John McCall90d1c2d2009-09-24 23:30:46 +00001818 RValueReferenceType *New
1819 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001820 Types.push_back(New);
1821 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001822 return QualType(New, 0);
1823}
1824
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001825/// getMemberPointerType - Return the uniqued reference to the type for a
1826/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001827QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001828 // Unique pointers, to guarantee there is only one pointer of a particular
1829 // structure.
1830 llvm::FoldingSetNodeID ID;
1831 MemberPointerType::Profile(ID, T, Cls);
1832
1833 void *InsertPos = 0;
1834 if (MemberPointerType *PT =
1835 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1836 return QualType(PT, 0);
1837
1838 // If the pointee or class type isn't canonical, this won't be a canonical
1839 // type either, so fill in the canonical type field.
1840 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001841 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001842 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1843
1844 // Get the new insert position for the node we care about.
1845 MemberPointerType *NewIP =
1846 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001847 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001848 }
John McCall90d1c2d2009-09-24 23:30:46 +00001849 MemberPointerType *New
1850 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001851 Types.push_back(New);
1852 MemberPointerTypes.InsertNode(New, InsertPos);
1853 return QualType(New, 0);
1854}
1855
Mike Stump11289f42009-09-09 15:08:12 +00001856/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001857/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001858QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001859 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001860 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001861 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001862 assert((EltTy->isDependentType() ||
1863 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001864 "Constant array of VLAs is illegal!");
1865
Chris Lattnere2df3f92009-05-13 04:12:56 +00001866 // Convert the array size into a canonical width matching the pointer size for
1867 // the target.
1868 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001869 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001870 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001871
Chris Lattner23b7eb62007-06-15 23:05:46 +00001872 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001873 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001874
Chris Lattner36f8e652007-01-27 08:31:04 +00001875 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001876 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001877 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001878 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001879
John McCall33ddac02011-01-19 10:06:00 +00001880 // If the element type isn't canonical or has qualifiers, this won't
1881 // be a canonical type either, so fill in the canonical type field.
1882 QualType Canon;
1883 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1884 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001885 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001886 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001887 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001888
Chris Lattner36f8e652007-01-27 08:31:04 +00001889 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001890 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001891 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001892 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001893 }
Mike Stump11289f42009-09-09 15:08:12 +00001894
John McCall90d1c2d2009-09-24 23:30:46 +00001895 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001896 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001897 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001898 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001899 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001900}
1901
John McCall06549462011-01-18 08:40:38 +00001902/// getVariableArrayDecayedType - Turns the given type, which may be
1903/// variably-modified, into the corresponding type with all the known
1904/// sizes replaced with [*].
1905QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1906 // Vastly most common case.
1907 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001908
John McCall06549462011-01-18 08:40:38 +00001909 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001910
John McCall06549462011-01-18 08:40:38 +00001911 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001912 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001913 switch (ty->getTypeClass()) {
1914#define TYPE(Class, Base)
1915#define ABSTRACT_TYPE(Class, Base)
1916#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1917#include "clang/AST/TypeNodes.def"
1918 llvm_unreachable("didn't desugar past all non-canonical types?");
1919
1920 // These types should never be variably-modified.
1921 case Type::Builtin:
1922 case Type::Complex:
1923 case Type::Vector:
1924 case Type::ExtVector:
1925 case Type::DependentSizedExtVector:
1926 case Type::ObjCObject:
1927 case Type::ObjCInterface:
1928 case Type::ObjCObjectPointer:
1929 case Type::Record:
1930 case Type::Enum:
1931 case Type::UnresolvedUsing:
1932 case Type::TypeOfExpr:
1933 case Type::TypeOf:
1934 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001935 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001936 case Type::DependentName:
1937 case Type::InjectedClassName:
1938 case Type::TemplateSpecialization:
1939 case Type::DependentTemplateSpecialization:
1940 case Type::TemplateTypeParm:
1941 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001942 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001943 case Type::PackExpansion:
1944 llvm_unreachable("type should never be variably-modified");
1945
1946 // These types can be variably-modified but should never need to
1947 // further decay.
1948 case Type::FunctionNoProto:
1949 case Type::FunctionProto:
1950 case Type::BlockPointer:
1951 case Type::MemberPointer:
1952 return type;
1953
1954 // These types can be variably-modified. All these modifications
1955 // preserve structure except as noted by comments.
1956 // TODO: if we ever care about optimizing VLAs, there are no-op
1957 // optimizations available here.
1958 case Type::Pointer:
1959 result = getPointerType(getVariableArrayDecayedType(
1960 cast<PointerType>(ty)->getPointeeType()));
1961 break;
1962
1963 case Type::LValueReference: {
1964 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1965 result = getLValueReferenceType(
1966 getVariableArrayDecayedType(lv->getPointeeType()),
1967 lv->isSpelledAsLValue());
1968 break;
1969 }
1970
1971 case Type::RValueReference: {
1972 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1973 result = getRValueReferenceType(
1974 getVariableArrayDecayedType(lv->getPointeeType()));
1975 break;
1976 }
1977
Eli Friedman0dfb8892011-10-06 23:00:33 +00001978 case Type::Atomic: {
1979 const AtomicType *at = cast<AtomicType>(ty);
1980 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1981 break;
1982 }
1983
John McCall06549462011-01-18 08:40:38 +00001984 case Type::ConstantArray: {
1985 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1986 result = getConstantArrayType(
1987 getVariableArrayDecayedType(cat->getElementType()),
1988 cat->getSize(),
1989 cat->getSizeModifier(),
1990 cat->getIndexTypeCVRQualifiers());
1991 break;
1992 }
1993
1994 case Type::DependentSizedArray: {
1995 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1996 result = getDependentSizedArrayType(
1997 getVariableArrayDecayedType(dat->getElementType()),
1998 dat->getSizeExpr(),
1999 dat->getSizeModifier(),
2000 dat->getIndexTypeCVRQualifiers(),
2001 dat->getBracketsRange());
2002 break;
2003 }
2004
2005 // Turn incomplete types into [*] types.
2006 case Type::IncompleteArray: {
2007 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2008 result = getVariableArrayType(
2009 getVariableArrayDecayedType(iat->getElementType()),
2010 /*size*/ 0,
2011 ArrayType::Normal,
2012 iat->getIndexTypeCVRQualifiers(),
2013 SourceRange());
2014 break;
2015 }
2016
2017 // Turn VLA types into [*] types.
2018 case Type::VariableArray: {
2019 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2020 result = getVariableArrayType(
2021 getVariableArrayDecayedType(vat->getElementType()),
2022 /*size*/ 0,
2023 ArrayType::Star,
2024 vat->getIndexTypeCVRQualifiers(),
2025 vat->getBracketsRange());
2026 break;
2027 }
2028 }
2029
2030 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002031 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002032}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002033
Steve Naroffcadebd02007-08-30 18:14:25 +00002034/// getVariableArrayType - Returns a non-unique reference to the type for a
2035/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002036QualType ASTContext::getVariableArrayType(QualType EltTy,
2037 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002038 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002039 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002040 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002041 // Since we don't unique expressions, it isn't possible to unique VLA's
2042 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002043 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002044
John McCall33ddac02011-01-19 10:06:00 +00002045 // Be sure to pull qualifiers off the element type.
2046 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2047 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002048 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002049 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002050 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002051 }
2052
John McCall90d1c2d2009-09-24 23:30:46 +00002053 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002054 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002055
2056 VariableArrayTypes.push_back(New);
2057 Types.push_back(New);
2058 return QualType(New, 0);
2059}
2060
Douglas Gregor4619e432008-12-05 23:32:09 +00002061/// getDependentSizedArrayType - Returns a non-unique reference to
2062/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002063/// type.
John McCall33ddac02011-01-19 10:06:00 +00002064QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2065 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002066 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002067 unsigned elementTypeQuals,
2068 SourceRange brackets) const {
2069 assert((!numElements || numElements->isTypeDependent() ||
2070 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002071 "Size must be type- or value-dependent!");
2072
John McCall33ddac02011-01-19 10:06:00 +00002073 // Dependently-sized array types that do not have a specified number
2074 // of elements will have their sizes deduced from a dependent
2075 // initializer. We do no canonicalization here at all, which is okay
2076 // because they can't be used in most locations.
2077 if (!numElements) {
2078 DependentSizedArrayType *newType
2079 = new (*this, TypeAlignment)
2080 DependentSizedArrayType(*this, elementType, QualType(),
2081 numElements, ASM, elementTypeQuals,
2082 brackets);
2083 Types.push_back(newType);
2084 return QualType(newType, 0);
2085 }
2086
2087 // Otherwise, we actually build a new type every time, but we
2088 // also build a canonical type.
2089
2090 SplitQualType canonElementType = getCanonicalType(elementType).split();
2091
2092 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002093 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002094 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002095 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002096 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002097
John McCall33ddac02011-01-19 10:06:00 +00002098 // Look for an existing type with these properties.
2099 DependentSizedArrayType *canonTy =
2100 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002101
John McCall33ddac02011-01-19 10:06:00 +00002102 // If we don't have one, build one.
2103 if (!canonTy) {
2104 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002105 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002106 QualType(), numElements, ASM, elementTypeQuals,
2107 brackets);
2108 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2109 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002110 }
2111
John McCall33ddac02011-01-19 10:06:00 +00002112 // Apply qualifiers from the element type to the array.
2113 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002114 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002115
John McCall33ddac02011-01-19 10:06:00 +00002116 // If we didn't need extra canonicalization for the element type,
2117 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002118 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002119 return canon;
2120
2121 // Otherwise, we need to build a type which follows the spelling
2122 // of the element type.
2123 DependentSizedArrayType *sugaredType
2124 = new (*this, TypeAlignment)
2125 DependentSizedArrayType(*this, elementType, canon, numElements,
2126 ASM, elementTypeQuals, brackets);
2127 Types.push_back(sugaredType);
2128 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002129}
2130
John McCall33ddac02011-01-19 10:06:00 +00002131QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002132 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002133 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002134 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002135 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002136
John McCall33ddac02011-01-19 10:06:00 +00002137 void *insertPos = 0;
2138 if (IncompleteArrayType *iat =
2139 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2140 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002141
2142 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002143 // either, so fill in the canonical type field. We also have to pull
2144 // qualifiers off the element type.
2145 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002146
John McCall33ddac02011-01-19 10:06:00 +00002147 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2148 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002149 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002150 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002151 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002152
2153 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002154 IncompleteArrayType *existing =
2155 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2156 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002157 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002158
John McCall33ddac02011-01-19 10:06:00 +00002159 IncompleteArrayType *newType = new (*this, TypeAlignment)
2160 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002161
John McCall33ddac02011-01-19 10:06:00 +00002162 IncompleteArrayTypes.InsertNode(newType, insertPos);
2163 Types.push_back(newType);
2164 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002165}
2166
Steve Naroff91fcddb2007-07-18 18:00:27 +00002167/// getVectorType - Return the unique reference to a vector type of
2168/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002169QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002170 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002171 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002172
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002173 // Check if we've already instantiated a vector of this type.
2174 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002175 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002176
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002177 void *InsertPos = 0;
2178 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2179 return QualType(VTP, 0);
2180
2181 // If the element type isn't canonical, this won't be a canonical type either,
2182 // so fill in the canonical type field.
2183 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002184 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002185 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002186
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002187 // Get the new insert position for the node we care about.
2188 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002189 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002190 }
John McCall90d1c2d2009-09-24 23:30:46 +00002191 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002192 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002193 VectorTypes.InsertNode(New, InsertPos);
2194 Types.push_back(New);
2195 return QualType(New, 0);
2196}
2197
Nate Begemance4d7fc2008-04-18 23:10:10 +00002198/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002199/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002200QualType
2201ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002202 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002203
Steve Naroff91fcddb2007-07-18 18:00:27 +00002204 // Check if we've already instantiated a vector of this type.
2205 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002206 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002207 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002208 void *InsertPos = 0;
2209 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2210 return QualType(VTP, 0);
2211
2212 // If the element type isn't canonical, this won't be a canonical type either,
2213 // so fill in the canonical type field.
2214 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002215 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002216 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002217
Steve Naroff91fcddb2007-07-18 18:00:27 +00002218 // Get the new insert position for the node we care about.
2219 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002220 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002221 }
John McCall90d1c2d2009-09-24 23:30:46 +00002222 ExtVectorType *New = new (*this, TypeAlignment)
2223 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002224 VectorTypes.InsertNode(New, InsertPos);
2225 Types.push_back(New);
2226 return QualType(New, 0);
2227}
2228
Jay Foad39c79802011-01-12 09:06:06 +00002229QualType
2230ASTContext::getDependentSizedExtVectorType(QualType vecType,
2231 Expr *SizeExpr,
2232 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002233 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002234 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002235 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002236
Douglas Gregor352169a2009-07-31 03:54:25 +00002237 void *InsertPos = 0;
2238 DependentSizedExtVectorType *Canon
2239 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2240 DependentSizedExtVectorType *New;
2241 if (Canon) {
2242 // We already have a canonical version of this array type; use it as
2243 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002244 New = new (*this, TypeAlignment)
2245 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2246 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002247 } else {
2248 QualType CanonVecTy = getCanonicalType(vecType);
2249 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002250 New = new (*this, TypeAlignment)
2251 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2252 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002253
2254 DependentSizedExtVectorType *CanonCheck
2255 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2256 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2257 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002258 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2259 } else {
2260 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2261 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002262 New = new (*this, TypeAlignment)
2263 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002264 }
2265 }
Mike Stump11289f42009-09-09 15:08:12 +00002266
Douglas Gregor758a8692009-06-17 21:51:59 +00002267 Types.push_back(New);
2268 return QualType(New, 0);
2269}
2270
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002271/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002272///
Jay Foad39c79802011-01-12 09:06:06 +00002273QualType
2274ASTContext::getFunctionNoProtoType(QualType ResultTy,
2275 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002276 const CallingConv DefaultCC = Info.getCC();
2277 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2278 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002279 // Unique functions, to guarantee there is only one function of a particular
2280 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002281 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002282 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002283
Chris Lattner47955de2007-01-27 08:37:20 +00002284 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002285 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002286 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002287 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002288
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002289 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002290 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002291 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002292 Canonical =
2293 getFunctionNoProtoType(getCanonicalType(ResultTy),
2294 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002295
Chris Lattner47955de2007-01-27 08:37:20 +00002296 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002297 FunctionNoProtoType *NewIP =
2298 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002299 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002300 }
Mike Stump11289f42009-09-09 15:08:12 +00002301
Roman Divacky65b88cd2011-03-01 17:40:53 +00002302 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002303 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002304 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002305 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002306 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002307 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002308}
2309
2310/// getFunctionType - Return a normal function type with a typed argument
2311/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002312QualType
2313ASTContext::getFunctionType(QualType ResultTy,
2314 const QualType *ArgArray, unsigned NumArgs,
2315 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002316 // Unique functions, to guarantee there is only one function of a particular
2317 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002318 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002319 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002320
2321 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002322 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002323 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002324 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002325
2326 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002327 bool isCanonical =
2328 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2329 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002330 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002331 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002332 isCanonical = false;
2333
Roman Divacky65b88cd2011-03-01 17:40:53 +00002334 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2335 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2336 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002337
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002338 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002339 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002340 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002341 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002342 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002343 CanonicalArgs.reserve(NumArgs);
2344 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002345 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002346
John McCalldb40c7f2010-12-14 08:05:40 +00002347 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002348 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002349 CanonicalEPI.ExceptionSpecType = EST_None;
2350 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002351 CanonicalEPI.ExtInfo
2352 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2353
Chris Lattner76a00cf2008-04-06 22:59:24 +00002354 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002355 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002356 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002357
Chris Lattnerfd4de792007-01-27 01:15:32 +00002358 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002359 FunctionProtoType *NewIP =
2360 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002361 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002362 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002363
John McCall31168b02011-06-15 23:02:42 +00002364 // FunctionProtoType objects are allocated with extra bytes after
2365 // them for three variable size arrays at the end:
2366 // - parameter types
2367 // - exception types
2368 // - consumed-arguments flags
2369 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002370 // expression, or information used to resolve the exception
2371 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002372 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002373 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002374 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002375 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002376 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002377 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002378 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002379 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002380 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2381 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002382 }
John McCall31168b02011-06-15 23:02:42 +00002383 if (EPI.ConsumedArguments)
2384 Size += NumArgs * sizeof(bool);
2385
John McCalldb40c7f2010-12-14 08:05:40 +00002386 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002387 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2388 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002389 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002390 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002391 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002392 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002393}
Chris Lattneref51c202006-11-10 07:17:23 +00002394
John McCalle78aac42010-03-10 03:28:59 +00002395#ifndef NDEBUG
2396static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2397 if (!isa<CXXRecordDecl>(D)) return false;
2398 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2399 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2400 return true;
2401 if (RD->getDescribedClassTemplate() &&
2402 !isa<ClassTemplateSpecializationDecl>(RD))
2403 return true;
2404 return false;
2405}
2406#endif
2407
2408/// getInjectedClassNameType - Return the unique reference to the
2409/// injected class name type for the specified templated declaration.
2410QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002411 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002412 assert(NeedsInjectedClassNameType(Decl));
2413 if (Decl->TypeForDecl) {
2414 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002415 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002416 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2417 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2418 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2419 } else {
John McCall424cec92011-01-19 06:33:43 +00002420 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002421 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002422 Decl->TypeForDecl = newType;
2423 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002424 }
2425 return QualType(Decl->TypeForDecl, 0);
2426}
2427
Douglas Gregor83a586e2008-04-13 21:07:44 +00002428/// getTypeDeclType - Return the unique reference to the type for the
2429/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002430QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002431 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002432 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002433
Richard Smithdda56e42011-04-15 14:24:37 +00002434 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002435 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002436
John McCall96f0b5f2010-03-10 06:48:02 +00002437 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2438 "Template type parameter types are always available.");
2439
John McCall81e38502010-02-16 03:57:14 +00002440 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002441 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002442 "struct/union has previous declaration");
2443 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002444 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002445 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002446 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002447 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002448 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002449 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002450 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002451 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2452 Decl->TypeForDecl = newType;
2453 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002454 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002455 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002456
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002457 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002458}
2459
Chris Lattner32d920b2007-01-26 02:01:53 +00002460/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002461/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002462QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002463ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2464 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002465 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002466
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002467 if (Canonical.isNull())
2468 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002469 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002470 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002471 Decl->TypeForDecl = newType;
2472 Types.push_back(newType);
2473 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002474}
2475
Jay Foad39c79802011-01-12 09:06:06 +00002476QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002477 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2478
Douglas Gregorec9fd132012-01-14 16:38:05 +00002479 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002480 if (PrevDecl->TypeForDecl)
2481 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2482
John McCall424cec92011-01-19 06:33:43 +00002483 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2484 Decl->TypeForDecl = newType;
2485 Types.push_back(newType);
2486 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002487}
2488
Jay Foad39c79802011-01-12 09:06:06 +00002489QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002490 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2491
Douglas Gregorec9fd132012-01-14 16:38:05 +00002492 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002493 if (PrevDecl->TypeForDecl)
2494 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2495
John McCall424cec92011-01-19 06:33:43 +00002496 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2497 Decl->TypeForDecl = newType;
2498 Types.push_back(newType);
2499 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002500}
2501
John McCall81904512011-01-06 01:58:22 +00002502QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2503 QualType modifiedType,
2504 QualType equivalentType) {
2505 llvm::FoldingSetNodeID id;
2506 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2507
2508 void *insertPos = 0;
2509 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2510 if (type) return QualType(type, 0);
2511
2512 QualType canon = getCanonicalType(equivalentType);
2513 type = new (*this, TypeAlignment)
2514 AttributedType(canon, attrKind, modifiedType, equivalentType);
2515
2516 Types.push_back(type);
2517 AttributedTypes.InsertNode(type, insertPos);
2518
2519 return QualType(type, 0);
2520}
2521
2522
John McCallcebee162009-10-18 09:09:24 +00002523/// \brief Retrieve a substitution-result type.
2524QualType
2525ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002526 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002527 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002528 && "replacement types must always be canonical");
2529
2530 llvm::FoldingSetNodeID ID;
2531 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2532 void *InsertPos = 0;
2533 SubstTemplateTypeParmType *SubstParm
2534 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2535
2536 if (!SubstParm) {
2537 SubstParm = new (*this, TypeAlignment)
2538 SubstTemplateTypeParmType(Parm, Replacement);
2539 Types.push_back(SubstParm);
2540 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2541 }
2542
2543 return QualType(SubstParm, 0);
2544}
2545
Douglas Gregorada4b792011-01-14 02:55:32 +00002546/// \brief Retrieve a
2547QualType ASTContext::getSubstTemplateTypeParmPackType(
2548 const TemplateTypeParmType *Parm,
2549 const TemplateArgument &ArgPack) {
2550#ifndef NDEBUG
2551 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2552 PEnd = ArgPack.pack_end();
2553 P != PEnd; ++P) {
2554 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2555 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2556 }
2557#endif
2558
2559 llvm::FoldingSetNodeID ID;
2560 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2561 void *InsertPos = 0;
2562 if (SubstTemplateTypeParmPackType *SubstParm
2563 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2564 return QualType(SubstParm, 0);
2565
2566 QualType Canon;
2567 if (!Parm->isCanonicalUnqualified()) {
2568 Canon = getCanonicalType(QualType(Parm, 0));
2569 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2570 ArgPack);
2571 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2572 }
2573
2574 SubstTemplateTypeParmPackType *SubstParm
2575 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2576 ArgPack);
2577 Types.push_back(SubstParm);
2578 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2579 return QualType(SubstParm, 0);
2580}
2581
Douglas Gregoreff93e02009-02-05 23:33:38 +00002582/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002583/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002584/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002585QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002586 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002587 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002588 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002589 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002590 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002591 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002592 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2593
2594 if (TypeParm)
2595 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002596
Chandler Carruth08836322011-05-01 00:51:33 +00002597 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002598 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002599 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002600
2601 TemplateTypeParmType *TypeCheck
2602 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2603 assert(!TypeCheck && "Template type parameter canonical type broken");
2604 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002605 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002606 TypeParm = new (*this, TypeAlignment)
2607 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002608
2609 Types.push_back(TypeParm);
2610 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2611
2612 return QualType(TypeParm, 0);
2613}
2614
John McCalle78aac42010-03-10 03:28:59 +00002615TypeSourceInfo *
2616ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2617 SourceLocation NameLoc,
2618 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002619 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002620 assert(!Name.getAsDependentTemplateName() &&
2621 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002622 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002623
2624 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2625 TemplateSpecializationTypeLoc TL
2626 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002627 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002628 TL.setTemplateNameLoc(NameLoc);
2629 TL.setLAngleLoc(Args.getLAngleLoc());
2630 TL.setRAngleLoc(Args.getRAngleLoc());
2631 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2632 TL.setArgLocInfo(i, Args[i].getLocInfo());
2633 return DI;
2634}
2635
Mike Stump11289f42009-09-09 15:08:12 +00002636QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002637ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002638 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002639 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002640 assert(!Template.getAsDependentTemplateName() &&
2641 "No dependent template names here!");
2642
John McCall6b51f282009-11-23 01:53:49 +00002643 unsigned NumArgs = Args.size();
2644
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002645 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002646 ArgVec.reserve(NumArgs);
2647 for (unsigned i = 0; i != NumArgs; ++i)
2648 ArgVec.push_back(Args[i].getArgument());
2649
John McCall2408e322010-04-27 00:57:59 +00002650 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002651 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002652}
2653
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002654#ifndef NDEBUG
2655static bool hasAnyPackExpansions(const TemplateArgument *Args,
2656 unsigned NumArgs) {
2657 for (unsigned I = 0; I != NumArgs; ++I)
2658 if (Args[I].isPackExpansion())
2659 return true;
2660
2661 return true;
2662}
2663#endif
2664
John McCall0ad16662009-10-29 08:12:44 +00002665QualType
2666ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002667 const TemplateArgument *Args,
2668 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002669 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002670 assert(!Template.getAsDependentTemplateName() &&
2671 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002672 // Look through qualified template names.
2673 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2674 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002675
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002676 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002677 Template.getAsTemplateDecl() &&
2678 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002679 QualType CanonType;
2680 if (!Underlying.isNull())
2681 CanonType = getCanonicalType(Underlying);
2682 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002683 // We can get here with an alias template when the specialization contains
2684 // a pack expansion that does not match up with a parameter pack.
2685 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2686 "Caller must compute aliased type");
2687 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002688 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2689 NumArgs);
2690 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002691
Douglas Gregora8e02e72009-07-28 23:00:59 +00002692 // Allocate the (non-canonical) template specialization type, but don't
2693 // try to unique it: these types typically have location information that
2694 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002695 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2696 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002697 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002698 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002699 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002700 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2701 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002702
Douglas Gregor8bf42052009-02-09 18:46:07 +00002703 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002704 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002705}
2706
Mike Stump11289f42009-09-09 15:08:12 +00002707QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002708ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2709 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002710 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002711 assert(!Template.getAsDependentTemplateName() &&
2712 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002713
Douglas Gregore29139c2011-03-03 17:04:51 +00002714 // Look through qualified template names.
2715 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2716 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002717
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002718 // Build the canonical template specialization type.
2719 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002720 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002721 CanonArgs.reserve(NumArgs);
2722 for (unsigned I = 0; I != NumArgs; ++I)
2723 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2724
2725 // Determine whether this canonical template specialization type already
2726 // exists.
2727 llvm::FoldingSetNodeID ID;
2728 TemplateSpecializationType::Profile(ID, CanonTemplate,
2729 CanonArgs.data(), NumArgs, *this);
2730
2731 void *InsertPos = 0;
2732 TemplateSpecializationType *Spec
2733 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2734
2735 if (!Spec) {
2736 // Allocate a new canonical template specialization type.
2737 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2738 sizeof(TemplateArgument) * NumArgs),
2739 TypeAlignment);
2740 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2741 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002742 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002743 Types.push_back(Spec);
2744 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2745 }
2746
2747 assert(Spec->isDependentType() &&
2748 "Non-dependent template-id type must have a canonical type");
2749 return QualType(Spec, 0);
2750}
2751
2752QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002753ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2754 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002755 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002756 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002757 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002758
2759 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002760 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002761 if (T)
2762 return QualType(T, 0);
2763
Douglas Gregorc42075a2010-02-04 18:10:26 +00002764 QualType Canon = NamedType;
2765 if (!Canon.isCanonical()) {
2766 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002767 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2768 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002769 (void)CheckT;
2770 }
2771
Abramo Bagnara6150c882010-05-11 21:36:43 +00002772 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002773 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002774 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002775 return QualType(T, 0);
2776}
2777
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002778QualType
Jay Foad39c79802011-01-12 09:06:06 +00002779ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002780 llvm::FoldingSetNodeID ID;
2781 ParenType::Profile(ID, InnerType);
2782
2783 void *InsertPos = 0;
2784 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2785 if (T)
2786 return QualType(T, 0);
2787
2788 QualType Canon = InnerType;
2789 if (!Canon.isCanonical()) {
2790 Canon = getCanonicalType(InnerType);
2791 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2792 assert(!CheckT && "Paren canonical type broken");
2793 (void)CheckT;
2794 }
2795
2796 T = new (*this) ParenType(InnerType, Canon);
2797 Types.push_back(T);
2798 ParenTypes.InsertNode(T, InsertPos);
2799 return QualType(T, 0);
2800}
2801
Douglas Gregor02085352010-03-31 20:19:30 +00002802QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2803 NestedNameSpecifier *NNS,
2804 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002805 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002806 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2807
2808 if (Canon.isNull()) {
2809 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002810 ElaboratedTypeKeyword CanonKeyword = Keyword;
2811 if (Keyword == ETK_None)
2812 CanonKeyword = ETK_Typename;
2813
2814 if (CanonNNS != NNS || CanonKeyword != Keyword)
2815 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002816 }
2817
2818 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002819 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002820
2821 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002822 DependentNameType *T
2823 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002824 if (T)
2825 return QualType(T, 0);
2826
Douglas Gregor02085352010-03-31 20:19:30 +00002827 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002828 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002829 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002830 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002831}
2832
Mike Stump11289f42009-09-09 15:08:12 +00002833QualType
John McCallc392f372010-06-11 00:33:02 +00002834ASTContext::getDependentTemplateSpecializationType(
2835 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002836 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002837 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002838 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002839 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002840 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002841 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2842 ArgCopy.push_back(Args[I].getArgument());
2843 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2844 ArgCopy.size(),
2845 ArgCopy.data());
2846}
2847
2848QualType
2849ASTContext::getDependentTemplateSpecializationType(
2850 ElaboratedTypeKeyword Keyword,
2851 NestedNameSpecifier *NNS,
2852 const IdentifierInfo *Name,
2853 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002854 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002855 assert((!NNS || NNS->isDependent()) &&
2856 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002857
Douglas Gregorc42075a2010-02-04 18:10:26 +00002858 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002859 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2860 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002861
2862 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002863 DependentTemplateSpecializationType *T
2864 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002865 if (T)
2866 return QualType(T, 0);
2867
John McCallc392f372010-06-11 00:33:02 +00002868 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002869
John McCallc392f372010-06-11 00:33:02 +00002870 ElaboratedTypeKeyword CanonKeyword = Keyword;
2871 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2872
2873 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002874 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002875 for (unsigned I = 0; I != NumArgs; ++I) {
2876 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2877 if (!CanonArgs[I].structurallyEquals(Args[I]))
2878 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002879 }
2880
John McCallc392f372010-06-11 00:33:02 +00002881 QualType Canon;
2882 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2883 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2884 Name, NumArgs,
2885 CanonArgs.data());
2886
2887 // Find the insert position again.
2888 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2889 }
2890
2891 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2892 sizeof(TemplateArgument) * NumArgs),
2893 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002894 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002895 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002896 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002897 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002898 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002899}
2900
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002901QualType ASTContext::getPackExpansionType(QualType Pattern,
2902 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002903 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002904 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002905
2906 assert(Pattern->containsUnexpandedParameterPack() &&
2907 "Pack expansions must expand one or more parameter packs");
2908 void *InsertPos = 0;
2909 PackExpansionType *T
2910 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2911 if (T)
2912 return QualType(T, 0);
2913
2914 QualType Canon;
2915 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00002916 Canon = getCanonicalType(Pattern);
2917 // The canonical type might not contain an unexpanded parameter pack, if it
2918 // contains an alias template specialization which ignores one of its
2919 // parameters.
2920 if (Canon->containsUnexpandedParameterPack()) {
2921 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002922
Richard Smith68eea502012-07-16 00:20:35 +00002923 // Find the insert position again, in case we inserted an element into
2924 // PackExpansionTypes and invalidated our insert position.
2925 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2926 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00002927 }
2928
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002929 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002930 Types.push_back(T);
2931 PackExpansionTypes.InsertNode(T, InsertPos);
2932 return QualType(T, 0);
2933}
2934
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002935/// CmpProtocolNames - Comparison predicate for sorting protocols
2936/// alphabetically.
2937static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2938 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002939 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002940}
2941
John McCall8b07ec22010-05-15 11:32:37 +00002942static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002943 unsigned NumProtocols) {
2944 if (NumProtocols == 0) return true;
2945
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002946 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2947 return false;
2948
John McCallfc93cf92009-10-22 22:37:11 +00002949 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002950 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2951 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002952 return false;
2953 return true;
2954}
2955
2956static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002957 unsigned &NumProtocols) {
2958 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002959
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002960 // Sort protocols, keyed by name.
2961 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2962
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002963 // Canonicalize.
2964 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2965 Protocols[I] = Protocols[I]->getCanonicalDecl();
2966
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002967 // Remove duplicates.
2968 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2969 NumProtocols = ProtocolsEnd-Protocols;
2970}
2971
John McCall8b07ec22010-05-15 11:32:37 +00002972QualType ASTContext::getObjCObjectType(QualType BaseType,
2973 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002974 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002975 // If the base type is an interface and there aren't any protocols
2976 // to add, then the interface type will do just fine.
2977 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2978 return BaseType;
2979
2980 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002981 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002982 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002983 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002984 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2985 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002986
John McCall8b07ec22010-05-15 11:32:37 +00002987 // Build the canonical type, which has the canonical base type and
2988 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002989 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002990 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2991 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2992 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002993 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002994 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002995 unsigned UniqueCount = NumProtocols;
2996
John McCallfc93cf92009-10-22 22:37:11 +00002997 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002998 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2999 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003000 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003001 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3002 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003003 }
3004
3005 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003006 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3007 }
3008
3009 unsigned Size = sizeof(ObjCObjectTypeImpl);
3010 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3011 void *Mem = Allocate(Size, TypeAlignment);
3012 ObjCObjectTypeImpl *T =
3013 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3014
3015 Types.push_back(T);
3016 ObjCObjectTypes.InsertNode(T, InsertPos);
3017 return QualType(T, 0);
3018}
3019
3020/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3021/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003022QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003023 llvm::FoldingSetNodeID ID;
3024 ObjCObjectPointerType::Profile(ID, ObjectT);
3025
3026 void *InsertPos = 0;
3027 if (ObjCObjectPointerType *QT =
3028 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3029 return QualType(QT, 0);
3030
3031 // Find the canonical object type.
3032 QualType Canonical;
3033 if (!ObjectT.isCanonical()) {
3034 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3035
3036 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003037 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3038 }
3039
Douglas Gregorf85bee62010-02-08 22:59:26 +00003040 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003041 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3042 ObjCObjectPointerType *QType =
3043 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003044
Steve Narofffb4330f2009-06-17 22:40:22 +00003045 Types.push_back(QType);
3046 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003047 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003048}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003049
Douglas Gregor1c283312010-08-11 12:19:30 +00003050/// getObjCInterfaceType - Return the unique reference to the type for the
3051/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003052QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3053 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003054 if (Decl->TypeForDecl)
3055 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003056
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003057 if (PrevDecl) {
3058 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3059 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3060 return QualType(PrevDecl->TypeForDecl, 0);
3061 }
3062
Douglas Gregor7671e532011-12-16 16:34:57 +00003063 // Prefer the definition, if there is one.
3064 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3065 Decl = Def;
3066
Douglas Gregor1c283312010-08-11 12:19:30 +00003067 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3068 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3069 Decl->TypeForDecl = T;
3070 Types.push_back(T);
3071 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003072}
3073
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003074/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3075/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003076/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003077/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003078/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003079QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003080 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003081 if (tofExpr->isTypeDependent()) {
3082 llvm::FoldingSetNodeID ID;
3083 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003084
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003085 void *InsertPos = 0;
3086 DependentTypeOfExprType *Canon
3087 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3088 if (Canon) {
3089 // We already have a "canonical" version of an identical, dependent
3090 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003091 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003092 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003093 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003094 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003095 Canon
3096 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003097 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3098 toe = Canon;
3099 }
3100 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003101 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003102 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003103 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003104 Types.push_back(toe);
3105 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003106}
3107
Steve Naroffa773cd52007-08-01 18:02:17 +00003108/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3109/// TypeOfType AST's. The only motivation to unique these nodes would be
3110/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003111/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003112/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003113QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003114 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003115 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003116 Types.push_back(tot);
3117 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003118}
3119
Anders Carlssonad6bd352009-06-24 21:24:56 +00003120
Anders Carlsson81df7b82009-06-24 19:06:50 +00003121/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3122/// DecltypeType AST's. The only motivation to unique these nodes would be
3123/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003124/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003125/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003126QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003127 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003128
3129 // C++0x [temp.type]p2:
3130 // If an expression e involves a template parameter, decltype(e) denotes a
3131 // unique dependent type. Two such decltype-specifiers refer to the same
3132 // type only if their expressions are equivalent (14.5.6.1).
3133 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003134 llvm::FoldingSetNodeID ID;
3135 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003136
Douglas Gregora21f6c32009-07-30 23:36:40 +00003137 void *InsertPos = 0;
3138 DependentDecltypeType *Canon
3139 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3140 if (Canon) {
3141 // We already have a "canonical" version of an equivalent, dependent
3142 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003143 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003144 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003145 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003146 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003147 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003148 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3149 dt = Canon;
3150 }
3151 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003152 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3153 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003154 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003155 Types.push_back(dt);
3156 return QualType(dt, 0);
3157}
3158
Alexis Hunte852b102011-05-24 22:41:36 +00003159/// getUnaryTransformationType - We don't unique these, since the memory
3160/// savings are minimal and these are rare.
3161QualType ASTContext::getUnaryTransformType(QualType BaseType,
3162 QualType UnderlyingType,
3163 UnaryTransformType::UTTKind Kind)
3164 const {
3165 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003166 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3167 Kind,
3168 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003169 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003170 Types.push_back(Ty);
3171 return QualType(Ty, 0);
3172}
3173
Richard Smithb2bc2e62011-02-21 20:05:19 +00003174/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003175QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003176 void *InsertPos = 0;
3177 if (!DeducedType.isNull()) {
3178 // Look in the folding set for an existing type.
3179 llvm::FoldingSetNodeID ID;
3180 AutoType::Profile(ID, DeducedType);
3181 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3182 return QualType(AT, 0);
3183 }
3184
3185 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3186 Types.push_back(AT);
3187 if (InsertPos)
3188 AutoTypes.InsertNode(AT, InsertPos);
3189 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003190}
3191
Eli Friedman0dfb8892011-10-06 23:00:33 +00003192/// getAtomicType - Return the uniqued reference to the atomic type for
3193/// the given value type.
3194QualType ASTContext::getAtomicType(QualType T) const {
3195 // Unique pointers, to guarantee there is only one pointer of a particular
3196 // structure.
3197 llvm::FoldingSetNodeID ID;
3198 AtomicType::Profile(ID, T);
3199
3200 void *InsertPos = 0;
3201 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3202 return QualType(AT, 0);
3203
3204 // If the atomic value type isn't canonical, this won't be a canonical type
3205 // either, so fill in the canonical type field.
3206 QualType Canonical;
3207 if (!T.isCanonical()) {
3208 Canonical = getAtomicType(getCanonicalType(T));
3209
3210 // Get the new insert position for the node we care about.
3211 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3212 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3213 }
3214 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3215 Types.push_back(New);
3216 AtomicTypes.InsertNode(New, InsertPos);
3217 return QualType(New, 0);
3218}
3219
Richard Smith02e85f32011-04-14 22:09:26 +00003220/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3221QualType ASTContext::getAutoDeductType() const {
3222 if (AutoDeductTy.isNull())
3223 AutoDeductTy = getAutoType(QualType());
3224 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3225 return AutoDeductTy;
3226}
3227
3228/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3229QualType ASTContext::getAutoRRefDeductType() const {
3230 if (AutoRRefDeductTy.isNull())
3231 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3232 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3233 return AutoRRefDeductTy;
3234}
3235
Chris Lattnerfb072462007-01-23 05:45:31 +00003236/// getTagDeclType - Return the unique reference to the type for the
3237/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003238QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003239 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003240 // FIXME: What is the design on getTagDeclType when it requires casting
3241 // away const? mutable?
3242 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003243}
3244
Mike Stump11289f42009-09-09 15:08:12 +00003245/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3246/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3247/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003248CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003249 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003250}
Chris Lattnerfb072462007-01-23 05:45:31 +00003251
Hans Wennborg27541db2011-10-27 08:29:09 +00003252/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3253CanQualType ASTContext::getIntMaxType() const {
3254 return getFromTargetType(Target->getIntMaxType());
3255}
3256
3257/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3258CanQualType ASTContext::getUIntMaxType() const {
3259 return getFromTargetType(Target->getUIntMaxType());
3260}
3261
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003262/// getSignedWCharType - Return the type of "signed wchar_t".
3263/// Used when in C++, as a GCC extension.
3264QualType ASTContext::getSignedWCharType() const {
3265 // FIXME: derive from "Target" ?
3266 return WCharTy;
3267}
3268
3269/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3270/// Used when in C++, as a GCC extension.
3271QualType ASTContext::getUnsignedWCharType() const {
3272 // FIXME: derive from "Target" ?
3273 return UnsignedIntTy;
3274}
3275
Hans Wennborg27541db2011-10-27 08:29:09 +00003276/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003277/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3278QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003279 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003280}
3281
Chris Lattnera21ad802008-04-02 05:18:44 +00003282//===----------------------------------------------------------------------===//
3283// Type Operators
3284//===----------------------------------------------------------------------===//
3285
Jay Foad39c79802011-01-12 09:06:06 +00003286CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003287 // Push qualifiers into arrays, and then discard any remaining
3288 // qualifiers.
3289 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003290 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003291 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003292 QualType Result;
3293 if (isa<ArrayType>(Ty)) {
3294 Result = getArrayDecayedType(QualType(Ty,0));
3295 } else if (isa<FunctionType>(Ty)) {
3296 Result = getPointerType(QualType(Ty, 0));
3297 } else {
3298 Result = QualType(Ty, 0);
3299 }
3300
3301 return CanQualType::CreateUnsafe(Result);
3302}
3303
John McCall6c9dd522011-01-18 07:41:22 +00003304QualType ASTContext::getUnqualifiedArrayType(QualType type,
3305 Qualifiers &quals) {
3306 SplitQualType splitType = type.getSplitUnqualifiedType();
3307
3308 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3309 // the unqualified desugared type and then drops it on the floor.
3310 // We then have to strip that sugar back off with
3311 // getUnqualifiedDesugaredType(), which is silly.
3312 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003313 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003314
3315 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003316 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003317 quals = splitType.Quals;
3318 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003319 }
3320
John McCall6c9dd522011-01-18 07:41:22 +00003321 // Otherwise, recurse on the array's element type.
3322 QualType elementType = AT->getElementType();
3323 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3324
3325 // If that didn't change the element type, AT has no qualifiers, so we
3326 // can just use the results in splitType.
3327 if (elementType == unqualElementType) {
3328 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003329 quals = splitType.Quals;
3330 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003331 }
3332
3333 // Otherwise, add in the qualifiers from the outermost type, then
3334 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003335 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003336
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003337 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003338 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003339 CAT->getSizeModifier(), 0);
3340 }
3341
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003342 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003343 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003344 }
3345
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003346 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003347 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003348 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003349 VAT->getSizeModifier(),
3350 VAT->getIndexTypeCVRQualifiers(),
3351 VAT->getBracketsRange());
3352 }
3353
3354 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003355 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003356 DSAT->getSizeModifier(), 0,
3357 SourceRange());
3358}
3359
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003360/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3361/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3362/// they point to and return true. If T1 and T2 aren't pointer types
3363/// or pointer-to-member types, or if they are not similar at this
3364/// level, returns false and leaves T1 and T2 unchanged. Top-level
3365/// qualifiers on T1 and T2 are ignored. This function will typically
3366/// be called in a loop that successively "unwraps" pointer and
3367/// pointer-to-member types to compare them at each level.
3368bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3369 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3370 *T2PtrType = T2->getAs<PointerType>();
3371 if (T1PtrType && T2PtrType) {
3372 T1 = T1PtrType->getPointeeType();
3373 T2 = T2PtrType->getPointeeType();
3374 return true;
3375 }
3376
3377 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3378 *T2MPType = T2->getAs<MemberPointerType>();
3379 if (T1MPType && T2MPType &&
3380 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3381 QualType(T2MPType->getClass(), 0))) {
3382 T1 = T1MPType->getPointeeType();
3383 T2 = T2MPType->getPointeeType();
3384 return true;
3385 }
3386
David Blaikiebbafb8a2012-03-11 07:00:24 +00003387 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003388 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3389 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3390 if (T1OPType && T2OPType) {
3391 T1 = T1OPType->getPointeeType();
3392 T2 = T2OPType->getPointeeType();
3393 return true;
3394 }
3395 }
3396
3397 // FIXME: Block pointers, too?
3398
3399 return false;
3400}
3401
Jay Foad39c79802011-01-12 09:06:06 +00003402DeclarationNameInfo
3403ASTContext::getNameForTemplate(TemplateName Name,
3404 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003405 switch (Name.getKind()) {
3406 case TemplateName::QualifiedTemplate:
3407 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003408 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003409 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3410 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003411
John McCalld9dfe3a2011-06-30 08:33:18 +00003412 case TemplateName::OverloadedTemplate: {
3413 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3414 // DNInfo work in progress: CHECKME: what about DNLoc?
3415 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3416 }
3417
3418 case TemplateName::DependentTemplate: {
3419 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003420 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003421 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003422 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3423 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003424 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003425 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3426 // DNInfo work in progress: FIXME: source locations?
3427 DeclarationNameLoc DNLoc;
3428 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3429 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3430 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003431 }
3432 }
3433
John McCalld9dfe3a2011-06-30 08:33:18 +00003434 case TemplateName::SubstTemplateTemplateParm: {
3435 SubstTemplateTemplateParmStorage *subst
3436 = Name.getAsSubstTemplateTemplateParm();
3437 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3438 NameLoc);
3439 }
3440
3441 case TemplateName::SubstTemplateTemplateParmPack: {
3442 SubstTemplateTemplateParmPackStorage *subst
3443 = Name.getAsSubstTemplateTemplateParmPack();
3444 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3445 NameLoc);
3446 }
3447 }
3448
3449 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003450}
3451
Jay Foad39c79802011-01-12 09:06:06 +00003452TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003453 switch (Name.getKind()) {
3454 case TemplateName::QualifiedTemplate:
3455 case TemplateName::Template: {
3456 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003457 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003458 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003459 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3460
3461 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003462 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003463 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003464
John McCalld9dfe3a2011-06-30 08:33:18 +00003465 case TemplateName::OverloadedTemplate:
3466 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003467
John McCalld9dfe3a2011-06-30 08:33:18 +00003468 case TemplateName::DependentTemplate: {
3469 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3470 assert(DTN && "Non-dependent template names must refer to template decls.");
3471 return DTN->CanonicalTemplateName;
3472 }
3473
3474 case TemplateName::SubstTemplateTemplateParm: {
3475 SubstTemplateTemplateParmStorage *subst
3476 = Name.getAsSubstTemplateTemplateParm();
3477 return getCanonicalTemplateName(subst->getReplacement());
3478 }
3479
3480 case TemplateName::SubstTemplateTemplateParmPack: {
3481 SubstTemplateTemplateParmPackStorage *subst
3482 = Name.getAsSubstTemplateTemplateParmPack();
3483 TemplateTemplateParmDecl *canonParameter
3484 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3485 TemplateArgument canonArgPack
3486 = getCanonicalTemplateArgument(subst->getArgumentPack());
3487 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3488 }
3489 }
3490
3491 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003492}
3493
Douglas Gregoradee3e32009-11-11 23:06:43 +00003494bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3495 X = getCanonicalTemplateName(X);
3496 Y = getCanonicalTemplateName(Y);
3497 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3498}
3499
Mike Stump11289f42009-09-09 15:08:12 +00003500TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003501ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003502 switch (Arg.getKind()) {
3503 case TemplateArgument::Null:
3504 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003505
Douglas Gregora8e02e72009-07-28 23:00:59 +00003506 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003507 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003508
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003509 case TemplateArgument::Declaration: {
3510 if (Decl *D = Arg.getAsDecl())
3511 return TemplateArgument(D->getCanonicalDecl());
3512 return TemplateArgument((Decl*)0);
3513 }
Mike Stump11289f42009-09-09 15:08:12 +00003514
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003515 case TemplateArgument::Template:
3516 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003517
3518 case TemplateArgument::TemplateExpansion:
3519 return TemplateArgument(getCanonicalTemplateName(
3520 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003521 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003522
Douglas Gregora8e02e72009-07-28 23:00:59 +00003523 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003524 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003525
Douglas Gregora8e02e72009-07-28 23:00:59 +00003526 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003527 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003528
Douglas Gregora8e02e72009-07-28 23:00:59 +00003529 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003530 if (Arg.pack_size() == 0)
3531 return Arg;
3532
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003533 TemplateArgument *CanonArgs
3534 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003535 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003536 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003537 AEnd = Arg.pack_end();
3538 A != AEnd; (void)++A, ++Idx)
3539 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003540
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003541 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003542 }
3543 }
3544
3545 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003546 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003547}
3548
Douglas Gregor333489b2009-03-27 23:10:48 +00003549NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003550ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003551 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003552 return 0;
3553
3554 switch (NNS->getKind()) {
3555 case NestedNameSpecifier::Identifier:
3556 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003557 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003558 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3559 NNS->getAsIdentifier());
3560
3561 case NestedNameSpecifier::Namespace:
3562 // A namespace is canonical; build a nested-name-specifier with
3563 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003564 return NestedNameSpecifier::Create(*this, 0,
3565 NNS->getAsNamespace()->getOriginalNamespace());
3566
3567 case NestedNameSpecifier::NamespaceAlias:
3568 // A namespace is canonical; build a nested-name-specifier with
3569 // this namespace and no prefix.
3570 return NestedNameSpecifier::Create(*this, 0,
3571 NNS->getAsNamespaceAlias()->getNamespace()
3572 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003573
3574 case NestedNameSpecifier::TypeSpec:
3575 case NestedNameSpecifier::TypeSpecWithTemplate: {
3576 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003577
3578 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3579 // break it apart into its prefix and identifier, then reconsititute those
3580 // as the canonical nested-name-specifier. This is required to canonicalize
3581 // a dependent nested-name-specifier involving typedefs of dependent-name
3582 // types, e.g.,
3583 // typedef typename T::type T1;
3584 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003585 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3586 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003587 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003588
Eli Friedman5358a0a2012-03-03 04:09:56 +00003589 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3590 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3591 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003592 return NestedNameSpecifier::Create(*this, 0, false,
3593 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003594 }
3595
3596 case NestedNameSpecifier::Global:
3597 // The global specifier is canonical and unique.
3598 return NNS;
3599 }
3600
David Blaikie8a40f702012-01-17 06:56:22 +00003601 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003602}
3603
Chris Lattner7adf0762008-08-04 07:31:14 +00003604
Jay Foad39c79802011-01-12 09:06:06 +00003605const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003606 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003607 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003608 // Handle the common positive case fast.
3609 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3610 return AT;
3611 }
Mike Stump11289f42009-09-09 15:08:12 +00003612
John McCall8ccfcb52009-09-24 19:53:00 +00003613 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003614 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003615 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003616
John McCall8ccfcb52009-09-24 19:53:00 +00003617 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003618 // implements C99 6.7.3p8: "If the specification of an array type includes
3619 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003620
Chris Lattner7adf0762008-08-04 07:31:14 +00003621 // If we get here, we either have type qualifiers on the type, or we have
3622 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003623 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003624
John McCall33ddac02011-01-19 10:06:00 +00003625 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003626 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003627
Chris Lattner7adf0762008-08-04 07:31:14 +00003628 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003629 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003630 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003631 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003632
Chris Lattner7adf0762008-08-04 07:31:14 +00003633 // Otherwise, we have an array and we have qualifiers on it. Push the
3634 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003635 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003636
Chris Lattner7adf0762008-08-04 07:31:14 +00003637 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3638 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3639 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003640 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003641 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3642 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3643 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003644 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003645
Mike Stump11289f42009-09-09 15:08:12 +00003646 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003647 = dyn_cast<DependentSizedArrayType>(ATy))
3648 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003649 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003650 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003651 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003652 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003653 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003654
Chris Lattner7adf0762008-08-04 07:31:14 +00003655 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003656 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003657 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003658 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003659 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003660 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003661}
3662
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003663QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003664 // C99 6.7.5.3p7:
3665 // A declaration of a parameter as "array of type" shall be
3666 // adjusted to "qualified pointer to type", where the type
3667 // qualifiers (if any) are those specified within the [ and ] of
3668 // the array type derivation.
3669 if (T->isArrayType())
3670 return getArrayDecayedType(T);
3671
3672 // C99 6.7.5.3p8:
3673 // A declaration of a parameter as "function returning type"
3674 // shall be adjusted to "pointer to function returning type", as
3675 // in 6.3.2.1.
3676 if (T->isFunctionType())
3677 return getPointerType(T);
3678
3679 return T;
3680}
3681
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003682QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003683 T = getVariableArrayDecayedType(T);
3684 T = getAdjustedParameterType(T);
3685 return T.getUnqualifiedType();
3686}
3687
Chris Lattnera21ad802008-04-02 05:18:44 +00003688/// getArrayDecayedType - Return the properly qualified result of decaying the
3689/// specified array type to a pointer. This operation is non-trivial when
3690/// handling typedefs etc. The canonical type of "T" must be an array type,
3691/// this returns a pointer to a properly qualified element of the array.
3692///
3693/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003694QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003695 // Get the element type with 'getAsArrayType' so that we don't lose any
3696 // typedefs in the element type of the array. This also handles propagation
3697 // of type qualifiers from the array type into the element type if present
3698 // (C99 6.7.3p8).
3699 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3700 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003701
Chris Lattner7adf0762008-08-04 07:31:14 +00003702 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003703
3704 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003705 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003706}
3707
John McCall33ddac02011-01-19 10:06:00 +00003708QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3709 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003710}
3711
John McCall33ddac02011-01-19 10:06:00 +00003712QualType ASTContext::getBaseElementType(QualType type) const {
3713 Qualifiers qs;
3714 while (true) {
3715 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003716 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003717 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003718
John McCall33ddac02011-01-19 10:06:00 +00003719 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003720 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003721 }
Mike Stump11289f42009-09-09 15:08:12 +00003722
John McCall33ddac02011-01-19 10:06:00 +00003723 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003724}
3725
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003726/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003727uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003728ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3729 uint64_t ElementCount = 1;
3730 do {
3731 ElementCount *= CA->getSize().getZExtValue();
3732 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3733 } while (CA);
3734 return ElementCount;
3735}
3736
Steve Naroff0af91202007-04-27 21:51:21 +00003737/// getFloatingRank - Return a relative rank for floating point types.
3738/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003739static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003740 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003741 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003742
John McCall9dd450b2009-09-21 23:43:11 +00003743 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3744 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003745 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003746 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003747 case BuiltinType::Float: return FloatRank;
3748 case BuiltinType::Double: return DoubleRank;
3749 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003750 }
3751}
3752
Mike Stump11289f42009-09-09 15:08:12 +00003753/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3754/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003755/// 'typeDomain' is a real floating point or complex type.
3756/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003757QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3758 QualType Domain) const {
3759 FloatingRank EltRank = getFloatingRank(Size);
3760 if (Domain->isComplexType()) {
3761 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003762 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003763 case FloatRank: return FloatComplexTy;
3764 case DoubleRank: return DoubleComplexTy;
3765 case LongDoubleRank: return LongDoubleComplexTy;
3766 }
Steve Naroff0af91202007-04-27 21:51:21 +00003767 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003768
3769 assert(Domain->isRealFloatingType() && "Unknown domain!");
3770 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003771 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003772 case FloatRank: return FloatTy;
3773 case DoubleRank: return DoubleTy;
3774 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003775 }
David Blaikief47fa302012-01-17 02:30:50 +00003776 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003777}
3778
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003779/// getFloatingTypeOrder - Compare the rank of the two specified floating
3780/// point types, ignoring the domain of the type (i.e. 'double' ==
3781/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003782/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003783int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003784 FloatingRank LHSR = getFloatingRank(LHS);
3785 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003786
Chris Lattnerb90739d2008-04-06 23:38:49 +00003787 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003788 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003789 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003790 return 1;
3791 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003792}
3793
Chris Lattner76a00cf2008-04-06 22:59:24 +00003794/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3795/// routine will assert if passed a built-in type that isn't an integer or enum,
3796/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003797unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003798 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003799
Chris Lattner76a00cf2008-04-06 22:59:24 +00003800 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003801 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003802 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003803 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003804 case BuiltinType::Char_S:
3805 case BuiltinType::Char_U:
3806 case BuiltinType::SChar:
3807 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003808 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003809 case BuiltinType::Short:
3810 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003811 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003812 case BuiltinType::Int:
3813 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003814 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003815 case BuiltinType::Long:
3816 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003817 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003818 case BuiltinType::LongLong:
3819 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003820 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003821 case BuiltinType::Int128:
3822 case BuiltinType::UInt128:
3823 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003824 }
3825}
3826
Eli Friedman629ffb92009-08-20 04:21:42 +00003827/// \brief Whether this is a promotable bitfield reference according
3828/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3829///
3830/// \returns the type this bit-field will promote to, or NULL if no
3831/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003832QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003833 if (E->isTypeDependent() || E->isValueDependent())
3834 return QualType();
3835
Eli Friedman629ffb92009-08-20 04:21:42 +00003836 FieldDecl *Field = E->getBitField();
3837 if (!Field)
3838 return QualType();
3839
3840 QualType FT = Field->getType();
3841
Richard Smithcaf33902011-10-10 18:28:20 +00003842 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003843 uint64_t IntSize = getTypeSize(IntTy);
3844 // GCC extension compatibility: if the bit-field size is less than or equal
3845 // to the size of int, it gets promoted no matter what its type is.
3846 // For instance, unsigned long bf : 4 gets promoted to signed int.
3847 if (BitWidth < IntSize)
3848 return IntTy;
3849
3850 if (BitWidth == IntSize)
3851 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3852
3853 // Types bigger than int are not subject to promotions, and therefore act
3854 // like the base type.
3855 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3856 // is ridiculous.
3857 return QualType();
3858}
3859
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003860/// getPromotedIntegerType - Returns the type that Promotable will
3861/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3862/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003863QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003864 assert(!Promotable.isNull());
3865 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003866 if (const EnumType *ET = Promotable->getAs<EnumType>())
3867 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003868
3869 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3870 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3871 // (3.9.1) can be converted to a prvalue of the first of the following
3872 // types that can represent all the values of its underlying type:
3873 // int, unsigned int, long int, unsigned long int, long long int, or
3874 // unsigned long long int [...]
3875 // FIXME: Is there some better way to compute this?
3876 if (BT->getKind() == BuiltinType::WChar_S ||
3877 BT->getKind() == BuiltinType::WChar_U ||
3878 BT->getKind() == BuiltinType::Char16 ||
3879 BT->getKind() == BuiltinType::Char32) {
3880 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3881 uint64_t FromSize = getTypeSize(BT);
3882 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3883 LongLongTy, UnsignedLongLongTy };
3884 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3885 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3886 if (FromSize < ToSize ||
3887 (FromSize == ToSize &&
3888 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3889 return PromoteTypes[Idx];
3890 }
3891 llvm_unreachable("char type should fit into long long");
3892 }
3893 }
3894
3895 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003896 if (Promotable->isSignedIntegerType())
3897 return IntTy;
3898 uint64_t PromotableSize = getTypeSize(Promotable);
3899 uint64_t IntSize = getTypeSize(IntTy);
3900 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3901 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3902}
3903
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003904/// \brief Recurses in pointer/array types until it finds an objc retainable
3905/// type and returns its ownership.
3906Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3907 while (!T.isNull()) {
3908 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3909 return T.getObjCLifetime();
3910 if (T->isArrayType())
3911 T = getBaseElementType(T);
3912 else if (const PointerType *PT = T->getAs<PointerType>())
3913 T = PT->getPointeeType();
3914 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003915 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003916 else
3917 break;
3918 }
3919
3920 return Qualifiers::OCL_None;
3921}
3922
Mike Stump11289f42009-09-09 15:08:12 +00003923/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003924/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003925/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003926int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003927 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3928 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003929 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003930
Chris Lattner76a00cf2008-04-06 22:59:24 +00003931 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3932 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003933
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003934 unsigned LHSRank = getIntegerRank(LHSC);
3935 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003936
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003937 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3938 if (LHSRank == RHSRank) return 0;
3939 return LHSRank > RHSRank ? 1 : -1;
3940 }
Mike Stump11289f42009-09-09 15:08:12 +00003941
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003942 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3943 if (LHSUnsigned) {
3944 // If the unsigned [LHS] type is larger, return it.
3945 if (LHSRank >= RHSRank)
3946 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003947
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003948 // If the signed type can represent all values of the unsigned type, it
3949 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003950 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003951 return -1;
3952 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003953
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003954 // If the unsigned [RHS] type is larger, return it.
3955 if (RHSRank >= LHSRank)
3956 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003957
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003958 // If the signed type can represent all values of the unsigned type, it
3959 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003960 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003961 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003962}
Anders Carlsson98f07902007-08-17 05:31:46 +00003963
Anders Carlsson6d417272009-11-14 21:45:58 +00003964static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003965CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3966 DeclContext *DC, IdentifierInfo *Id) {
3967 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003968 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003969 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003970 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003971 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003972}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003973
Mike Stump11289f42009-09-09 15:08:12 +00003974// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003975QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003976 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003977 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003978 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003979 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003980 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003981
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003982 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003983
Anders Carlsson98f07902007-08-17 05:31:46 +00003984 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003985 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003986 // int flags;
3987 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003988 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003989 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003990 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003991 FieldTypes[3] = LongTy;
3992
Anders Carlsson98f07902007-08-17 05:31:46 +00003993 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003994 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003995 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003996 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003997 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003998 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003999 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004000 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004001 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004002 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004003 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004004 }
4005
Douglas Gregord5058122010-02-11 01:19:42 +00004006 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004007 }
Mike Stump11289f42009-09-09 15:08:12 +00004008
Anders Carlsson98f07902007-08-17 05:31:46 +00004009 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004010}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004011
Douglas Gregor512b0772009-04-23 22:29:11 +00004012void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004013 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004014 assert(Rec && "Invalid CFConstantStringType");
4015 CFConstantStringTypeDecl = Rec->getDecl();
4016}
4017
Jay Foad39c79802011-01-12 09:06:06 +00004018QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004019 if (BlockDescriptorType)
4020 return getTagDeclType(BlockDescriptorType);
4021
4022 RecordDecl *T;
4023 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004024 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004025 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004026 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004027
4028 QualType FieldTypes[] = {
4029 UnsignedLongTy,
4030 UnsignedLongTy,
4031 };
4032
4033 const char *FieldNames[] = {
4034 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004035 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004036 };
4037
4038 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004039 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004040 SourceLocation(),
4041 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004042 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004043 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004044 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004045 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004046 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004047 T->addDecl(Field);
4048 }
4049
Douglas Gregord5058122010-02-11 01:19:42 +00004050 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004051
4052 BlockDescriptorType = T;
4053
4054 return getTagDeclType(BlockDescriptorType);
4055}
4056
Jay Foad39c79802011-01-12 09:06:06 +00004057QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004058 if (BlockDescriptorExtendedType)
4059 return getTagDeclType(BlockDescriptorExtendedType);
4060
4061 RecordDecl *T;
4062 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004063 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004064 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004065 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004066
4067 QualType FieldTypes[] = {
4068 UnsignedLongTy,
4069 UnsignedLongTy,
4070 getPointerType(VoidPtrTy),
4071 getPointerType(VoidPtrTy)
4072 };
4073
4074 const char *FieldNames[] = {
4075 "reserved",
4076 "Size",
4077 "CopyFuncPtr",
4078 "DestroyFuncPtr"
4079 };
4080
4081 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004082 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004083 SourceLocation(),
4084 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004085 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004086 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004087 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004088 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004089 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004090 T->addDecl(Field);
4091 }
4092
Douglas Gregord5058122010-02-11 01:19:42 +00004093 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004094
4095 BlockDescriptorExtendedType = T;
4096
4097 return getTagDeclType(BlockDescriptorExtendedType);
4098}
4099
Jay Foad39c79802011-01-12 09:06:06 +00004100bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004101 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004102 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004103 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004104 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4105 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004106 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004107
4108 }
4109 }
Mike Stump94967902009-10-21 18:16:27 +00004110 return false;
4111}
4112
Jay Foad39c79802011-01-12 09:06:06 +00004113QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004114ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004115 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004116 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004117 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004118 // unsigned int __flags;
4119 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004120 // void *__copy_helper; // as needed
4121 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004122 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004123 // } *
4124
Mike Stump94967902009-10-21 18:16:27 +00004125 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4126
4127 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004128 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004129 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4130 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004131 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004132 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004133 T->startDefinition();
4134 QualType Int32Ty = IntTy;
4135 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4136 QualType FieldTypes[] = {
4137 getPointerType(VoidPtrTy),
4138 getPointerType(getTagDeclType(T)),
4139 Int32Ty,
4140 Int32Ty,
4141 getPointerType(VoidPtrTy),
4142 getPointerType(VoidPtrTy),
4143 Ty
4144 };
4145
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004146 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004147 "__isa",
4148 "__forwarding",
4149 "__flags",
4150 "__size",
4151 "__copy_helper",
4152 "__destroy_helper",
4153 DeclName,
4154 };
4155
4156 for (size_t i = 0; i < 7; ++i) {
4157 if (!HasCopyAndDispose && i >=4 && i <= 5)
4158 continue;
4159 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004160 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004161 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004162 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004163 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004164 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004165 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004166 T->addDecl(Field);
4167 }
4168
Douglas Gregord5058122010-02-11 01:19:42 +00004169 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004170
4171 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004172}
4173
Douglas Gregorbab8a962011-09-08 01:46:34 +00004174TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4175 if (!ObjCInstanceTypeDecl)
4176 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4177 getTranslationUnitDecl(),
4178 SourceLocation(),
4179 SourceLocation(),
4180 &Idents.get("instancetype"),
4181 getTrivialTypeSourceInfo(getObjCIdType()));
4182 return ObjCInstanceTypeDecl;
4183}
4184
Anders Carlsson18acd442007-10-29 06:33:42 +00004185// This returns true if a type has been typedefed to BOOL:
4186// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004187static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004188 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004189 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4190 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004191
Anders Carlssond8499822007-10-29 05:01:08 +00004192 return false;
4193}
4194
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004195/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004196/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004197CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004198 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4199 return CharUnits::Zero();
4200
Ken Dyck40775002010-01-11 17:06:35 +00004201 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004202
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004203 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004204 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004205 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004206 // Treat arrays as pointers, since that's how they're passed in.
4207 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004208 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004209 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004210}
4211
4212static inline
4213std::string charUnitsToString(const CharUnits &CU) {
4214 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004215}
4216
John McCall351762c2011-02-07 10:33:21 +00004217/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004218/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004219std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4220 std::string S;
4221
David Chisnall950a9512009-11-17 19:33:30 +00004222 const BlockDecl *Decl = Expr->getBlockDecl();
4223 QualType BlockTy =
4224 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4225 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004226 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004227 // Compute size of all parameters.
4228 // Start with computing size of a pointer in number of bytes.
4229 // FIXME: There might(should) be a better way of doing this computation!
4230 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004231 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4232 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004233 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004234 E = Decl->param_end(); PI != E; ++PI) {
4235 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004236 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004237 if (sz.isZero())
4238 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004239 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004240 ParmOffset += sz;
4241 }
4242 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004243 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004244 // Block pointer and offset.
4245 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004246
4247 // Argument types.
4248 ParmOffset = PtrSize;
4249 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4250 Decl->param_end(); PI != E; ++PI) {
4251 ParmVarDecl *PVDecl = *PI;
4252 QualType PType = PVDecl->getOriginalType();
4253 if (const ArrayType *AT =
4254 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4255 // Use array's original type only if it has known number of
4256 // elements.
4257 if (!isa<ConstantArrayType>(AT))
4258 PType = PVDecl->getType();
4259 } else if (PType->isFunctionType())
4260 PType = PVDecl->getType();
4261 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004262 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004263 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004264 }
John McCall351762c2011-02-07 10:33:21 +00004265
4266 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004267}
4268
Douglas Gregora9d84932011-05-27 01:19:52 +00004269bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004270 std::string& S) {
4271 // Encode result type.
4272 getObjCEncodingForType(Decl->getResultType(), S);
4273 CharUnits ParmOffset;
4274 // Compute size of all parameters.
4275 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4276 E = Decl->param_end(); PI != E; ++PI) {
4277 QualType PType = (*PI)->getType();
4278 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004279 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004280 continue;
4281
David Chisnall50e4eba2010-12-30 14:05:53 +00004282 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004283 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004284 ParmOffset += sz;
4285 }
4286 S += charUnitsToString(ParmOffset);
4287 ParmOffset = CharUnits::Zero();
4288
4289 // Argument types.
4290 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4291 E = Decl->param_end(); PI != E; ++PI) {
4292 ParmVarDecl *PVDecl = *PI;
4293 QualType PType = PVDecl->getOriginalType();
4294 if (const ArrayType *AT =
4295 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4296 // Use array's original type only if it has known number of
4297 // elements.
4298 if (!isa<ConstantArrayType>(AT))
4299 PType = PVDecl->getType();
4300 } else if (PType->isFunctionType())
4301 PType = PVDecl->getType();
4302 getObjCEncodingForType(PType, S);
4303 S += charUnitsToString(ParmOffset);
4304 ParmOffset += getObjCEncodingTypeSize(PType);
4305 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004306
4307 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004308}
4309
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004310/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4311/// method parameter or return type. If Extended, include class names and
4312/// block object types.
4313void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4314 QualType T, std::string& S,
4315 bool Extended) const {
4316 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4317 getObjCEncodingForTypeQualifier(QT, S);
4318 // Encode parameter type.
4319 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4320 true /*OutermostType*/,
4321 false /*EncodingProperty*/,
4322 false /*StructField*/,
4323 Extended /*EncodeBlockParameters*/,
4324 Extended /*EncodeClassNames*/);
4325}
4326
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004327/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004328/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004329bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004330 std::string& S,
4331 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004332 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004333 // Encode return type.
4334 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4335 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004336 // Compute size of all parameters.
4337 // Start with computing size of a pointer in number of bytes.
4338 // FIXME: There might(should) be a better way of doing this computation!
4339 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004340 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004341 // The first two arguments (self and _cmd) are pointers; account for
4342 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004343 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004344 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004345 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004346 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004347 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004348 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004349 continue;
4350
Ken Dyck40775002010-01-11 17:06:35 +00004351 assert (sz.isPositive() &&
4352 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004353 ParmOffset += sz;
4354 }
Ken Dyck40775002010-01-11 17:06:35 +00004355 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004356 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004357 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004358
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004359 // Argument types.
4360 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004361 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004362 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004363 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004364 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004365 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004366 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4367 // Use array's original type only if it has known number of
4368 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004369 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004370 PType = PVDecl->getType();
4371 } else if (PType->isFunctionType())
4372 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004373 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4374 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004375 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004376 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004377 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004378
4379 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004380}
4381
Daniel Dunbar4932b362008-08-28 04:38:10 +00004382/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004383/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004384/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4385/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004386/// Property attributes are stored as a comma-delimited C string. The simple
4387/// attributes readonly and bycopy are encoded as single characters. The
4388/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4389/// encoded as single characters, followed by an identifier. Property types
4390/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004391/// these attributes are defined by the following enumeration:
4392/// @code
4393/// enum PropertyAttributes {
4394/// kPropertyReadOnly = 'R', // property is read-only.
4395/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4396/// kPropertyByref = '&', // property is a reference to the value last assigned
4397/// kPropertyDynamic = 'D', // property is dynamic
4398/// kPropertyGetter = 'G', // followed by getter selector name
4399/// kPropertySetter = 'S', // followed by setter selector name
4400/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004401/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004402/// kPropertyWeak = 'W' // 'weak' property
4403/// kPropertyStrong = 'P' // property GC'able
4404/// kPropertyNonAtomic = 'N' // property non-atomic
4405/// };
4406/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004407void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004408 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004409 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004410 // Collect information from the property implementation decl(s).
4411 bool Dynamic = false;
4412 ObjCPropertyImplDecl *SynthesizePID = 0;
4413
4414 // FIXME: Duplicated code due to poor abstraction.
4415 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004416 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004417 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4418 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004419 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004420 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004421 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004422 if (PID->getPropertyDecl() == PD) {
4423 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4424 Dynamic = true;
4425 } else {
4426 SynthesizePID = PID;
4427 }
4428 }
4429 }
4430 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004431 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004432 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004433 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004434 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004435 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004436 if (PID->getPropertyDecl() == PD) {
4437 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4438 Dynamic = true;
4439 } else {
4440 SynthesizePID = PID;
4441 }
4442 }
Mike Stump11289f42009-09-09 15:08:12 +00004443 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004444 }
4445 }
4446
4447 // FIXME: This is not very efficient.
4448 S = "T";
4449
4450 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004451 // GCC has some special rules regarding encoding of properties which
4452 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004453 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004454 true /* outermost type */,
4455 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004456
4457 if (PD->isReadOnly()) {
4458 S += ",R";
4459 } else {
4460 switch (PD->getSetterKind()) {
4461 case ObjCPropertyDecl::Assign: break;
4462 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004463 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004464 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004465 }
4466 }
4467
4468 // It really isn't clear at all what this means, since properties
4469 // are "dynamic by default".
4470 if (Dynamic)
4471 S += ",D";
4472
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004473 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4474 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004475
Daniel Dunbar4932b362008-08-28 04:38:10 +00004476 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4477 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004478 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004479 }
4480
4481 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4482 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004483 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004484 }
4485
4486 if (SynthesizePID) {
4487 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4488 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004489 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004490 }
4491
4492 // FIXME: OBJCGC: weak & strong
4493}
4494
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004495/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004496/// Another legacy compatibility encoding: 32-bit longs are encoded as
4497/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004498/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4499///
4500void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004501 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004502 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004503 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004504 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004505 else
Jay Foad39c79802011-01-12 09:06:06 +00004506 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004507 PointeeTy = IntTy;
4508 }
4509 }
4510}
4511
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004512void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004513 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004514 // We follow the behavior of gcc, expanding structures which are
4515 // directly pointed to, and expanding embedded structures. Note that
4516 // these rules are sufficient to prevent recursive encoding of the
4517 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004518 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004519 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004520}
4521
David Chisnallb190a2c2010-06-04 01:10:52 +00004522static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4523 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004524 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004525 case BuiltinType::Void: return 'v';
4526 case BuiltinType::Bool: return 'B';
4527 case BuiltinType::Char_U:
4528 case BuiltinType::UChar: return 'C';
4529 case BuiltinType::UShort: return 'S';
4530 case BuiltinType::UInt: return 'I';
4531 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004532 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004533 case BuiltinType::UInt128: return 'T';
4534 case BuiltinType::ULongLong: return 'Q';
4535 case BuiltinType::Char_S:
4536 case BuiltinType::SChar: return 'c';
4537 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004538 case BuiltinType::WChar_S:
4539 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004540 case BuiltinType::Int: return 'i';
4541 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004542 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004543 case BuiltinType::LongLong: return 'q';
4544 case BuiltinType::Int128: return 't';
4545 case BuiltinType::Float: return 'f';
4546 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004547 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004548 }
4549}
4550
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004551static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4552 EnumDecl *Enum = ET->getDecl();
4553
4554 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4555 if (!Enum->isFixed())
4556 return 'i';
4557
4558 // The encoding of a fixed enum type matches its fixed underlying type.
4559 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4560}
4561
Jay Foad39c79802011-01-12 09:06:06 +00004562static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004563 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004564 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004565 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004566 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4567 // The GNU runtime requires more information; bitfields are encoded as b,
4568 // then the offset (in bits) of the first element, then the type of the
4569 // bitfield, then the size in bits. For example, in this structure:
4570 //
4571 // struct
4572 // {
4573 // int integer;
4574 // int flags:2;
4575 // };
4576 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4577 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4578 // information is not especially sensible, but we're stuck with it for
4579 // compatibility with GCC, although providing it breaks anything that
4580 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004581 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004582 const RecordDecl *RD = FD->getParent();
4583 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004584 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004585 if (const EnumType *ET = T->getAs<EnumType>())
4586 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004587 else
Jay Foad39c79802011-01-12 09:06:06 +00004588 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004589 }
Richard Smithcaf33902011-10-10 18:28:20 +00004590 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004591}
4592
Daniel Dunbar07d07852009-10-18 21:17:35 +00004593// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004594void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4595 bool ExpandPointedToStructures,
4596 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004597 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004598 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004599 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004600 bool StructField,
4601 bool EncodeBlockParameters,
4602 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004603 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004604 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004605 return EncodeBitField(this, S, T, FD);
4606 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004607 return;
4608 }
Mike Stump11289f42009-09-09 15:08:12 +00004609
John McCall9dd450b2009-09-21 23:43:11 +00004610 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004611 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004612 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004613 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004614 return;
4615 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004616
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004617 // encoding for pointer or r3eference types.
4618 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004619 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004620 if (PT->isObjCSelType()) {
4621 S += ':';
4622 return;
4623 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004624 PointeeTy = PT->getPointeeType();
4625 }
4626 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4627 PointeeTy = RT->getPointeeType();
4628 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004629 bool isReadOnly = false;
4630 // For historical/compatibility reasons, the read-only qualifier of the
4631 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4632 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004633 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004634 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004635 if (OutermostType && T.isConstQualified()) {
4636 isReadOnly = true;
4637 S += 'r';
4638 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004639 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004640 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004641 while (P->getAs<PointerType>())
4642 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004643 if (P.isConstQualified()) {
4644 isReadOnly = true;
4645 S += 'r';
4646 }
4647 }
4648 if (isReadOnly) {
4649 // Another legacy compatibility encoding. Some ObjC qualifier and type
4650 // combinations need to be rearranged.
4651 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004652 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004653 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004654 }
Mike Stump11289f42009-09-09 15:08:12 +00004655
Anders Carlssond8499822007-10-29 05:01:08 +00004656 if (PointeeTy->isCharType()) {
4657 // char pointer types should be encoded as '*' unless it is a
4658 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004659 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004660 S += '*';
4661 return;
4662 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004663 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004664 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4665 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4666 S += '#';
4667 return;
4668 }
4669 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4670 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4671 S += '@';
4672 return;
4673 }
4674 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004675 }
Anders Carlssond8499822007-10-29 05:01:08 +00004676 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004677 getLegacyIntegralTypeEncoding(PointeeTy);
4678
Mike Stump11289f42009-09-09 15:08:12 +00004679 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004680 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004681 return;
4682 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004683
Chris Lattnere7cabb92009-07-13 00:10:46 +00004684 if (const ArrayType *AT =
4685 // Ignore type qualifiers etc.
4686 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004687 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004688 // Incomplete arrays are encoded as a pointer to the array element.
4689 S += '^';
4690
Mike Stump11289f42009-09-09 15:08:12 +00004691 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004692 false, ExpandStructures, FD);
4693 } else {
4694 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004695
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004696 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4697 if (getTypeSize(CAT->getElementType()) == 0)
4698 S += '0';
4699 else
4700 S += llvm::utostr(CAT->getSize().getZExtValue());
4701 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004702 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004703 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4704 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004705 S += '0';
4706 }
Mike Stump11289f42009-09-09 15:08:12 +00004707
4708 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004709 false, ExpandStructures, FD);
4710 S += ']';
4711 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004712 return;
4713 }
Mike Stump11289f42009-09-09 15:08:12 +00004714
John McCall9dd450b2009-09-21 23:43:11 +00004715 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004716 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004717 return;
4718 }
Mike Stump11289f42009-09-09 15:08:12 +00004719
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004720 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004721 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004722 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004723 // Anonymous structures print as '?'
4724 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4725 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004726 if (ClassTemplateSpecializationDecl *Spec
4727 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4728 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4729 std::string TemplateArgsStr
4730 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004731 TemplateArgs.data(),
4732 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004733 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004734
4735 S += TemplateArgsStr;
4736 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004737 } else {
4738 S += '?';
4739 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004740 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004741 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004742 if (!RDecl->isUnion()) {
4743 getObjCEncodingForStructureImpl(RDecl, S, FD);
4744 } else {
4745 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4746 FieldEnd = RDecl->field_end();
4747 Field != FieldEnd; ++Field) {
4748 if (FD) {
4749 S += '"';
4750 S += Field->getNameAsString();
4751 S += '"';
4752 }
Mike Stump11289f42009-09-09 15:08:12 +00004753
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004754 // Special case bit-fields.
4755 if (Field->isBitField()) {
4756 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004757 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004758 } else {
4759 QualType qt = Field->getType();
4760 getLegacyIntegralTypeEncoding(qt);
4761 getObjCEncodingForTypeImpl(qt, S, false, true,
4762 FD, /*OutermostType*/false,
4763 /*EncodingProperty*/false,
4764 /*StructField*/true);
4765 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004766 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004767 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004768 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004769 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004770 return;
4771 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004772
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004773 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004774 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004775 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004776 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004777 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004778 return;
4779 }
Mike Stump11289f42009-09-09 15:08:12 +00004780
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004781 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004782 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004783 if (EncodeBlockParameters) {
4784 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4785
4786 S += '<';
4787 // Block return type
4788 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4789 ExpandPointedToStructures, ExpandStructures,
4790 FD,
4791 false /* OutermostType */,
4792 EncodingProperty,
4793 false /* StructField */,
4794 EncodeBlockParameters,
4795 EncodeClassNames);
4796 // Block self
4797 S += "@?";
4798 // Block parameters
4799 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4800 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4801 E = FPT->arg_type_end(); I && (I != E); ++I) {
4802 getObjCEncodingForTypeImpl(*I, S,
4803 ExpandPointedToStructures,
4804 ExpandStructures,
4805 FD,
4806 false /* OutermostType */,
4807 EncodingProperty,
4808 false /* StructField */,
4809 EncodeBlockParameters,
4810 EncodeClassNames);
4811 }
4812 }
4813 S += '>';
4814 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004815 return;
4816 }
Mike Stump11289f42009-09-09 15:08:12 +00004817
John McCall8b07ec22010-05-15 11:32:37 +00004818 // Ignore protocol qualifiers when mangling at this level.
4819 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4820 T = OT->getBaseType();
4821
John McCall8ccfcb52009-09-24 19:53:00 +00004822 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004823 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004824 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004825 S += '{';
4826 const IdentifierInfo *II = OI->getIdentifier();
4827 S += II->getName();
4828 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004829 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004830 DeepCollectObjCIvars(OI, true, Ivars);
4831 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004832 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004833 if (Field->isBitField())
4834 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004835 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004836 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004837 }
4838 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004839 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004840 }
Mike Stump11289f42009-09-09 15:08:12 +00004841
John McCall9dd450b2009-09-21 23:43:11 +00004842 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004843 if (OPT->isObjCIdType()) {
4844 S += '@';
4845 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004846 }
Mike Stump11289f42009-09-09 15:08:12 +00004847
Steve Narofff0c86112009-10-28 22:03:49 +00004848 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4849 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4850 // Since this is a binary compatibility issue, need to consult with runtime
4851 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004852 S += '#';
4853 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004854 }
Mike Stump11289f42009-09-09 15:08:12 +00004855
Chris Lattnere7cabb92009-07-13 00:10:46 +00004856 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004857 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004858 ExpandPointedToStructures,
4859 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004860 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004861 // Note that we do extended encoding of protocol qualifer list
4862 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004863 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004864 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4865 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004866 S += '<';
4867 S += (*I)->getNameAsString();
4868 S += '>';
4869 }
4870 S += '"';
4871 }
4872 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004873 }
Mike Stump11289f42009-09-09 15:08:12 +00004874
Chris Lattnere7cabb92009-07-13 00:10:46 +00004875 QualType PointeeTy = OPT->getPointeeType();
4876 if (!EncodingProperty &&
4877 isa<TypedefType>(PointeeTy.getTypePtr())) {
4878 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004879 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004880 // {...};
4881 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004882 getObjCEncodingForTypeImpl(PointeeTy, S,
4883 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004884 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004885 return;
4886 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004887
4888 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004889 if (OPT->getInterfaceDecl() &&
4890 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004891 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004892 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004893 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4894 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004895 S += '<';
4896 S += (*I)->getNameAsString();
4897 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004898 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004899 S += '"';
4900 }
4901 return;
4902 }
Mike Stump11289f42009-09-09 15:08:12 +00004903
John McCalla9e6e8d2010-05-17 23:56:34 +00004904 // gcc just blithely ignores member pointers.
4905 // TODO: maybe there should be a mangling for these
4906 if (T->getAs<MemberPointerType>())
4907 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004908
4909 if (T->isVectorType()) {
4910 // This matches gcc's encoding, even though technically it is
4911 // insufficient.
4912 // FIXME. We should do a better job than gcc.
4913 return;
4914 }
4915
David Blaikie83d382b2011-09-23 05:06:16 +00004916 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004917}
4918
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004919void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4920 std::string &S,
4921 const FieldDecl *FD,
4922 bool includeVBases) const {
4923 assert(RDecl && "Expected non-null RecordDecl");
4924 assert(!RDecl->isUnion() && "Should not be called for unions");
4925 if (!RDecl->getDefinition())
4926 return;
4927
4928 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4929 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4930 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4931
4932 if (CXXRec) {
4933 for (CXXRecordDecl::base_class_iterator
4934 BI = CXXRec->bases_begin(),
4935 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4936 if (!BI->isVirtual()) {
4937 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004938 if (base->isEmpty())
4939 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00004940 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004941 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4942 std::make_pair(offs, base));
4943 }
4944 }
4945 }
4946
4947 unsigned i = 0;
4948 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4949 FieldEnd = RDecl->field_end();
4950 Field != FieldEnd; ++Field, ++i) {
4951 uint64_t offs = layout.getFieldOffset(i);
4952 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00004953 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004954 }
4955
4956 if (CXXRec && includeVBases) {
4957 for (CXXRecordDecl::base_class_iterator
4958 BI = CXXRec->vbases_begin(),
4959 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4960 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004961 if (base->isEmpty())
4962 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00004963 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004964 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4965 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4966 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004967 }
4968 }
4969
4970 CharUnits size;
4971 if (CXXRec) {
4972 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4973 } else {
4974 size = layout.getSize();
4975 }
4976
4977 uint64_t CurOffs = 0;
4978 std::multimap<uint64_t, NamedDecl *>::iterator
4979 CurLayObj = FieldOrBaseOffsets.begin();
4980
Douglas Gregorf5d6c742012-04-27 22:30:01 +00004981 if (CXXRec && CXXRec->isDynamicClass() &&
4982 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004983 if (FD) {
4984 S += "\"_vptr$";
4985 std::string recname = CXXRec->getNameAsString();
4986 if (recname.empty()) recname = "?";
4987 S += recname;
4988 S += '"';
4989 }
4990 S += "^^?";
4991 CurOffs += getTypeSize(VoidPtrTy);
4992 }
4993
4994 if (!RDecl->hasFlexibleArrayMember()) {
4995 // Mark the end of the structure.
4996 uint64_t offs = toBits(size);
4997 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4998 std::make_pair(offs, (NamedDecl*)0));
4999 }
5000
5001 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5002 assert(CurOffs <= CurLayObj->first);
5003
5004 if (CurOffs < CurLayObj->first) {
5005 uint64_t padding = CurLayObj->first - CurOffs;
5006 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5007 // packing/alignment of members is different that normal, in which case
5008 // the encoding will be out-of-sync with the real layout.
5009 // If the runtime switches to just consider the size of types without
5010 // taking into account alignment, we could make padding explicit in the
5011 // encoding (e.g. using arrays of chars). The encoding strings would be
5012 // longer then though.
5013 CurOffs += padding;
5014 }
5015
5016 NamedDecl *dcl = CurLayObj->second;
5017 if (dcl == 0)
5018 break; // reached end of structure.
5019
5020 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5021 // We expand the bases without their virtual bases since those are going
5022 // in the initial structure. Note that this differs from gcc which
5023 // expands virtual bases each time one is encountered in the hierarchy,
5024 // making the encoding type bigger than it really is.
5025 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005026 assert(!base->isEmpty());
5027 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005028 } else {
5029 FieldDecl *field = cast<FieldDecl>(dcl);
5030 if (FD) {
5031 S += '"';
5032 S += field->getNameAsString();
5033 S += '"';
5034 }
5035
5036 if (field->isBitField()) {
5037 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005038 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005039 } else {
5040 QualType qt = field->getType();
5041 getLegacyIntegralTypeEncoding(qt);
5042 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5043 /*OutermostType*/false,
5044 /*EncodingProperty*/false,
5045 /*StructField*/true);
5046 CurOffs += getTypeSize(field->getType());
5047 }
5048 }
5049 }
5050}
5051
Mike Stump11289f42009-09-09 15:08:12 +00005052void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005053 std::string& S) const {
5054 if (QT & Decl::OBJC_TQ_In)
5055 S += 'n';
5056 if (QT & Decl::OBJC_TQ_Inout)
5057 S += 'N';
5058 if (QT & Decl::OBJC_TQ_Out)
5059 S += 'o';
5060 if (QT & Decl::OBJC_TQ_Bycopy)
5061 S += 'O';
5062 if (QT & Decl::OBJC_TQ_Byref)
5063 S += 'R';
5064 if (QT & Decl::OBJC_TQ_Oneway)
5065 S += 'V';
5066}
5067
Douglas Gregor3ea72692011-08-12 05:46:01 +00005068TypedefDecl *ASTContext::getObjCIdDecl() const {
5069 if (!ObjCIdDecl) {
5070 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5071 T = getObjCObjectPointerType(T);
5072 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5073 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5074 getTranslationUnitDecl(),
5075 SourceLocation(), SourceLocation(),
5076 &Idents.get("id"), IdInfo);
5077 }
5078
5079 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005080}
5081
Douglas Gregor52e02802011-08-12 06:17:30 +00005082TypedefDecl *ASTContext::getObjCSelDecl() const {
5083 if (!ObjCSelDecl) {
5084 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5085 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5086 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5087 getTranslationUnitDecl(),
5088 SourceLocation(), SourceLocation(),
5089 &Idents.get("SEL"), SelInfo);
5090 }
5091 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005092}
5093
Douglas Gregor0a586182011-08-12 05:59:41 +00005094TypedefDecl *ASTContext::getObjCClassDecl() const {
5095 if (!ObjCClassDecl) {
5096 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5097 T = getObjCObjectPointerType(T);
5098 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5099 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5100 getTranslationUnitDecl(),
5101 SourceLocation(), SourceLocation(),
5102 &Idents.get("Class"), ClassInfo);
5103 }
5104
5105 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005106}
5107
Douglas Gregord53ae832012-01-17 18:09:05 +00005108ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5109 if (!ObjCProtocolClassDecl) {
5110 ObjCProtocolClassDecl
5111 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5112 SourceLocation(),
5113 &Idents.get("Protocol"),
5114 /*PrevDecl=*/0,
5115 SourceLocation(), true);
5116 }
5117
5118 return ObjCProtocolClassDecl;
5119}
5120
Meador Inge5d3fb222012-06-16 03:34:49 +00005121//===----------------------------------------------------------------------===//
5122// __builtin_va_list Construction Functions
5123//===----------------------------------------------------------------------===//
5124
5125static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5126 // typedef char* __builtin_va_list;
5127 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5128 TypeSourceInfo *TInfo
5129 = Context->getTrivialTypeSourceInfo(CharPtrType);
5130
5131 TypedefDecl *VaListTypeDecl
5132 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5133 Context->getTranslationUnitDecl(),
5134 SourceLocation(), SourceLocation(),
5135 &Context->Idents.get("__builtin_va_list"),
5136 TInfo);
5137 return VaListTypeDecl;
5138}
5139
5140static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5141 // typedef void* __builtin_va_list;
5142 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5143 TypeSourceInfo *TInfo
5144 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5145
5146 TypedefDecl *VaListTypeDecl
5147 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5148 Context->getTranslationUnitDecl(),
5149 SourceLocation(), SourceLocation(),
5150 &Context->Idents.get("__builtin_va_list"),
5151 TInfo);
5152 return VaListTypeDecl;
5153}
5154
5155static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5156 // typedef struct __va_list_tag {
5157 RecordDecl *VaListTagDecl;
5158
5159 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5160 Context->getTranslationUnitDecl(),
5161 &Context->Idents.get("__va_list_tag"));
5162 VaListTagDecl->startDefinition();
5163
5164 const size_t NumFields = 5;
5165 QualType FieldTypes[NumFields];
5166 const char *FieldNames[NumFields];
5167
5168 // unsigned char gpr;
5169 FieldTypes[0] = Context->UnsignedCharTy;
5170 FieldNames[0] = "gpr";
5171
5172 // unsigned char fpr;
5173 FieldTypes[1] = Context->UnsignedCharTy;
5174 FieldNames[1] = "fpr";
5175
5176 // unsigned short reserved;
5177 FieldTypes[2] = Context->UnsignedShortTy;
5178 FieldNames[2] = "reserved";
5179
5180 // void* overflow_arg_area;
5181 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5182 FieldNames[3] = "overflow_arg_area";
5183
5184 // void* reg_save_area;
5185 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5186 FieldNames[4] = "reg_save_area";
5187
5188 // Create fields
5189 for (unsigned i = 0; i < NumFields; ++i) {
5190 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5191 SourceLocation(),
5192 SourceLocation(),
5193 &Context->Idents.get(FieldNames[i]),
5194 FieldTypes[i], /*TInfo=*/0,
5195 /*BitWidth=*/0,
5196 /*Mutable=*/false,
5197 ICIS_NoInit);
5198 Field->setAccess(AS_public);
5199 VaListTagDecl->addDecl(Field);
5200 }
5201 VaListTagDecl->completeDefinition();
5202 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005203 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005204
5205 // } __va_list_tag;
5206 TypedefDecl *VaListTagTypedefDecl
5207 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5208 Context->getTranslationUnitDecl(),
5209 SourceLocation(), SourceLocation(),
5210 &Context->Idents.get("__va_list_tag"),
5211 Context->getTrivialTypeSourceInfo(VaListTagType));
5212 QualType VaListTagTypedefType =
5213 Context->getTypedefType(VaListTagTypedefDecl);
5214
5215 // typedef __va_list_tag __builtin_va_list[1];
5216 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5217 QualType VaListTagArrayType
5218 = Context->getConstantArrayType(VaListTagTypedefType,
5219 Size, ArrayType::Normal, 0);
5220 TypeSourceInfo *TInfo
5221 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5222 TypedefDecl *VaListTypedefDecl
5223 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5224 Context->getTranslationUnitDecl(),
5225 SourceLocation(), SourceLocation(),
5226 &Context->Idents.get("__builtin_va_list"),
5227 TInfo);
5228
5229 return VaListTypedefDecl;
5230}
5231
5232static TypedefDecl *
5233CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5234 // typedef struct __va_list_tag {
5235 RecordDecl *VaListTagDecl;
5236 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5237 Context->getTranslationUnitDecl(),
5238 &Context->Idents.get("__va_list_tag"));
5239 VaListTagDecl->startDefinition();
5240
5241 const size_t NumFields = 4;
5242 QualType FieldTypes[NumFields];
5243 const char *FieldNames[NumFields];
5244
5245 // unsigned gp_offset;
5246 FieldTypes[0] = Context->UnsignedIntTy;
5247 FieldNames[0] = "gp_offset";
5248
5249 // unsigned fp_offset;
5250 FieldTypes[1] = Context->UnsignedIntTy;
5251 FieldNames[1] = "fp_offset";
5252
5253 // void* overflow_arg_area;
5254 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5255 FieldNames[2] = "overflow_arg_area";
5256
5257 // void* reg_save_area;
5258 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5259 FieldNames[3] = "reg_save_area";
5260
5261 // Create fields
5262 for (unsigned i = 0; i < NumFields; ++i) {
5263 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5264 VaListTagDecl,
5265 SourceLocation(),
5266 SourceLocation(),
5267 &Context->Idents.get(FieldNames[i]),
5268 FieldTypes[i], /*TInfo=*/0,
5269 /*BitWidth=*/0,
5270 /*Mutable=*/false,
5271 ICIS_NoInit);
5272 Field->setAccess(AS_public);
5273 VaListTagDecl->addDecl(Field);
5274 }
5275 VaListTagDecl->completeDefinition();
5276 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005277 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005278
5279 // } __va_list_tag;
5280 TypedefDecl *VaListTagTypedefDecl
5281 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5282 Context->getTranslationUnitDecl(),
5283 SourceLocation(), SourceLocation(),
5284 &Context->Idents.get("__va_list_tag"),
5285 Context->getTrivialTypeSourceInfo(VaListTagType));
5286 QualType VaListTagTypedefType =
5287 Context->getTypedefType(VaListTagTypedefDecl);
5288
5289 // typedef __va_list_tag __builtin_va_list[1];
5290 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5291 QualType VaListTagArrayType
5292 = Context->getConstantArrayType(VaListTagTypedefType,
5293 Size, ArrayType::Normal,0);
5294 TypeSourceInfo *TInfo
5295 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5296 TypedefDecl *VaListTypedefDecl
5297 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5298 Context->getTranslationUnitDecl(),
5299 SourceLocation(), SourceLocation(),
5300 &Context->Idents.get("__builtin_va_list"),
5301 TInfo);
5302
5303 return VaListTypedefDecl;
5304}
5305
5306static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5307 // typedef int __builtin_va_list[4];
5308 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5309 QualType IntArrayType
5310 = Context->getConstantArrayType(Context->IntTy,
5311 Size, ArrayType::Normal, 0);
5312 TypedefDecl *VaListTypedefDecl
5313 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5314 Context->getTranslationUnitDecl(),
5315 SourceLocation(), SourceLocation(),
5316 &Context->Idents.get("__builtin_va_list"),
5317 Context->getTrivialTypeSourceInfo(IntArrayType));
5318
5319 return VaListTypedefDecl;
5320}
5321
5322static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5323 TargetInfo::BuiltinVaListKind Kind) {
5324 switch (Kind) {
5325 case TargetInfo::CharPtrBuiltinVaList:
5326 return CreateCharPtrBuiltinVaListDecl(Context);
5327 case TargetInfo::VoidPtrBuiltinVaList:
5328 return CreateVoidPtrBuiltinVaListDecl(Context);
5329 case TargetInfo::PowerABIBuiltinVaList:
5330 return CreatePowerABIBuiltinVaListDecl(Context);
5331 case TargetInfo::X86_64ABIBuiltinVaList:
5332 return CreateX86_64ABIBuiltinVaListDecl(Context);
5333 case TargetInfo::PNaClABIBuiltinVaList:
5334 return CreatePNaClABIBuiltinVaListDecl(Context);
5335 }
5336
5337 llvm_unreachable("Unhandled __builtin_va_list type kind");
5338}
5339
5340TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5341 if (!BuiltinVaListDecl)
5342 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5343
5344 return BuiltinVaListDecl;
5345}
5346
Meador Ingecfb60902012-07-01 15:57:25 +00005347QualType ASTContext::getVaListTagType() const {
5348 // Force the creation of VaListTagTy by building the __builtin_va_list
5349 // declaration.
5350 if (VaListTagTy.isNull())
5351 (void) getBuiltinVaListDecl();
5352
5353 return VaListTagTy;
5354}
5355
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005356void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005357 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005358 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005359
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005360 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005361}
5362
John McCalld28ae272009-12-02 08:04:21 +00005363/// \brief Retrieve the template name that corresponds to a non-empty
5364/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005365TemplateName
5366ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5367 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005368 unsigned size = End - Begin;
5369 assert(size > 1 && "set is not overloaded!");
5370
5371 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5372 size * sizeof(FunctionTemplateDecl*));
5373 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5374
5375 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005376 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005377 NamedDecl *D = *I;
5378 assert(isa<FunctionTemplateDecl>(D) ||
5379 (isa<UsingShadowDecl>(D) &&
5380 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5381 *Storage++ = D;
5382 }
5383
5384 return TemplateName(OT);
5385}
5386
Douglas Gregordc572a32009-03-30 22:58:21 +00005387/// \brief Retrieve the template name that represents a qualified
5388/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005389TemplateName
5390ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5391 bool TemplateKeyword,
5392 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005393 assert(NNS && "Missing nested-name-specifier in qualified template name");
5394
Douglas Gregorc42075a2010-02-04 18:10:26 +00005395 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005396 llvm::FoldingSetNodeID ID;
5397 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5398
5399 void *InsertPos = 0;
5400 QualifiedTemplateName *QTN =
5401 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5402 if (!QTN) {
5403 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5404 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5405 }
5406
5407 return TemplateName(QTN);
5408}
5409
5410/// \brief Retrieve the template name that represents a dependent
5411/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005412TemplateName
5413ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5414 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005415 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005416 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005417
5418 llvm::FoldingSetNodeID ID;
5419 DependentTemplateName::Profile(ID, NNS, Name);
5420
5421 void *InsertPos = 0;
5422 DependentTemplateName *QTN =
5423 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5424
5425 if (QTN)
5426 return TemplateName(QTN);
5427
5428 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5429 if (CanonNNS == NNS) {
5430 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5431 } else {
5432 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5433 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005434 DependentTemplateName *CheckQTN =
5435 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5436 assert(!CheckQTN && "Dependent type name canonicalization broken");
5437 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005438 }
5439
5440 DependentTemplateNames.InsertNode(QTN, InsertPos);
5441 return TemplateName(QTN);
5442}
5443
Douglas Gregor71395fa2009-11-04 00:56:37 +00005444/// \brief Retrieve the template name that represents a dependent
5445/// template name such as \c MetaFun::template operator+.
5446TemplateName
5447ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005448 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005449 assert((!NNS || NNS->isDependent()) &&
5450 "Nested name specifier must be dependent");
5451
5452 llvm::FoldingSetNodeID ID;
5453 DependentTemplateName::Profile(ID, NNS, Operator);
5454
5455 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005456 DependentTemplateName *QTN
5457 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005458
5459 if (QTN)
5460 return TemplateName(QTN);
5461
5462 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5463 if (CanonNNS == NNS) {
5464 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5465 } else {
5466 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5467 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005468
5469 DependentTemplateName *CheckQTN
5470 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5471 assert(!CheckQTN && "Dependent template name canonicalization broken");
5472 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005473 }
5474
5475 DependentTemplateNames.InsertNode(QTN, InsertPos);
5476 return TemplateName(QTN);
5477}
5478
Douglas Gregor5590be02011-01-15 06:45:20 +00005479TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005480ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5481 TemplateName replacement) const {
5482 llvm::FoldingSetNodeID ID;
5483 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5484
5485 void *insertPos = 0;
5486 SubstTemplateTemplateParmStorage *subst
5487 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5488
5489 if (!subst) {
5490 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5491 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5492 }
5493
5494 return TemplateName(subst);
5495}
5496
5497TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005498ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5499 const TemplateArgument &ArgPack) const {
5500 ASTContext &Self = const_cast<ASTContext &>(*this);
5501 llvm::FoldingSetNodeID ID;
5502 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5503
5504 void *InsertPos = 0;
5505 SubstTemplateTemplateParmPackStorage *Subst
5506 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5507
5508 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005509 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005510 ArgPack.pack_size(),
5511 ArgPack.pack_begin());
5512 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5513 }
5514
5515 return TemplateName(Subst);
5516}
5517
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005518/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005519/// TargetInfo, produce the corresponding type. The unsigned @p Type
5520/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005521CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005522 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005523 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005524 case TargetInfo::SignedShort: return ShortTy;
5525 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5526 case TargetInfo::SignedInt: return IntTy;
5527 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5528 case TargetInfo::SignedLong: return LongTy;
5529 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5530 case TargetInfo::SignedLongLong: return LongLongTy;
5531 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5532 }
5533
David Blaikie83d382b2011-09-23 05:06:16 +00005534 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005535}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005536
5537//===----------------------------------------------------------------------===//
5538// Type Predicates.
5539//===----------------------------------------------------------------------===//
5540
Fariborz Jahanian96207692009-02-18 21:49:28 +00005541/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5542/// garbage collection attribute.
5543///
John McCall553d45a2011-01-12 00:34:59 +00005544Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005545 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005546 return Qualifiers::GCNone;
5547
David Blaikiebbafb8a2012-03-11 07:00:24 +00005548 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005549 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5550
5551 // Default behaviour under objective-C's gc is for ObjC pointers
5552 // (or pointers to them) be treated as though they were declared
5553 // as __strong.
5554 if (GCAttrs == Qualifiers::GCNone) {
5555 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5556 return Qualifiers::Strong;
5557 else if (Ty->isPointerType())
5558 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5559 } else {
5560 // It's not valid to set GC attributes on anything that isn't a
5561 // pointer.
5562#ifndef NDEBUG
5563 QualType CT = Ty->getCanonicalTypeInternal();
5564 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5565 CT = AT->getElementType();
5566 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5567#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005568 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005569 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005570}
5571
Chris Lattner49af6a42008-04-07 06:51:04 +00005572//===----------------------------------------------------------------------===//
5573// Type Compatibility Testing
5574//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005575
Mike Stump11289f42009-09-09 15:08:12 +00005576/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005577/// compatible.
5578static bool areCompatVectorTypes(const VectorType *LHS,
5579 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005580 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005581 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005582 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005583}
5584
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005585bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5586 QualType SecondVec) {
5587 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5588 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5589
5590 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5591 return true;
5592
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005593 // Treat Neon vector types and most AltiVec vector types as if they are the
5594 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005595 const VectorType *First = FirstVec->getAs<VectorType>();
5596 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005597 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005598 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005599 First->getVectorKind() != VectorType::AltiVecPixel &&
5600 First->getVectorKind() != VectorType::AltiVecBool &&
5601 Second->getVectorKind() != VectorType::AltiVecPixel &&
5602 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005603 return true;
5604
5605 return false;
5606}
5607
Steve Naroff8e6aee52009-07-23 01:01:38 +00005608//===----------------------------------------------------------------------===//
5609// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5610//===----------------------------------------------------------------------===//
5611
5612/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5613/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005614bool
5615ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5616 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005617 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005618 return true;
5619 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5620 E = rProto->protocol_end(); PI != E; ++PI)
5621 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5622 return true;
5623 return false;
5624}
5625
Steve Naroff8e6aee52009-07-23 01:01:38 +00005626/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5627/// return true if lhs's protocols conform to rhs's protocol; false
5628/// otherwise.
5629bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5630 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5631 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5632 return false;
5633}
5634
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005635/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5636/// Class<p1, ...>.
5637bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5638 QualType rhs) {
5639 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5640 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5641 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5642
5643 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5644 E = lhsQID->qual_end(); I != E; ++I) {
5645 bool match = false;
5646 ObjCProtocolDecl *lhsProto = *I;
5647 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5648 E = rhsOPT->qual_end(); J != E; ++J) {
5649 ObjCProtocolDecl *rhsProto = *J;
5650 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5651 match = true;
5652 break;
5653 }
5654 }
5655 if (!match)
5656 return false;
5657 }
5658 return true;
5659}
5660
Steve Naroff8e6aee52009-07-23 01:01:38 +00005661/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5662/// ObjCQualifiedIDType.
5663bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5664 bool compare) {
5665 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005666 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005667 lhs->isObjCIdType() || lhs->isObjCClassType())
5668 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005669 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005670 rhs->isObjCIdType() || rhs->isObjCClassType())
5671 return true;
5672
5673 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005674 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005675
Steve Naroff8e6aee52009-07-23 01:01:38 +00005676 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005677
Steve Naroff8e6aee52009-07-23 01:01:38 +00005678 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005679 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005680 // make sure we check the class hierarchy.
5681 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5682 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5683 E = lhsQID->qual_end(); I != E; ++I) {
5684 // when comparing an id<P> on lhs with a static type on rhs,
5685 // see if static class implements all of id's protocols, directly or
5686 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005687 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005688 return false;
5689 }
5690 }
5691 // If there are no qualifiers and no interface, we have an 'id'.
5692 return true;
5693 }
Mike Stump11289f42009-09-09 15:08:12 +00005694 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005695 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5696 E = lhsQID->qual_end(); I != E; ++I) {
5697 ObjCProtocolDecl *lhsProto = *I;
5698 bool match = false;
5699
5700 // when comparing an id<P> on lhs with a static type on rhs,
5701 // see if static class implements all of id's protocols, directly or
5702 // through its super class and categories.
5703 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5704 E = rhsOPT->qual_end(); J != E; ++J) {
5705 ObjCProtocolDecl *rhsProto = *J;
5706 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5707 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5708 match = true;
5709 break;
5710 }
5711 }
Mike Stump11289f42009-09-09 15:08:12 +00005712 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005713 // make sure we check the class hierarchy.
5714 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5715 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5716 E = lhsQID->qual_end(); I != E; ++I) {
5717 // when comparing an id<P> on lhs with a static type on rhs,
5718 // see if static class implements all of id's protocols, directly or
5719 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005720 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005721 match = true;
5722 break;
5723 }
5724 }
5725 }
5726 if (!match)
5727 return false;
5728 }
Mike Stump11289f42009-09-09 15:08:12 +00005729
Steve Naroff8e6aee52009-07-23 01:01:38 +00005730 return true;
5731 }
Mike Stump11289f42009-09-09 15:08:12 +00005732
Steve Naroff8e6aee52009-07-23 01:01:38 +00005733 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5734 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5735
Mike Stump11289f42009-09-09 15:08:12 +00005736 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005737 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005738 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005739 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5740 E = lhsOPT->qual_end(); I != E; ++I) {
5741 ObjCProtocolDecl *lhsProto = *I;
5742 bool match = false;
5743
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005744 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005745 // see if static class implements all of id's protocols, directly or
5746 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005747 // First, lhs protocols in the qualifier list must be found, direct
5748 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005749 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5750 E = rhsQID->qual_end(); J != E; ++J) {
5751 ObjCProtocolDecl *rhsProto = *J;
5752 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5753 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5754 match = true;
5755 break;
5756 }
5757 }
5758 if (!match)
5759 return false;
5760 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005761
5762 // Static class's protocols, or its super class or category protocols
5763 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5764 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5765 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5766 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5767 // This is rather dubious but matches gcc's behavior. If lhs has
5768 // no type qualifier and its class has no static protocol(s)
5769 // assume that it is mismatch.
5770 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5771 return false;
5772 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5773 LHSInheritedProtocols.begin(),
5774 E = LHSInheritedProtocols.end(); I != E; ++I) {
5775 bool match = false;
5776 ObjCProtocolDecl *lhsProto = (*I);
5777 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5778 E = rhsQID->qual_end(); J != E; ++J) {
5779 ObjCProtocolDecl *rhsProto = *J;
5780 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5781 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5782 match = true;
5783 break;
5784 }
5785 }
5786 if (!match)
5787 return false;
5788 }
5789 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005790 return true;
5791 }
5792 return false;
5793}
5794
Eli Friedman47f77112008-08-22 00:56:42 +00005795/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005796/// compatible for assignment from RHS to LHS. This handles validation of any
5797/// protocol qualifiers on the LHS or RHS.
5798///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005799bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5800 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005801 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5802 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5803
Steve Naroff1329fa02009-07-15 18:40:39 +00005804 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005805 if (LHS->isObjCUnqualifiedIdOrClass() ||
5806 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005807 return true;
5808
John McCall8b07ec22010-05-15 11:32:37 +00005809 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005810 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5811 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005812 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005813
5814 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5815 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5816 QualType(RHSOPT,0));
5817
John McCall8b07ec22010-05-15 11:32:37 +00005818 // If we have 2 user-defined types, fall into that path.
5819 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005820 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005821
Steve Naroff8e6aee52009-07-23 01:01:38 +00005822 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005823}
5824
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005825/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005826/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005827/// arguments in block literals. When passed as arguments, passing 'A*' where
5828/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5829/// not OK. For the return type, the opposite is not OK.
5830bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5831 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005832 const ObjCObjectPointerType *RHSOPT,
5833 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005834 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005835 return true;
5836
5837 if (LHSOPT->isObjCBuiltinType()) {
5838 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5839 }
5840
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005841 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005842 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5843 QualType(RHSOPT,0),
5844 false);
5845
5846 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5847 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5848 if (LHS && RHS) { // We have 2 user-defined types.
5849 if (LHS != RHS) {
5850 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005851 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005852 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005853 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005854 }
5855 else
5856 return true;
5857 }
5858 return false;
5859}
5860
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005861/// getIntersectionOfProtocols - This routine finds the intersection of set
5862/// of protocols inherited from two distinct objective-c pointer objects.
5863/// It is used to build composite qualifier list of the composite type of
5864/// the conditional expression involving two objective-c pointer objects.
5865static
5866void getIntersectionOfProtocols(ASTContext &Context,
5867 const ObjCObjectPointerType *LHSOPT,
5868 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005869 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005870
John McCall8b07ec22010-05-15 11:32:37 +00005871 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5872 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5873 assert(LHS->getInterface() && "LHS must have an interface base");
5874 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005875
5876 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5877 unsigned LHSNumProtocols = LHS->getNumProtocols();
5878 if (LHSNumProtocols > 0)
5879 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5880 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005881 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005882 Context.CollectInheritedProtocols(LHS->getInterface(),
5883 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005884 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5885 LHSInheritedProtocols.end());
5886 }
5887
5888 unsigned RHSNumProtocols = RHS->getNumProtocols();
5889 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005890 ObjCProtocolDecl **RHSProtocols =
5891 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005892 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5893 if (InheritedProtocolSet.count(RHSProtocols[i]))
5894 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005895 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005896 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005897 Context.CollectInheritedProtocols(RHS->getInterface(),
5898 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005899 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5900 RHSInheritedProtocols.begin(),
5901 E = RHSInheritedProtocols.end(); I != E; ++I)
5902 if (InheritedProtocolSet.count((*I)))
5903 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005904 }
5905}
5906
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005907/// areCommonBaseCompatible - Returns common base class of the two classes if
5908/// one found. Note that this is O'2 algorithm. But it will be called as the
5909/// last type comparison in a ?-exp of ObjC pointer types before a
5910/// warning is issued. So, its invokation is extremely rare.
5911QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005912 const ObjCObjectPointerType *Lptr,
5913 const ObjCObjectPointerType *Rptr) {
5914 const ObjCObjectType *LHS = Lptr->getObjectType();
5915 const ObjCObjectType *RHS = Rptr->getObjectType();
5916 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5917 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005918 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005919 return QualType();
5920
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005921 do {
John McCall8b07ec22010-05-15 11:32:37 +00005922 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005923 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005924 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005925 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5926
5927 QualType Result = QualType(LHS, 0);
5928 if (!Protocols.empty())
5929 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5930 Result = getObjCObjectPointerType(Result);
5931 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005932 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005933 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005934
5935 return QualType();
5936}
5937
John McCall8b07ec22010-05-15 11:32:37 +00005938bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5939 const ObjCObjectType *RHS) {
5940 assert(LHS->getInterface() && "LHS is not an interface type");
5941 assert(RHS->getInterface() && "RHS is not an interface type");
5942
Chris Lattner49af6a42008-04-07 06:51:04 +00005943 // Verify that the base decls are compatible: the RHS must be a subclass of
5944 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005945 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005946 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005947
Chris Lattner49af6a42008-04-07 06:51:04 +00005948 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5949 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005950 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005951 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005952
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005953 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5954 // more detailed analysis is required.
5955 if (RHS->getNumProtocols() == 0) {
5956 // OK, if LHS is a superclass of RHS *and*
5957 // this superclass is assignment compatible with LHS.
5958 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005959 bool IsSuperClass =
5960 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5961 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005962 // OK if conversion of LHS to SuperClass results in narrowing of types
5963 // ; i.e., SuperClass may implement at least one of the protocols
5964 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5965 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5966 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005967 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005968 // If super class has no protocols, it is not a match.
5969 if (SuperClassInheritedProtocols.empty())
5970 return false;
5971
5972 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5973 LHSPE = LHS->qual_end();
5974 LHSPI != LHSPE; LHSPI++) {
5975 bool SuperImplementsProtocol = false;
5976 ObjCProtocolDecl *LHSProto = (*LHSPI);
5977
5978 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5979 SuperClassInheritedProtocols.begin(),
5980 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5981 ObjCProtocolDecl *SuperClassProto = (*I);
5982 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5983 SuperImplementsProtocol = true;
5984 break;
5985 }
5986 }
5987 if (!SuperImplementsProtocol)
5988 return false;
5989 }
5990 return true;
5991 }
5992 return false;
5993 }
Mike Stump11289f42009-09-09 15:08:12 +00005994
John McCall8b07ec22010-05-15 11:32:37 +00005995 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5996 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005997 LHSPI != LHSPE; LHSPI++) {
5998 bool RHSImplementsProtocol = false;
5999
6000 // If the RHS doesn't implement the protocol on the left, the types
6001 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006002 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6003 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006004 RHSPI != RHSPE; RHSPI++) {
6005 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006006 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006007 break;
6008 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006009 }
6010 // FIXME: For better diagnostics, consider passing back the protocol name.
6011 if (!RHSImplementsProtocol)
6012 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006013 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006014 // The RHS implements all protocols listed on the LHS.
6015 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006016}
6017
Steve Naroffb7605152009-02-12 17:52:19 +00006018bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6019 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006020 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6021 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006022
Steve Naroff7cae42b2009-07-10 23:34:53 +00006023 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006024 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006025
6026 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6027 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006028}
6029
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006030bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6031 return canAssignObjCInterfaces(
6032 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6033 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6034}
6035
Mike Stump11289f42009-09-09 15:08:12 +00006036/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006037/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006038/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006039/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006040bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6041 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006042 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006043 return hasSameType(LHS, RHS);
6044
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006045 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006046}
6047
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006048bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006049 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006050}
6051
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006052bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6053 return !mergeTypes(LHS, RHS, true).isNull();
6054}
6055
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006056/// mergeTransparentUnionType - if T is a transparent union type and a member
6057/// of T is compatible with SubType, return the merged type, else return
6058/// QualType()
6059QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6060 bool OfBlockPointer,
6061 bool Unqualified) {
6062 if (const RecordType *UT = T->getAsUnionType()) {
6063 RecordDecl *UD = UT->getDecl();
6064 if (UD->hasAttr<TransparentUnionAttr>()) {
6065 for (RecordDecl::field_iterator it = UD->field_begin(),
6066 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006067 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006068 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6069 if (!MT.isNull())
6070 return MT;
6071 }
6072 }
6073 }
6074
6075 return QualType();
6076}
6077
6078/// mergeFunctionArgumentTypes - merge two types which appear as function
6079/// argument types
6080QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6081 bool OfBlockPointer,
6082 bool Unqualified) {
6083 // GNU extension: two types are compatible if they appear as a function
6084 // argument, one of the types is a transparent union type and the other
6085 // type is compatible with a union member
6086 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6087 Unqualified);
6088 if (!lmerge.isNull())
6089 return lmerge;
6090
6091 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6092 Unqualified);
6093 if (!rmerge.isNull())
6094 return rmerge;
6095
6096 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6097}
6098
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006099QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006100 bool OfBlockPointer,
6101 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006102 const FunctionType *lbase = lhs->getAs<FunctionType>();
6103 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006104 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6105 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006106 bool allLTypes = true;
6107 bool allRTypes = true;
6108
6109 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006110 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006111 if (OfBlockPointer) {
6112 QualType RHS = rbase->getResultType();
6113 QualType LHS = lbase->getResultType();
6114 bool UnqualifiedResult = Unqualified;
6115 if (!UnqualifiedResult)
6116 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006117 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006118 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006119 else
John McCall8c6b56f2010-12-15 01:06:38 +00006120 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6121 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006122 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006123
6124 if (Unqualified)
6125 retType = retType.getUnqualifiedType();
6126
6127 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6128 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6129 if (Unqualified) {
6130 LRetType = LRetType.getUnqualifiedType();
6131 RRetType = RRetType.getUnqualifiedType();
6132 }
6133
6134 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006135 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006136 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006137 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006138
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006139 // FIXME: double check this
6140 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6141 // rbase->getRegParmAttr() != 0 &&
6142 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006143 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6144 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006145
Douglas Gregor8c940862010-01-18 17:14:39 +00006146 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006147 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006148 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006149
John McCall8c6b56f2010-12-15 01:06:38 +00006150 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006151 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6152 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006153 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6154 return QualType();
6155
John McCall31168b02011-06-15 23:02:42 +00006156 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6157 return QualType();
6158
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006159 // functypes which return are preferred over those that do not.
6160 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6161 allLTypes = false;
6162 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6163 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006164 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6165 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006166
John McCall31168b02011-06-15 23:02:42 +00006167 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006168
Eli Friedman47f77112008-08-22 00:56:42 +00006169 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006170 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6171 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006172 unsigned lproto_nargs = lproto->getNumArgs();
6173 unsigned rproto_nargs = rproto->getNumArgs();
6174
6175 // Compatible functions must have the same number of arguments
6176 if (lproto_nargs != rproto_nargs)
6177 return QualType();
6178
6179 // Variadic and non-variadic functions aren't compatible
6180 if (lproto->isVariadic() != rproto->isVariadic())
6181 return QualType();
6182
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006183 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6184 return QualType();
6185
Fariborz Jahanian97676972011-09-28 21:52:05 +00006186 if (LangOpts.ObjCAutoRefCount &&
6187 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6188 return QualType();
6189
Eli Friedman47f77112008-08-22 00:56:42 +00006190 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006191 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006192 for (unsigned i = 0; i < lproto_nargs; i++) {
6193 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6194 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006195 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6196 OfBlockPointer,
6197 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006198 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006199
6200 if (Unqualified)
6201 argtype = argtype.getUnqualifiedType();
6202
Eli Friedman47f77112008-08-22 00:56:42 +00006203 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006204 if (Unqualified) {
6205 largtype = largtype.getUnqualifiedType();
6206 rargtype = rargtype.getUnqualifiedType();
6207 }
6208
Chris Lattner465fa322008-10-05 17:34:18 +00006209 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6210 allLTypes = false;
6211 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6212 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006213 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006214
Eli Friedman47f77112008-08-22 00:56:42 +00006215 if (allLTypes) return lhs;
6216 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006217
6218 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6219 EPI.ExtInfo = einfo;
6220 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006221 }
6222
6223 if (lproto) allRTypes = false;
6224 if (rproto) allLTypes = false;
6225
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006226 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006227 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006228 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006229 if (proto->isVariadic()) return QualType();
6230 // Check that the types are compatible with the types that
6231 // would result from default argument promotions (C99 6.7.5.3p15).
6232 // The only types actually affected are promotable integer
6233 // types and floats, which would be passed as a different
6234 // type depending on whether the prototype is visible.
6235 unsigned proto_nargs = proto->getNumArgs();
6236 for (unsigned i = 0; i < proto_nargs; ++i) {
6237 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006238
6239 // Look at the promotion type of enum types, since that is the type used
6240 // to pass enum values.
6241 if (const EnumType *Enum = argTy->getAs<EnumType>())
6242 argTy = Enum->getDecl()->getPromotionType();
6243
Eli Friedman47f77112008-08-22 00:56:42 +00006244 if (argTy->isPromotableIntegerType() ||
6245 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6246 return QualType();
6247 }
6248
6249 if (allLTypes) return lhs;
6250 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006251
6252 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6253 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006254 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006255 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006256 }
6257
6258 if (allLTypes) return lhs;
6259 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006260 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006261}
6262
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006263QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006264 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006265 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006266 // C++ [expr]: If an expression initially has the type "reference to T", the
6267 // type is adjusted to "T" prior to any further analysis, the expression
6268 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006269 // expression is an lvalue unless the reference is an rvalue reference and
6270 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006271 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6272 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006273
6274 if (Unqualified) {
6275 LHS = LHS.getUnqualifiedType();
6276 RHS = RHS.getUnqualifiedType();
6277 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006278
Eli Friedman47f77112008-08-22 00:56:42 +00006279 QualType LHSCan = getCanonicalType(LHS),
6280 RHSCan = getCanonicalType(RHS);
6281
6282 // If two types are identical, they are compatible.
6283 if (LHSCan == RHSCan)
6284 return LHS;
6285
John McCall8ccfcb52009-09-24 19:53:00 +00006286 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006287 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6288 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006289 if (LQuals != RQuals) {
6290 // If any of these qualifiers are different, we have a type
6291 // mismatch.
6292 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006293 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6294 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006295 return QualType();
6296
6297 // Exactly one GC qualifier difference is allowed: __strong is
6298 // okay if the other type has no GC qualifier but is an Objective
6299 // C object pointer (i.e. implicitly strong by default). We fix
6300 // this by pretending that the unqualified type was actually
6301 // qualified __strong.
6302 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6303 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6304 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6305
6306 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6307 return QualType();
6308
6309 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6310 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6311 }
6312 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6313 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6314 }
Eli Friedman47f77112008-08-22 00:56:42 +00006315 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006316 }
6317
6318 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006319
Eli Friedmandcca6332009-06-01 01:22:52 +00006320 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6321 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006322
Chris Lattnerfd652912008-01-14 05:45:46 +00006323 // We want to consider the two function types to be the same for these
6324 // comparisons, just force one to the other.
6325 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6326 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006327
6328 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006329 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6330 LHSClass = Type::ConstantArray;
6331 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6332 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006333
John McCall8b07ec22010-05-15 11:32:37 +00006334 // ObjCInterfaces are just specialized ObjCObjects.
6335 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6336 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6337
Nate Begemance4d7fc2008-04-18 23:10:10 +00006338 // Canonicalize ExtVector -> Vector.
6339 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6340 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006341
Chris Lattner95554662008-04-07 05:43:21 +00006342 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006343 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006344 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006345 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006346 // Compatibility is based on the underlying type, not the promotion
6347 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006348 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006349 QualType TINT = ETy->getDecl()->getIntegerType();
6350 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006351 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006352 }
John McCall9dd450b2009-09-21 23:43:11 +00006353 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006354 QualType TINT = ETy->getDecl()->getIntegerType();
6355 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006356 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006357 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006358 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006359 if (OfBlockPointer && !BlockReturnType) {
6360 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6361 return LHS;
6362 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6363 return RHS;
6364 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006365
Eli Friedman47f77112008-08-22 00:56:42 +00006366 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006367 }
Eli Friedman47f77112008-08-22 00:56:42 +00006368
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006369 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006370 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006371#define TYPE(Class, Base)
6372#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006373#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006374#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6375#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6376#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006377 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006378
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006379 case Type::LValueReference:
6380 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006381 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006382 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006383
John McCall8b07ec22010-05-15 11:32:37 +00006384 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006385 case Type::IncompleteArray:
6386 case Type::VariableArray:
6387 case Type::FunctionProto:
6388 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006389 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006390
Chris Lattnerfd652912008-01-14 05:45:46 +00006391 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006392 {
6393 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006394 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6395 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006396 if (Unqualified) {
6397 LHSPointee = LHSPointee.getUnqualifiedType();
6398 RHSPointee = RHSPointee.getUnqualifiedType();
6399 }
6400 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6401 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006402 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006403 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006404 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006405 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006406 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006407 return getPointerType(ResultType);
6408 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006409 case Type::BlockPointer:
6410 {
6411 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006412 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6413 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006414 if (Unqualified) {
6415 LHSPointee = LHSPointee.getUnqualifiedType();
6416 RHSPointee = RHSPointee.getUnqualifiedType();
6417 }
6418 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6419 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006420 if (ResultType.isNull()) return QualType();
6421 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6422 return LHS;
6423 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6424 return RHS;
6425 return getBlockPointerType(ResultType);
6426 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006427 case Type::Atomic:
6428 {
6429 // Merge two pointer types, while trying to preserve typedef info
6430 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6431 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6432 if (Unqualified) {
6433 LHSValue = LHSValue.getUnqualifiedType();
6434 RHSValue = RHSValue.getUnqualifiedType();
6435 }
6436 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6437 Unqualified);
6438 if (ResultType.isNull()) return QualType();
6439 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6440 return LHS;
6441 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6442 return RHS;
6443 return getAtomicType(ResultType);
6444 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006445 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006446 {
6447 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6448 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6449 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6450 return QualType();
6451
6452 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6453 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006454 if (Unqualified) {
6455 LHSElem = LHSElem.getUnqualifiedType();
6456 RHSElem = RHSElem.getUnqualifiedType();
6457 }
6458
6459 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006460 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006461 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6462 return LHS;
6463 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6464 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006465 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6466 ArrayType::ArraySizeModifier(), 0);
6467 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6468 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006469 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6470 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006471 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6472 return LHS;
6473 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6474 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006475 if (LVAT) {
6476 // FIXME: This isn't correct! But tricky to implement because
6477 // the array's size has to be the size of LHS, but the type
6478 // has to be different.
6479 return LHS;
6480 }
6481 if (RVAT) {
6482 // FIXME: This isn't correct! But tricky to implement because
6483 // the array's size has to be the size of RHS, but the type
6484 // has to be different.
6485 return RHS;
6486 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006487 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6488 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006489 return getIncompleteArrayType(ResultType,
6490 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006491 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006492 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006493 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006494 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006495 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006496 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006497 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006498 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006499 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006500 case Type::Complex:
6501 // Distinct complex types are incompatible.
6502 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006503 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006504 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006505 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6506 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006507 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006508 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006509 case Type::ObjCObject: {
6510 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006511 // FIXME: This should be type compatibility, e.g. whether
6512 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006513 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6514 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6515 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006516 return LHS;
6517
Eli Friedman47f77112008-08-22 00:56:42 +00006518 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006519 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006520 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006521 if (OfBlockPointer) {
6522 if (canAssignObjCInterfacesInBlockPointer(
6523 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006524 RHS->getAs<ObjCObjectPointerType>(),
6525 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006526 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006527 return QualType();
6528 }
John McCall9dd450b2009-09-21 23:43:11 +00006529 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6530 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006531 return LHS;
6532
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006533 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006534 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006535 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006536
David Blaikie8a40f702012-01-17 06:56:22 +00006537 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006538}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006539
Fariborz Jahanian97676972011-09-28 21:52:05 +00006540bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6541 const FunctionProtoType *FromFunctionType,
6542 const FunctionProtoType *ToFunctionType) {
6543 if (FromFunctionType->hasAnyConsumedArgs() !=
6544 ToFunctionType->hasAnyConsumedArgs())
6545 return false;
6546 FunctionProtoType::ExtProtoInfo FromEPI =
6547 FromFunctionType->getExtProtoInfo();
6548 FunctionProtoType::ExtProtoInfo ToEPI =
6549 ToFunctionType->getExtProtoInfo();
6550 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6551 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6552 ArgIdx != NumArgs; ++ArgIdx) {
6553 if (FromEPI.ConsumedArguments[ArgIdx] !=
6554 ToEPI.ConsumedArguments[ArgIdx])
6555 return false;
6556 }
6557 return true;
6558}
6559
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006560/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6561/// 'RHS' attributes and returns the merged version; including for function
6562/// return types.
6563QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6564 QualType LHSCan = getCanonicalType(LHS),
6565 RHSCan = getCanonicalType(RHS);
6566 // If two types are identical, they are compatible.
6567 if (LHSCan == RHSCan)
6568 return LHS;
6569 if (RHSCan->isFunctionType()) {
6570 if (!LHSCan->isFunctionType())
6571 return QualType();
6572 QualType OldReturnType =
6573 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6574 QualType NewReturnType =
6575 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6576 QualType ResReturnType =
6577 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6578 if (ResReturnType.isNull())
6579 return QualType();
6580 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6581 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6582 // In either case, use OldReturnType to build the new function type.
6583 const FunctionType *F = LHS->getAs<FunctionType>();
6584 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006585 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6586 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006587 QualType ResultType
6588 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006589 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006590 return ResultType;
6591 }
6592 }
6593 return QualType();
6594 }
6595
6596 // If the qualifiers are different, the types can still be merged.
6597 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6598 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6599 if (LQuals != RQuals) {
6600 // If any of these qualifiers are different, we have a type mismatch.
6601 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6602 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6603 return QualType();
6604
6605 // Exactly one GC qualifier difference is allowed: __strong is
6606 // okay if the other type has no GC qualifier but is an Objective
6607 // C object pointer (i.e. implicitly strong by default). We fix
6608 // this by pretending that the unqualified type was actually
6609 // qualified __strong.
6610 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6611 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6612 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6613
6614 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6615 return QualType();
6616
6617 if (GC_L == Qualifiers::Strong)
6618 return LHS;
6619 if (GC_R == Qualifiers::Strong)
6620 return RHS;
6621 return QualType();
6622 }
6623
6624 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6625 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6626 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6627 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6628 if (ResQT == LHSBaseQT)
6629 return LHS;
6630 if (ResQT == RHSBaseQT)
6631 return RHS;
6632 }
6633 return QualType();
6634}
6635
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006636//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006637// Integer Predicates
6638//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006639
Jay Foad39c79802011-01-12 09:06:06 +00006640unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006641 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006642 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006643 if (T->isBooleanType())
6644 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006645 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006646 return (unsigned)getTypeSize(T);
6647}
6648
6649QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006650 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006651
6652 // Turn <4 x signed int> -> <4 x unsigned int>
6653 if (const VectorType *VTy = T->getAs<VectorType>())
6654 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006655 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006656
6657 // For enums, we return the unsigned version of the base type.
6658 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006659 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006660
6661 const BuiltinType *BTy = T->getAs<BuiltinType>();
6662 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006663 switch (BTy->getKind()) {
6664 case BuiltinType::Char_S:
6665 case BuiltinType::SChar:
6666 return UnsignedCharTy;
6667 case BuiltinType::Short:
6668 return UnsignedShortTy;
6669 case BuiltinType::Int:
6670 return UnsignedIntTy;
6671 case BuiltinType::Long:
6672 return UnsignedLongTy;
6673 case BuiltinType::LongLong:
6674 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006675 case BuiltinType::Int128:
6676 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006677 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006678 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006679 }
6680}
6681
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006682ASTMutationListener::~ASTMutationListener() { }
6683
Chris Lattnerecd79c62009-06-14 00:45:47 +00006684
6685//===----------------------------------------------------------------------===//
6686// Builtin Type Computation
6687//===----------------------------------------------------------------------===//
6688
6689/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006690/// pointer over the consumed characters. This returns the resultant type. If
6691/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6692/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6693/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006694///
6695/// RequiresICE is filled in on return to indicate whether the value is required
6696/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006697static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006698 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006699 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006700 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006701 // Modifiers.
6702 int HowLong = 0;
6703 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006704 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006705
Chris Lattnerdc226c22010-10-01 22:42:38 +00006706 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006707 bool Done = false;
6708 while (!Done) {
6709 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006710 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006711 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006712 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006713 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006714 case 'S':
6715 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6716 assert(!Signed && "Can't use 'S' modifier multiple times!");
6717 Signed = true;
6718 break;
6719 case 'U':
6720 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6721 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6722 Unsigned = true;
6723 break;
6724 case 'L':
6725 assert(HowLong <= 2 && "Can't have LLLL modifier");
6726 ++HowLong;
6727 break;
6728 }
6729 }
6730
6731 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006732
Chris Lattnerecd79c62009-06-14 00:45:47 +00006733 // Read the base type.
6734 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006735 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006736 case 'v':
6737 assert(HowLong == 0 && !Signed && !Unsigned &&
6738 "Bad modifiers used with 'v'!");
6739 Type = Context.VoidTy;
6740 break;
6741 case 'f':
6742 assert(HowLong == 0 && !Signed && !Unsigned &&
6743 "Bad modifiers used with 'f'!");
6744 Type = Context.FloatTy;
6745 break;
6746 case 'd':
6747 assert(HowLong < 2 && !Signed && !Unsigned &&
6748 "Bad modifiers used with 'd'!");
6749 if (HowLong)
6750 Type = Context.LongDoubleTy;
6751 else
6752 Type = Context.DoubleTy;
6753 break;
6754 case 's':
6755 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6756 if (Unsigned)
6757 Type = Context.UnsignedShortTy;
6758 else
6759 Type = Context.ShortTy;
6760 break;
6761 case 'i':
6762 if (HowLong == 3)
6763 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6764 else if (HowLong == 2)
6765 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6766 else if (HowLong == 1)
6767 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6768 else
6769 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6770 break;
6771 case 'c':
6772 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6773 if (Signed)
6774 Type = Context.SignedCharTy;
6775 else if (Unsigned)
6776 Type = Context.UnsignedCharTy;
6777 else
6778 Type = Context.CharTy;
6779 break;
6780 case 'b': // boolean
6781 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6782 Type = Context.BoolTy;
6783 break;
6784 case 'z': // size_t.
6785 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6786 Type = Context.getSizeType();
6787 break;
6788 case 'F':
6789 Type = Context.getCFConstantStringType();
6790 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006791 case 'G':
6792 Type = Context.getObjCIdType();
6793 break;
6794 case 'H':
6795 Type = Context.getObjCSelType();
6796 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006797 case 'a':
6798 Type = Context.getBuiltinVaListType();
6799 assert(!Type.isNull() && "builtin va list type not initialized!");
6800 break;
6801 case 'A':
6802 // This is a "reference" to a va_list; however, what exactly
6803 // this means depends on how va_list is defined. There are two
6804 // different kinds of va_list: ones passed by value, and ones
6805 // passed by reference. An example of a by-value va_list is
6806 // x86, where va_list is a char*. An example of by-ref va_list
6807 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6808 // we want this argument to be a char*&; for x86-64, we want
6809 // it to be a __va_list_tag*.
6810 Type = Context.getBuiltinVaListType();
6811 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006812 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006813 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006814 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006815 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006816 break;
6817 case 'V': {
6818 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006819 unsigned NumElements = strtoul(Str, &End, 10);
6820 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006821 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006822
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006823 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6824 RequiresICE, false);
6825 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006826
6827 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006828 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006829 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006830 break;
6831 }
Douglas Gregorfed66992012-06-07 18:08:25 +00006832 case 'E': {
6833 char *End;
6834
6835 unsigned NumElements = strtoul(Str, &End, 10);
6836 assert(End != Str && "Missing vector size");
6837
6838 Str = End;
6839
6840 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6841 false);
6842 Type = Context.getExtVectorType(ElementType, NumElements);
6843 break;
6844 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006845 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006846 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6847 false);
6848 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006849 Type = Context.getComplexType(ElementType);
6850 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006851 }
6852 case 'Y' : {
6853 Type = Context.getPointerDiffType();
6854 break;
6855 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006856 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006857 Type = Context.getFILEType();
6858 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006859 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006860 return QualType();
6861 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006862 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006863 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006864 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006865 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006866 else
6867 Type = Context.getjmp_bufType();
6868
Mike Stump2adb4da2009-07-28 23:47:15 +00006869 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006870 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006871 return QualType();
6872 }
6873 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006874 case 'K':
6875 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6876 Type = Context.getucontext_tType();
6877
6878 if (Type.isNull()) {
6879 Error = ASTContext::GE_Missing_ucontext;
6880 return QualType();
6881 }
6882 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006883 }
Mike Stump11289f42009-09-09 15:08:12 +00006884
Chris Lattnerdc226c22010-10-01 22:42:38 +00006885 // If there are modifiers and if we're allowed to parse them, go for it.
6886 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006887 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006888 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006889 default: Done = true; --Str; break;
6890 case '*':
6891 case '&': {
6892 // Both pointers and references can have their pointee types
6893 // qualified with an address space.
6894 char *End;
6895 unsigned AddrSpace = strtoul(Str, &End, 10);
6896 if (End != Str && AddrSpace != 0) {
6897 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6898 Str = End;
6899 }
6900 if (c == '*')
6901 Type = Context.getPointerType(Type);
6902 else
6903 Type = Context.getLValueReferenceType(Type);
6904 break;
6905 }
6906 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6907 case 'C':
6908 Type = Type.withConst();
6909 break;
6910 case 'D':
6911 Type = Context.getVolatileType(Type);
6912 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006913 case 'R':
6914 Type = Type.withRestrict();
6915 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006916 }
6917 }
Chris Lattner84733392010-10-01 07:13:18 +00006918
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006919 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006920 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006921
Chris Lattnerecd79c62009-06-14 00:45:47 +00006922 return Type;
6923}
6924
6925/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006926QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006927 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006928 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006929 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006930
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006931 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006932
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006933 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006934 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006935 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6936 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006937 if (Error != GE_None)
6938 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006939
6940 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6941
Chris Lattnerecd79c62009-06-14 00:45:47 +00006942 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006943 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006944 if (Error != GE_None)
6945 return QualType();
6946
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006947 // If this argument is required to be an IntegerConstantExpression and the
6948 // caller cares, fill in the bitmask we return.
6949 if (RequiresICE && IntegerConstantArgs)
6950 *IntegerConstantArgs |= 1 << ArgTypes.size();
6951
Chris Lattnerecd79c62009-06-14 00:45:47 +00006952 // Do array -> pointer decay. The builtin should use the decayed type.
6953 if (Ty->isArrayType())
6954 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006955
Chris Lattnerecd79c62009-06-14 00:45:47 +00006956 ArgTypes.push_back(Ty);
6957 }
6958
6959 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6960 "'.' should only occur at end of builtin type list!");
6961
John McCall991eb4b2010-12-21 00:44:39 +00006962 FunctionType::ExtInfo EI;
6963 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6964
6965 bool Variadic = (TypeStr[0] == '.');
6966
6967 // We really shouldn't be making a no-proto type here, especially in C++.
6968 if (ArgTypes.empty() && Variadic)
6969 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006970
John McCalldb40c7f2010-12-14 08:05:40 +00006971 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006972 EPI.ExtInfo = EI;
6973 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006974
6975 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006976}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006977
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006978GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6979 GVALinkage External = GVA_StrongExternal;
6980
6981 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006982 switch (L) {
6983 case NoLinkage:
6984 case InternalLinkage:
6985 case UniqueExternalLinkage:
6986 return GVA_Internal;
6987
6988 case ExternalLinkage:
6989 switch (FD->getTemplateSpecializationKind()) {
6990 case TSK_Undeclared:
6991 case TSK_ExplicitSpecialization:
6992 External = GVA_StrongExternal;
6993 break;
6994
6995 case TSK_ExplicitInstantiationDefinition:
6996 return GVA_ExplicitTemplateInstantiation;
6997
6998 case TSK_ExplicitInstantiationDeclaration:
6999 case TSK_ImplicitInstantiation:
7000 External = GVA_TemplateInstantiation;
7001 break;
7002 }
7003 }
7004
7005 if (!FD->isInlined())
7006 return External;
7007
David Blaikiebbafb8a2012-03-11 07:00:24 +00007008 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007009 // GNU or C99 inline semantics. Determine whether this symbol should be
7010 // externally visible.
7011 if (FD->isInlineDefinitionExternallyVisible())
7012 return External;
7013
7014 // C99 inline semantics, where the symbol is not externally visible.
7015 return GVA_C99Inline;
7016 }
7017
7018 // C++0x [temp.explicit]p9:
7019 // [ Note: The intent is that an inline function that is the subject of
7020 // an explicit instantiation declaration will still be implicitly
7021 // instantiated when used so that the body can be considered for
7022 // inlining, but that no out-of-line copy of the inline function would be
7023 // generated in the translation unit. -- end note ]
7024 if (FD->getTemplateSpecializationKind()
7025 == TSK_ExplicitInstantiationDeclaration)
7026 return GVA_C99Inline;
7027
7028 return GVA_CXXInline;
7029}
7030
7031GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7032 // If this is a static data member, compute the kind of template
7033 // specialization. Otherwise, this variable is not part of a
7034 // template.
7035 TemplateSpecializationKind TSK = TSK_Undeclared;
7036 if (VD->isStaticDataMember())
7037 TSK = VD->getTemplateSpecializationKind();
7038
7039 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007040 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007041 VD->getType()->getLinkage() == UniqueExternalLinkage)
7042 L = UniqueExternalLinkage;
7043
7044 switch (L) {
7045 case NoLinkage:
7046 case InternalLinkage:
7047 case UniqueExternalLinkage:
7048 return GVA_Internal;
7049
7050 case ExternalLinkage:
7051 switch (TSK) {
7052 case TSK_Undeclared:
7053 case TSK_ExplicitSpecialization:
7054 return GVA_StrongExternal;
7055
7056 case TSK_ExplicitInstantiationDeclaration:
7057 llvm_unreachable("Variable should not be instantiated");
7058 // Fall through to treat this like any other instantiation.
7059
7060 case TSK_ExplicitInstantiationDefinition:
7061 return GVA_ExplicitTemplateInstantiation;
7062
7063 case TSK_ImplicitInstantiation:
7064 return GVA_TemplateInstantiation;
7065 }
7066 }
7067
David Blaikie8a40f702012-01-17 06:56:22 +00007068 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007069}
7070
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007071bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007072 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7073 if (!VD->isFileVarDecl())
7074 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007075 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007076 return false;
7077
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007078 // Weak references don't produce any output by themselves.
7079 if (D->hasAttr<WeakRefAttr>())
7080 return false;
7081
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007082 // Aliases and used decls are required.
7083 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7084 return true;
7085
7086 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7087 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007088 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007089 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007090
7091 // Constructors and destructors are required.
7092 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7093 return true;
7094
7095 // The key function for a class is required.
7096 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7097 const CXXRecordDecl *RD = MD->getParent();
7098 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7099 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7100 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7101 return true;
7102 }
7103 }
7104
7105 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7106
7107 // static, static inline, always_inline, and extern inline functions can
7108 // always be deferred. Normal inline functions can be deferred in C99/C++.
7109 // Implicit template instantiations can also be deferred in C++.
7110 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007111 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007112 return false;
7113 return true;
7114 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007115
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007116 const VarDecl *VD = cast<VarDecl>(D);
7117 assert(VD->isFileVarDecl() && "Expected file scoped var");
7118
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007119 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7120 return false;
7121
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007122 // Structs that have non-trivial constructors or destructors are required.
7123
7124 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007125 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007126 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7127 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007128 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7129 RD->hasTrivialCopyConstructor() &&
7130 RD->hasTrivialMoveConstructor() &&
7131 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007132 return true;
7133 }
7134 }
7135
7136 GVALinkage L = GetGVALinkageForVariable(VD);
7137 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7138 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7139 return false;
7140 }
7141
7142 return true;
7143}
Charles Davis53c59df2010-08-16 03:33:14 +00007144
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007145CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007146 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007147 return ABI->getDefaultMethodCallConv(isVariadic);
7148}
7149
7150CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7151 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7152 return CC_Default;
7153 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007154}
7155
Jay Foad39c79802011-01-12 09:06:06 +00007156bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007157 // Pass through to the C++ ABI object
7158 return ABI->isNearlyEmpty(RD);
7159}
7160
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007161MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007162 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007163 case CXXABI_ARM:
7164 case CXXABI_Itanium:
7165 return createItaniumMangleContext(*this, getDiagnostics());
7166 case CXXABI_Microsoft:
7167 return createMicrosoftMangleContext(*this, getDiagnostics());
7168 }
David Blaikie83d382b2011-09-23 05:06:16 +00007169 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007170}
7171
Charles Davis53c59df2010-08-16 03:33:14 +00007172CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007173
7174size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007175 return ASTRecordLayouts.getMemorySize()
7176 + llvm::capacity_in_bytes(ObjCLayouts)
7177 + llvm::capacity_in_bytes(KeyFunctions)
7178 + llvm::capacity_in_bytes(ObjCImpls)
7179 + llvm::capacity_in_bytes(BlockVarCopyInits)
7180 + llvm::capacity_in_bytes(DeclAttrs)
7181 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7182 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7183 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7184 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7185 + llvm::capacity_in_bytes(OverriddenMethods)
7186 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007187 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007188 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007189}
Ted Kremenek540017e2011-10-06 05:00:56 +00007190
Douglas Gregor63798542012-02-20 19:44:39 +00007191unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7192 CXXRecordDecl *Lambda = CallOperator->getParent();
7193 return LambdaMangleContexts[Lambda->getDeclContext()]
7194 .getManglingNumber(CallOperator);
7195}
7196
7197
Ted Kremenek540017e2011-10-06 05:00:56 +00007198void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7199 ParamIndices[D] = index;
7200}
7201
7202unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7203 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7204 assert(I != ParamIndices.end() &&
7205 "ParmIndices lacks entry set by ParmVarDecl");
7206 return I->second;
7207}