blob: 2a1521e21e8a15fb411ea9f0b54982a7f6939cba [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
81 // If the declaration doesn't map directly to a location in a file, we
82 // can't find the comment.
83 SourceLocation DeclLoc = D->getLocation();
84 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
85 return NULL;
86
87 // Find the comment that occurs just after this declaration.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +000088 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
89 ArrayRef<RawComment *>::iterator Comment
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000090 = std::lower_bound(RawComments.begin(),
91 RawComments.end(),
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +000092 &CommentAtDeclLoc,
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000093 BeforeThanCompare<RawComment>(SourceMgr));
94
95 // Decompose the location for the declaration and find the beginning of the
96 // file buffer.
97 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
98
99 // First check whether we have a trailing comment.
100 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000101 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000102 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000103 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000104 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000105 // Check that Doxygen trailing comment comes after the declaration, starts
106 // on the same line and in the same file as the declaration.
107 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
108 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
109 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
110 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000111 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000112 }
113 }
114
115 // The comment just after the declaration was not a trailing comment.
116 // Let's look at the previous comment.
117 if (Comment == RawComments.begin())
118 return NULL;
119 --Comment;
120
121 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000122 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000123 return NULL;
124
125 // Decompose the end of the comment.
126 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000127 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000128
129 // If the comment and the declaration aren't in the same file, then they
130 // aren't related.
131 if (DeclLocDecomp.first != CommentEndDecomp.first)
132 return NULL;
133
134 // Get the corresponding buffer.
135 bool Invalid = false;
136 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
137 &Invalid).data();
138 if (Invalid)
139 return NULL;
140
141 // Extract text between the comment and declaration.
142 StringRef Text(Buffer + CommentEndDecomp.second,
143 DeclLocDecomp.second - CommentEndDecomp.second);
144
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000145 // There should be no other declarations or preprocessor directives between
146 // comment and declaration.
147 if (Text.find_first_of(",;{}#") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000148 return NULL;
149
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000150 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000151}
152
153const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const {
154 // Check whether we have cached a comment string for this declaration
155 // already.
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000156 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000157 = DeclComments.find(D);
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000158 if (Pos != DeclComments.end()) {
159 RawAndParsedComment C = Pos->second;
160 return C.first;
161 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000162
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000163 RawComment *RC = getRawCommentForDeclNoCache(D);
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000164 // If we found a comment, it should be a documentation comment.
165 assert(!RC || RC->isDocumentation());
Dmitri Gribenko08630052012-07-06 15:40:08 +0000166 DeclComments[D] =
167 RawAndParsedComment(RC, static_cast<comments::FullComment *>(NULL));
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000168 if (RC)
169 RC->setAttached();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000170 return RC;
171}
172
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000173comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const {
174 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
175 = DeclComments.find(D);
176 const RawComment *RC;
177 if (Pos != DeclComments.end()) {
178 RawAndParsedComment C = Pos->second;
179 if (comments::FullComment *FC = C.second)
180 return FC;
181 RC = C.first;
182 } else
183 RC = getRawCommentForDecl(D);
184
185 if (!RC)
186 return NULL;
187
188 const StringRef RawText = RC->getRawText(SourceMgr);
189 comments::Lexer L(RC->getSourceRange().getBegin(), comments::CommentOptions(),
190 RawText.begin(), RawText.end());
191
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000192 comments::Sema S(getAllocator(), getSourceManager(), getDiagnostics());
193 S.setDecl(D);
194 comments::Parser P(L, S, getAllocator(), getSourceManager(),
195 getDiagnostics());
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000196
197 comments::FullComment *FC = P.parseFullComment();
198 DeclComments[D].second = FC;
199 return FC;
200}
201
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000202void
203ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
204 TemplateTemplateParmDecl *Parm) {
205 ID.AddInteger(Parm->getDepth());
206 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000207 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000208
209 TemplateParameterList *Params = Parm->getTemplateParameters();
210 ID.AddInteger(Params->size());
211 for (TemplateParameterList::const_iterator P = Params->begin(),
212 PEnd = Params->end();
213 P != PEnd; ++P) {
214 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
215 ID.AddInteger(0);
216 ID.AddBoolean(TTP->isParameterPack());
217 continue;
218 }
219
220 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
221 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000222 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000223 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000224 if (NTTP->isExpandedParameterPack()) {
225 ID.AddBoolean(true);
226 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000227 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
228 QualType T = NTTP->getExpansionType(I);
229 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
230 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000231 } else
232 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000233 continue;
234 }
235
236 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
237 ID.AddInteger(2);
238 Profile(ID, TTP);
239 }
240}
241
242TemplateTemplateParmDecl *
243ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000244 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000245 // Check if we already have a canonical template template parameter.
246 llvm::FoldingSetNodeID ID;
247 CanonicalTemplateTemplateParm::Profile(ID, TTP);
248 void *InsertPos = 0;
249 CanonicalTemplateTemplateParm *Canonical
250 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
251 if (Canonical)
252 return Canonical->getParam();
253
254 // Build a canonical template parameter list.
255 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000256 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000257 CanonParams.reserve(Params->size());
258 for (TemplateParameterList::const_iterator P = Params->begin(),
259 PEnd = Params->end();
260 P != PEnd; ++P) {
261 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
262 CanonParams.push_back(
263 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000264 SourceLocation(),
265 SourceLocation(),
266 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000267 TTP->getIndex(), 0, false,
268 TTP->isParameterPack()));
269 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000270 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
271 QualType T = getCanonicalType(NTTP->getType());
272 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
273 NonTypeTemplateParmDecl *Param;
274 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000275 SmallVector<QualType, 2> ExpandedTypes;
276 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000277 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
278 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
279 ExpandedTInfos.push_back(
280 getTrivialTypeSourceInfo(ExpandedTypes.back()));
281 }
282
283 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000284 SourceLocation(),
285 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000286 NTTP->getDepth(),
287 NTTP->getPosition(), 0,
288 T,
289 TInfo,
290 ExpandedTypes.data(),
291 ExpandedTypes.size(),
292 ExpandedTInfos.data());
293 } else {
294 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000295 SourceLocation(),
296 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000297 NTTP->getDepth(),
298 NTTP->getPosition(), 0,
299 T,
300 NTTP->isParameterPack(),
301 TInfo);
302 }
303 CanonParams.push_back(Param);
304
305 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000306 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
307 cast<TemplateTemplateParmDecl>(*P)));
308 }
309
310 TemplateTemplateParmDecl *CanonTTP
311 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
312 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000313 TTP->getPosition(),
314 TTP->isParameterPack(),
315 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000316 TemplateParameterList::Create(*this, SourceLocation(),
317 SourceLocation(),
318 CanonParams.data(),
319 CanonParams.size(),
320 SourceLocation()));
321
322 // Get the new insert position for the node we care about.
323 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
324 assert(Canonical == 0 && "Shouldn't be in the map!");
325 (void)Canonical;
326
327 // Create the canonical template template parameter entry.
328 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
329 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
330 return CanonTTP;
331}
332
Charles Davis53c59df2010-08-16 03:33:14 +0000333CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000334 if (!LangOpts.CPlusPlus) return 0;
335
Charles Davis6bcb07a2010-08-19 02:18:14 +0000336 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000337 case CXXABI_ARM:
338 return CreateARMCXXABI(*this);
339 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000340 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000341 case CXXABI_Microsoft:
342 return CreateMicrosoftCXXABI(*this);
343 }
David Blaikie8a40f702012-01-17 06:56:22 +0000344 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000345}
346
Douglas Gregore8bbc122011-09-02 00:18:52 +0000347static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000348 const LangOptions &LOpts) {
349 if (LOpts.FakeAddressSpaceMap) {
350 // The fake address space map must have a distinct entry for each
351 // language-specific address space.
352 static const unsigned FakeAddrSpaceMap[] = {
353 1, // opencl_global
354 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000355 3, // opencl_constant
356 4, // cuda_device
357 5, // cuda_constant
358 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000359 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000360 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000361 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000362 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000363 }
364}
365
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000366ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000367 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000368 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000369 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000370 unsigned size_reserve,
371 bool DelayInitialization)
372 : FunctionProtoTypes(this_()),
373 TemplateSpecializationTypes(this_()),
374 DependentTemplateSpecializationTypes(this_()),
375 SubstTemplateTemplateParmPacks(this_()),
376 GlobalNestedNameSpecifier(0),
377 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000378 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000379 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000380 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000381 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000382 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
383 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
384 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000385 NullTypeSourceInfo(QualType()),
386 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000387 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000388 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000389 Idents(idents), Selectors(sels),
390 BuiltinInfo(builtins),
391 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000392 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000393 Comments(SM), CommentsLoaded(false),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000394 LastSDM(0, 0),
395 UniqueBlockByRefTypeID(0)
396{
Mike Stump11289f42009-09-09 15:08:12 +0000397 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000398 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000399
400 if (!DelayInitialization) {
401 assert(t && "No target supplied for ASTContext initialization");
402 InitBuiltinTypes(*t);
403 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000404}
405
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000406ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000407 // Release the DenseMaps associated with DeclContext objects.
408 // FIXME: Is this the ideal solution?
409 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000410
Douglas Gregor5b11d492010-07-25 17:53:33 +0000411 // Call all of the deallocation functions.
412 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
413 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000414
Ted Kremenek076baeb2010-06-08 23:00:58 +0000415 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000416 // because they can contain DenseMaps.
417 for (llvm::DenseMap<const ObjCContainerDecl*,
418 const ASTRecordLayout*>::iterator
419 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
420 // Increment in loop to prevent using deallocated memory.
421 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
422 R->Destroy(*this);
423
Ted Kremenek076baeb2010-06-08 23:00:58 +0000424 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
425 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
426 // Increment in loop to prevent using deallocated memory.
427 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
428 R->Destroy(*this);
429 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000430
431 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
432 AEnd = DeclAttrs.end();
433 A != AEnd; ++A)
434 A->second->~AttrVec();
435}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000436
Douglas Gregor1a809332010-05-23 18:26:36 +0000437void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
438 Deallocations.push_back(std::make_pair(Callback, Data));
439}
440
Mike Stump11289f42009-09-09 15:08:12 +0000441void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000442ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000443 ExternalSource.reset(Source.take());
444}
445
Chris Lattner4eb445d2007-01-26 01:27:23 +0000446void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000447 llvm::errs() << "\n*** AST Context Stats:\n";
448 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000449
Douglas Gregora30d0462009-05-26 14:40:08 +0000450 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000451#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000452#define ABSTRACT_TYPE(Name, Parent)
453#include "clang/AST/TypeNodes.def"
454 0 // Extra
455 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000456
Chris Lattner4eb445d2007-01-26 01:27:23 +0000457 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
458 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000459 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000460 }
461
Douglas Gregora30d0462009-05-26 14:40:08 +0000462 unsigned Idx = 0;
463 unsigned TotalBytes = 0;
464#define TYPE(Name, Parent) \
465 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000466 llvm::errs() << " " << counts[Idx] << " " << #Name \
467 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000468 TotalBytes += counts[Idx] * sizeof(Name##Type); \
469 ++Idx;
470#define ABSTRACT_TYPE(Name, Parent)
471#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000472
Chandler Carruth3c147a72011-07-04 05:32:14 +0000473 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
474
Douglas Gregor7454c562010-07-02 20:37:36 +0000475 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000476 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
477 << NumImplicitDefaultConstructors
478 << " implicit default constructors created\n";
479 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
480 << NumImplicitCopyConstructors
481 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000482 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000483 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
484 << NumImplicitMoveConstructors
485 << " implicit move constructors created\n";
486 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
487 << NumImplicitCopyAssignmentOperators
488 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000489 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000490 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
491 << NumImplicitMoveAssignmentOperators
492 << " implicit move assignment operators created\n";
493 llvm::errs() << NumImplicitDestructorsDeclared << "/"
494 << NumImplicitDestructors
495 << " implicit destructors created\n";
496
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000497 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000498 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000499 ExternalSource->PrintStats();
500 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000501
Douglas Gregor5b11d492010-07-25 17:53:33 +0000502 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000503}
504
Douglas Gregor801c99d2011-08-12 06:49:56 +0000505TypedefDecl *ASTContext::getInt128Decl() const {
506 if (!Int128Decl) {
507 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
508 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
509 getTranslationUnitDecl(),
510 SourceLocation(),
511 SourceLocation(),
512 &Idents.get("__int128_t"),
513 TInfo);
514 }
515
516 return Int128Decl;
517}
518
519TypedefDecl *ASTContext::getUInt128Decl() const {
520 if (!UInt128Decl) {
521 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
522 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
523 getTranslationUnitDecl(),
524 SourceLocation(),
525 SourceLocation(),
526 &Idents.get("__uint128_t"),
527 TInfo);
528 }
529
530 return UInt128Decl;
531}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000532
John McCall48f2d582009-10-23 23:03:21 +0000533void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000534 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000535 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000536 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000537}
538
Douglas Gregore8bbc122011-09-02 00:18:52 +0000539void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
540 assert((!this->Target || this->Target == &Target) &&
541 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000542 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000543
Douglas Gregore8bbc122011-09-02 00:18:52 +0000544 this->Target = &Target;
545
546 ABI.reset(createCXXABI(Target));
547 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
548
Chris Lattner970e54e2006-11-12 00:37:36 +0000549 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000550 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000551
Chris Lattner970e54e2006-11-12 00:37:36 +0000552 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000553 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000554 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000555 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000556 InitBuiltinType(CharTy, BuiltinType::Char_S);
557 else
558 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000559 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000560 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
561 InitBuiltinType(ShortTy, BuiltinType::Short);
562 InitBuiltinType(IntTy, BuiltinType::Int);
563 InitBuiltinType(LongTy, BuiltinType::Long);
564 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000565
Chris Lattner970e54e2006-11-12 00:37:36 +0000566 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000567 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
568 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
569 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
570 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
571 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000572
Chris Lattner970e54e2006-11-12 00:37:36 +0000573 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000574 InitBuiltinType(FloatTy, BuiltinType::Float);
575 InitBuiltinType(DoubleTy, BuiltinType::Double);
576 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000577
Chris Lattnerf122cef2009-04-30 02:43:43 +0000578 // GNU extension, 128-bit integers.
579 InitBuiltinType(Int128Ty, BuiltinType::Int128);
580 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
581
Chris Lattnerad3467e2010-12-25 23:25:43 +0000582 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000583 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000584 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
585 else // -fshort-wchar makes wchar_t be unsigned.
586 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
587 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000588 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000589
James Molloy36365542012-05-04 10:55:22 +0000590 WIntTy = getFromTargetType(Target.getWIntType());
591
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000592 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
593 InitBuiltinType(Char16Ty, BuiltinType::Char16);
594 else // C99
595 Char16Ty = getFromTargetType(Target.getChar16Type());
596
597 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
598 InitBuiltinType(Char32Ty, BuiltinType::Char32);
599 else // C99
600 Char32Ty = getFromTargetType(Target.getChar32Type());
601
Douglas Gregor4619e432008-12-05 23:32:09 +0000602 // Placeholder type for type-dependent expressions whose type is
603 // completely unknown. No code should ever check a type against
604 // DependentTy and users should never see it; however, it is here to
605 // help diagnose failures to properly check for type-dependent
606 // expressions.
607 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000608
John McCall36e7fe32010-10-12 00:20:44 +0000609 // Placeholder type for functions.
610 InitBuiltinType(OverloadTy, BuiltinType::Overload);
611
John McCall0009fcc2011-04-26 20:42:42 +0000612 // Placeholder type for bound members.
613 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
614
John McCall526ab472011-10-25 17:37:35 +0000615 // Placeholder type for pseudo-objects.
616 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
617
John McCall31996342011-04-07 08:22:57 +0000618 // "any" type; useful for debugger-like clients.
619 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
620
John McCall8a6b59a2011-10-17 18:09:15 +0000621 // Placeholder type for unbridged ARC casts.
622 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
623
Chris Lattner970e54e2006-11-12 00:37:36 +0000624 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000625 FloatComplexTy = getComplexType(FloatTy);
626 DoubleComplexTy = getComplexType(DoubleTy);
627 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000628
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000629 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000630 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
631 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000632 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000633
634 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000635 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
636 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000637
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000638 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000639
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000640 // void * type
641 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000642
643 // nullptr type (C++0x 2.14.7)
644 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000645
646 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
647 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000648
649 // Builtin type used to help define __builtin_va_list.
650 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000651}
652
David Blaikie9c902b52011-09-25 23:23:43 +0000653DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000654 return SourceMgr.getDiagnostics();
655}
656
Douglas Gregor561eceb2010-08-30 16:49:28 +0000657AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
658 AttrVec *&Result = DeclAttrs[D];
659 if (!Result) {
660 void *Mem = Allocate(sizeof(AttrVec));
661 Result = new (Mem) AttrVec;
662 }
663
664 return *Result;
665}
666
667/// \brief Erase the attributes corresponding to the given declaration.
668void ASTContext::eraseDeclAttrs(const Decl *D) {
669 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
670 if (Pos != DeclAttrs.end()) {
671 Pos->second->~AttrVec();
672 DeclAttrs.erase(Pos);
673 }
674}
675
Douglas Gregor86d142a2009-10-08 07:24:58 +0000676MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000677ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000678 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000679 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000680 = InstantiatedFromStaticDataMember.find(Var);
681 if (Pos == InstantiatedFromStaticDataMember.end())
682 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000683
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000684 return Pos->second;
685}
686
Mike Stump11289f42009-09-09 15:08:12 +0000687void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000688ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000689 TemplateSpecializationKind TSK,
690 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000691 assert(Inst->isStaticDataMember() && "Not a static data member");
692 assert(Tmpl->isStaticDataMember() && "Not a static data member");
693 assert(!InstantiatedFromStaticDataMember[Inst] &&
694 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000695 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000696 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000697}
698
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000699FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
700 const FunctionDecl *FD){
701 assert(FD && "Specialization is 0");
702 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000703 = ClassScopeSpecializationPattern.find(FD);
704 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000705 return 0;
706
707 return Pos->second;
708}
709
710void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
711 FunctionDecl *Pattern) {
712 assert(FD && "Specialization is 0");
713 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000714 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000715}
716
John McCalle61f2ba2009-11-18 02:36:19 +0000717NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000718ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000719 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000720 = InstantiatedFromUsingDecl.find(UUD);
721 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000722 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000723
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000724 return Pos->second;
725}
726
727void
John McCallb96ec562009-12-04 22:46:56 +0000728ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
729 assert((isa<UsingDecl>(Pattern) ||
730 isa<UnresolvedUsingValueDecl>(Pattern) ||
731 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
732 "pattern decl is not a using decl");
733 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
734 InstantiatedFromUsingDecl[Inst] = Pattern;
735}
736
737UsingShadowDecl *
738ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
739 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
740 = InstantiatedFromUsingShadowDecl.find(Inst);
741 if (Pos == InstantiatedFromUsingShadowDecl.end())
742 return 0;
743
744 return Pos->second;
745}
746
747void
748ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
749 UsingShadowDecl *Pattern) {
750 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
751 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000752}
753
Anders Carlsson5da84842009-09-01 04:26:58 +0000754FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
755 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
756 = InstantiatedFromUnnamedFieldDecl.find(Field);
757 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
758 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000759
Anders Carlsson5da84842009-09-01 04:26:58 +0000760 return Pos->second;
761}
762
763void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
764 FieldDecl *Tmpl) {
765 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
766 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
767 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
768 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000769
Anders Carlsson5da84842009-09-01 04:26:58 +0000770 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
771}
772
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000773bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
774 const FieldDecl *LastFD) const {
775 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000776 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000777}
778
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000779bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
780 const FieldDecl *LastFD) const {
781 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000782 FD->getBitWidthValue(*this) == 0 &&
783 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000784}
785
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000786bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
787 const FieldDecl *LastFD) const {
788 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000789 FD->getBitWidthValue(*this) &&
790 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000791}
792
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000793bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000794 const FieldDecl *LastFD) const {
795 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000796 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000797}
798
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000799bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000800 const FieldDecl *LastFD) const {
801 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000802 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000803}
804
Douglas Gregor832940b2010-03-02 23:58:15 +0000805ASTContext::overridden_cxx_method_iterator
806ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
807 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
808 = OverriddenMethods.find(Method);
809 if (Pos == OverriddenMethods.end())
810 return 0;
811
812 return Pos->second.begin();
813}
814
815ASTContext::overridden_cxx_method_iterator
816ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
817 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
818 = OverriddenMethods.find(Method);
819 if (Pos == OverriddenMethods.end())
820 return 0;
821
822 return Pos->second.end();
823}
824
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000825unsigned
826ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
827 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
828 = OverriddenMethods.find(Method);
829 if (Pos == OverriddenMethods.end())
830 return 0;
831
832 return Pos->second.size();
833}
834
Douglas Gregor832940b2010-03-02 23:58:15 +0000835void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
836 const CXXMethodDecl *Overridden) {
837 OverriddenMethods[Method].push_back(Overridden);
838}
839
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000840void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
841 assert(!Import->NextLocalImport && "Import declaration already in the chain");
842 assert(!Import->isFromASTFile() && "Non-local import declaration");
843 if (!FirstLocalImport) {
844 FirstLocalImport = Import;
845 LastLocalImport = Import;
846 return;
847 }
848
849 LastLocalImport->NextLocalImport = Import;
850 LastLocalImport = Import;
851}
852
Chris Lattner53cfe802007-07-18 17:52:12 +0000853//===----------------------------------------------------------------------===//
854// Type Sizing and Analysis
855//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000856
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000857/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
858/// scalar floating point type.
859const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000860 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000861 assert(BT && "Not a floating point type!");
862 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000863 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000864 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000865 case BuiltinType::Float: return Target->getFloatFormat();
866 case BuiltinType::Double: return Target->getDoubleFormat();
867 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000868 }
869}
870
Ken Dyck160146e2010-01-27 17:10:57 +0000871/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000872/// specified decl. Note that bitfields do not have a valid alignment, so
873/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000874/// If @p RefAsPointee, references are treated like their underlying type
875/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000876CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000877 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000878
John McCall94268702010-10-08 18:24:19 +0000879 bool UseAlignAttrOnly = false;
880 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
881 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000882
John McCall94268702010-10-08 18:24:19 +0000883 // __attribute__((aligned)) can increase or decrease alignment
884 // *except* on a struct or struct member, where it only increases
885 // alignment unless 'packed' is also specified.
886 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000887 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000888 // ignore that possibility; Sema should diagnose it.
889 if (isa<FieldDecl>(D)) {
890 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
891 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
892 } else {
893 UseAlignAttrOnly = true;
894 }
895 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000896 else if (isa<FieldDecl>(D))
897 UseAlignAttrOnly =
898 D->hasAttr<PackedAttr>() ||
899 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000900
John McCall4e819612011-01-20 07:57:12 +0000901 // If we're using the align attribute only, just ignore everything
902 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000903 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000904 // do nothing
905
John McCall94268702010-10-08 18:24:19 +0000906 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000907 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000908 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000909 if (RefAsPointee)
910 T = RT->getPointeeType();
911 else
912 T = getPointerType(RT->getPointeeType());
913 }
914 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000915 // Adjust alignments of declarations with array type by the
916 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000917 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000918 const ArrayType *arrayType;
919 if (MinWidth && (arrayType = getAsArrayType(T))) {
920 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000921 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000922 else if (isa<ConstantArrayType>(arrayType) &&
923 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000924 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000925
John McCall33ddac02011-01-19 10:06:00 +0000926 // Walk through any array types while we're at it.
927 T = getBaseElementType(arrayType);
928 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000929 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000930 }
John McCall4e819612011-01-20 07:57:12 +0000931
932 // Fields can be subject to extra alignment constraints, like if
933 // the field is packed, the struct is packed, or the struct has a
934 // a max-field-alignment constraint (#pragma pack). So calculate
935 // the actual alignment of the field within the struct, and then
936 // (as we're expected to) constrain that by the alignment of the type.
937 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
938 // So calculate the alignment of the field.
939 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
940
941 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000942 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000943
944 // Use the GCD of that and the offset within the record.
945 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
946 if (offset > 0) {
947 // Alignment is always a power of 2, so the GCD will be a power of 2,
948 // which means we get to do this crazy thing instead of Euclid's.
949 uint64_t lowBitOfOffset = offset & (~offset + 1);
950 if (lowBitOfOffset < fieldAlign)
951 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
952 }
953
954 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000955 }
Chris Lattner68061312009-01-24 21:53:27 +0000956 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000957
Ken Dyckcc56c542011-01-15 18:38:59 +0000958 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000959}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000960
John McCall87fe5d52010-05-20 01:18:31 +0000961std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000962ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000963 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000964 return std::make_pair(toCharUnitsFromBits(Info.first),
965 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000966}
967
968std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000969ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000970 return getTypeInfoInChars(T.getTypePtr());
971}
972
Daniel Dunbarc6475872012-03-09 04:12:54 +0000973std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
974 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
975 if (it != MemoizedTypeInfo.end())
976 return it->second;
977
978 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
979 MemoizedTypeInfo.insert(std::make_pair(T, Info));
980 return Info;
981}
982
983/// getTypeInfoImpl - Return the size of the specified type, in bits. This
984/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000985///
986/// FIXME: Pointers into different addr spaces could have different sizes and
987/// alignment requirements: getPointerInfo should take an AddrSpace, this
988/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000989std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +0000990ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000991 uint64_t Width=0;
992 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000993 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000994#define TYPE(Class, Base)
995#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000996#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000997#define DEPENDENT_TYPE(Class, Base) case Type::Class:
998#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000999 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001000
Chris Lattner355332d2007-07-13 22:27:08 +00001001 case Type::FunctionNoProto:
1002 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001003 // GCC extension: alignof(function) = 32 bits
1004 Width = 0;
1005 Align = 32;
1006 break;
1007
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001008 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001009 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001010 Width = 0;
1011 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1012 break;
1013
Steve Naroff5c131802007-08-30 01:06:46 +00001014 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001015 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001016
Chris Lattner37e05872008-03-05 18:54:05 +00001017 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001018 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001019 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1020 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001021 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001022 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001023 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001024 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001025 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001026 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001027 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001028 const VectorType *VT = cast<VectorType>(T);
1029 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1030 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001031 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001032 // If the alignment is not a power of 2, round up to the next power of 2.
1033 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001034 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001035 Align = llvm::NextPowerOf2(Align);
1036 Width = llvm::RoundUpToAlignment(Width, Align);
1037 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001038 break;
1039 }
Chris Lattner647fb222007-07-18 18:26:58 +00001040
Chris Lattner7570e9c2008-03-08 08:52:55 +00001041 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001042 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001043 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001044 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001045 // GCC extension: alignof(void) = 8 bits.
1046 Width = 0;
1047 Align = 8;
1048 break;
1049
Chris Lattner6a4f7452007-12-19 19:23:28 +00001050 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001051 Width = Target->getBoolWidth();
1052 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001053 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001054 case BuiltinType::Char_S:
1055 case BuiltinType::Char_U:
1056 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001057 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001058 Width = Target->getCharWidth();
1059 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001060 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001061 case BuiltinType::WChar_S:
1062 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001063 Width = Target->getWCharWidth();
1064 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001065 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001066 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001067 Width = Target->getChar16Width();
1068 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001069 break;
1070 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001071 Width = Target->getChar32Width();
1072 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001073 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001074 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001075 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001076 Width = Target->getShortWidth();
1077 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001078 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001079 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001080 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001081 Width = Target->getIntWidth();
1082 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001083 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001084 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001085 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001086 Width = Target->getLongWidth();
1087 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001088 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001089 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001090 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001091 Width = Target->getLongLongWidth();
1092 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001093 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001094 case BuiltinType::Int128:
1095 case BuiltinType::UInt128:
1096 Width = 128;
1097 Align = 128; // int128_t is 128-bit aligned on all targets.
1098 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001099 case BuiltinType::Half:
1100 Width = Target->getHalfWidth();
1101 Align = Target->getHalfAlign();
1102 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001103 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001104 Width = Target->getFloatWidth();
1105 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001106 break;
1107 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001108 Width = Target->getDoubleWidth();
1109 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001110 break;
1111 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001112 Width = Target->getLongDoubleWidth();
1113 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001114 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001115 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001116 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1117 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001118 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001119 case BuiltinType::ObjCId:
1120 case BuiltinType::ObjCClass:
1121 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001122 Width = Target->getPointerWidth(0);
1123 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001124 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001125 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001126 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001127 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001128 Width = Target->getPointerWidth(0);
1129 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001130 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001131 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001132 unsigned AS = getTargetAddressSpace(
1133 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001134 Width = Target->getPointerWidth(AS);
1135 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001136 break;
1137 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001138 case Type::LValueReference:
1139 case Type::RValueReference: {
1140 // alignof and sizeof should never enter this code path here, so we go
1141 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001142 unsigned AS = getTargetAddressSpace(
1143 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001144 Width = Target->getPointerWidth(AS);
1145 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001146 break;
1147 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001148 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001149 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001150 Width = Target->getPointerWidth(AS);
1151 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001152 break;
1153 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001154 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001155 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001156 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001157 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001158 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001159 Align = PtrDiffInfo.second;
1160 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001161 }
Chris Lattner647fb222007-07-18 18:26:58 +00001162 case Type::Complex: {
1163 // Complex types have the same alignment as their elements, but twice the
1164 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001165 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001166 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001167 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001168 Align = EltInfo.second;
1169 break;
1170 }
John McCall8b07ec22010-05-15 11:32:37 +00001171 case Type::ObjCObject:
1172 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001173 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001174 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001175 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001176 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001177 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001178 break;
1179 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001180 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001181 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001182 const TagType *TT = cast<TagType>(T);
1183
1184 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001185 Width = 8;
1186 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001187 break;
1188 }
Mike Stump11289f42009-09-09 15:08:12 +00001189
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001190 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001191 return getTypeInfo(ET->getDecl()->getIntegerType());
1192
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001193 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001194 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001195 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001196 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001197 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001198 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001199
Chris Lattner63d2b362009-10-22 05:17:15 +00001200 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001201 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1202 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001203
Richard Smith30482bc2011-02-20 03:19:35 +00001204 case Type::Auto: {
1205 const AutoType *A = cast<AutoType>(T);
1206 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001207 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001208 }
1209
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001210 case Type::Paren:
1211 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1212
Douglas Gregoref462e62009-04-30 17:32:17 +00001213 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001214 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001215 std::pair<uint64_t, unsigned> Info
1216 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001217 // If the typedef has an aligned attribute on it, it overrides any computed
1218 // alignment we have. This violates the GCC documentation (which says that
1219 // attribute(aligned) can only round up) but matches its implementation.
1220 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1221 Align = AttrAlign;
1222 else
1223 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001224 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001225 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001226 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001227
1228 case Type::TypeOfExpr:
1229 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1230 .getTypePtr());
1231
1232 case Type::TypeOf:
1233 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1234
Anders Carlsson81df7b82009-06-24 19:06:50 +00001235 case Type::Decltype:
1236 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1237 .getTypePtr());
1238
Alexis Hunte852b102011-05-24 22:41:36 +00001239 case Type::UnaryTransform:
1240 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1241
Abramo Bagnara6150c882010-05-11 21:36:43 +00001242 case Type::Elaborated:
1243 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001244
John McCall81904512011-01-06 01:58:22 +00001245 case Type::Attributed:
1246 return getTypeInfo(
1247 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1248
Richard Smith3f1b5d02011-05-05 21:57:07 +00001249 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001250 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001251 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001252 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1253 // A type alias template specialization may refer to a typedef with the
1254 // aligned attribute on it.
1255 if (TST->isTypeAlias())
1256 return getTypeInfo(TST->getAliasedType().getTypePtr());
1257 else
1258 return getTypeInfo(getCanonicalType(T));
1259 }
1260
Eli Friedman0dfb8892011-10-06 23:00:33 +00001261 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001262 std::pair<uint64_t, unsigned> Info
1263 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1264 Width = Info.first;
1265 Align = Info.second;
1266 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1267 llvm::isPowerOf2_64(Width)) {
1268 // We can potentially perform lock-free atomic operations for this
1269 // type; promote the alignment appropriately.
1270 // FIXME: We could potentially promote the width here as well...
1271 // is that worthwhile? (Non-struct atomic types generally have
1272 // power-of-two size anyway, but structs might not. Requires a bit
1273 // of implementation work to make sure we zero out the extra bits.)
1274 Align = static_cast<unsigned>(Width);
1275 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001276 }
1277
Douglas Gregoref462e62009-04-30 17:32:17 +00001278 }
Mike Stump11289f42009-09-09 15:08:12 +00001279
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001280 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001281 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001282}
1283
Ken Dyckcc56c542011-01-15 18:38:59 +00001284/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1285CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1286 return CharUnits::fromQuantity(BitSize / getCharWidth());
1287}
1288
Ken Dyckb0fcc592011-02-11 01:54:29 +00001289/// toBits - Convert a size in characters to a size in characters.
1290int64_t ASTContext::toBits(CharUnits CharSize) const {
1291 return CharSize.getQuantity() * getCharWidth();
1292}
1293
Ken Dyck8c89d592009-12-22 14:23:30 +00001294/// getTypeSizeInChars - Return the size of the specified type, in characters.
1295/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001296CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001297 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001298}
Jay Foad39c79802011-01-12 09:06:06 +00001299CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001300 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001301}
1302
Ken Dycka6046ab2010-01-26 17:25:18 +00001303/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001304/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001305CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001306 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001307}
Jay Foad39c79802011-01-12 09:06:06 +00001308CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001309 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001310}
1311
Chris Lattnera3402cd2009-01-27 18:08:34 +00001312/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1313/// type for the current target in bits. This can be different than the ABI
1314/// alignment in cases where it is beneficial for performance to overalign
1315/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001316unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001317 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001318
1319 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001320 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001321 T = CT->getElementType().getTypePtr();
1322 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001323 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1324 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001325 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1326
Chris Lattnera3402cd2009-01-27 18:08:34 +00001327 return ABIAlign;
1328}
1329
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001330/// DeepCollectObjCIvars -
1331/// This routine first collects all declared, but not synthesized, ivars in
1332/// super class and then collects all ivars, including those synthesized for
1333/// current class. This routine is used for implementation of current class
1334/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001335///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001336void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1337 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001338 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001339 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1340 DeepCollectObjCIvars(SuperClass, false, Ivars);
1341 if (!leafClass) {
1342 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1343 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001344 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001345 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001346 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001347 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001348 Iv= Iv->getNextIvar())
1349 Ivars.push_back(Iv);
1350 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001351}
1352
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001353/// CollectInheritedProtocols - Collect all protocols in current class and
1354/// those inherited by it.
1355void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001356 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001357 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001358 // We can use protocol_iterator here instead of
1359 // all_referenced_protocol_iterator since we are walking all categories.
1360 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1361 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001362 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001363 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001364 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001365 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001366 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001367 CollectInheritedProtocols(*P, Protocols);
1368 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001369 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001370
1371 // Categories of this Interface.
1372 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1373 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1374 CollectInheritedProtocols(CDeclChain, Protocols);
1375 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1376 while (SD) {
1377 CollectInheritedProtocols(SD, Protocols);
1378 SD = SD->getSuperClass();
1379 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001380 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001381 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001382 PE = OC->protocol_end(); P != PE; ++P) {
1383 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001384 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001385 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1386 PE = Proto->protocol_end(); P != PE; ++P)
1387 CollectInheritedProtocols(*P, Protocols);
1388 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001389 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001390 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1391 PE = OP->protocol_end(); P != PE; ++P) {
1392 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001393 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001394 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1395 PE = Proto->protocol_end(); P != PE; ++P)
1396 CollectInheritedProtocols(*P, Protocols);
1397 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001398 }
1399}
1400
Jay Foad39c79802011-01-12 09:06:06 +00001401unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001402 unsigned count = 0;
1403 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001404 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1405 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001406 count += CDecl->ivar_size();
1407
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001408 // Count ivar defined in this class's implementation. This
1409 // includes synthesized ivars.
1410 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001411 count += ImplDecl->ivar_size();
1412
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001413 return count;
1414}
1415
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001416bool ASTContext::isSentinelNullExpr(const Expr *E) {
1417 if (!E)
1418 return false;
1419
1420 // nullptr_t is always treated as null.
1421 if (E->getType()->isNullPtrType()) return true;
1422
1423 if (E->getType()->isAnyPointerType() &&
1424 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1425 Expr::NPC_ValueDependentIsNull))
1426 return true;
1427
1428 // Unfortunately, __null has type 'int'.
1429 if (isa<GNUNullExpr>(E)) return true;
1430
1431 return false;
1432}
1433
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001434/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1435ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1436 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1437 I = ObjCImpls.find(D);
1438 if (I != ObjCImpls.end())
1439 return cast<ObjCImplementationDecl>(I->second);
1440 return 0;
1441}
1442/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1443ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1444 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1445 I = ObjCImpls.find(D);
1446 if (I != ObjCImpls.end())
1447 return cast<ObjCCategoryImplDecl>(I->second);
1448 return 0;
1449}
1450
1451/// \brief Set the implementation of ObjCInterfaceDecl.
1452void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1453 ObjCImplementationDecl *ImplD) {
1454 assert(IFaceD && ImplD && "Passed null params");
1455 ObjCImpls[IFaceD] = ImplD;
1456}
1457/// \brief Set the implementation of ObjCCategoryDecl.
1458void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1459 ObjCCategoryImplDecl *ImplD) {
1460 assert(CatD && ImplD && "Passed null params");
1461 ObjCImpls[CatD] = ImplD;
1462}
1463
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001464ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1465 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1466 return ID;
1467 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1468 return CD->getClassInterface();
1469 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1470 return IMD->getClassInterface();
1471
1472 return 0;
1473}
1474
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001475/// \brief Get the copy initialization expression of VarDecl,or NULL if
1476/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001477Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001478 assert(VD && "Passed null params");
1479 assert(VD->hasAttr<BlocksAttr>() &&
1480 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001481 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001482 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001483 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1484}
1485
1486/// \brief Set the copy inialization expression of a block var decl.
1487void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1488 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001489 assert(VD->hasAttr<BlocksAttr>() &&
1490 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001491 BlockVarCopyInits[VD] = Init;
1492}
1493
John McCallbcd03502009-12-07 02:54:59 +00001494TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001495 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001496 if (!DataSize)
1497 DataSize = TypeLoc::getFullDataSizeForType(T);
1498 else
1499 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001500 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001501
John McCallbcd03502009-12-07 02:54:59 +00001502 TypeSourceInfo *TInfo =
1503 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1504 new (TInfo) TypeSourceInfo(T);
1505 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001506}
1507
John McCallbcd03502009-12-07 02:54:59 +00001508TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001509 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001510 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001511 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001512 return DI;
1513}
1514
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001515const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001516ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001517 return getObjCLayout(D, 0);
1518}
1519
1520const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001521ASTContext::getASTObjCImplementationLayout(
1522 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001523 return getObjCLayout(D->getClassInterface(), D);
1524}
1525
Chris Lattner983a8bb2007-07-13 22:13:22 +00001526//===----------------------------------------------------------------------===//
1527// Type creation/memoization methods
1528//===----------------------------------------------------------------------===//
1529
Jay Foad39c79802011-01-12 09:06:06 +00001530QualType
John McCall33ddac02011-01-19 10:06:00 +00001531ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1532 unsigned fastQuals = quals.getFastQualifiers();
1533 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001534
1535 // Check if we've already instantiated this type.
1536 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001537 ExtQuals::Profile(ID, baseType, quals);
1538 void *insertPos = 0;
1539 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1540 assert(eq->getQualifiers() == quals);
1541 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001542 }
1543
John McCall33ddac02011-01-19 10:06:00 +00001544 // If the base type is not canonical, make the appropriate canonical type.
1545 QualType canon;
1546 if (!baseType->isCanonicalUnqualified()) {
1547 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001548 canonSplit.Quals.addConsistentQualifiers(quals);
1549 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001550
1551 // Re-find the insert position.
1552 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1553 }
1554
1555 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1556 ExtQualNodes.InsertNode(eq, insertPos);
1557 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001558}
1559
Jay Foad39c79802011-01-12 09:06:06 +00001560QualType
1561ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001562 QualType CanT = getCanonicalType(T);
1563 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001564 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001565
John McCall8ccfcb52009-09-24 19:53:00 +00001566 // If we are composing extended qualifiers together, merge together
1567 // into one ExtQuals node.
1568 QualifierCollector Quals;
1569 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001570
John McCall8ccfcb52009-09-24 19:53:00 +00001571 // If this type already has an address space specified, it cannot get
1572 // another one.
1573 assert(!Quals.hasAddressSpace() &&
1574 "Type cannot be in multiple addr spaces!");
1575 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001576
John McCall8ccfcb52009-09-24 19:53:00 +00001577 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001578}
1579
Chris Lattnerd60183d2009-02-18 22:53:11 +00001580QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001581 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001582 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001583 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001584 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001585
John McCall53fa7142010-12-24 02:08:15 +00001586 if (const PointerType *ptr = T->getAs<PointerType>()) {
1587 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001588 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001589 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1590 return getPointerType(ResultType);
1591 }
1592 }
Mike Stump11289f42009-09-09 15:08:12 +00001593
John McCall8ccfcb52009-09-24 19:53:00 +00001594 // If we are composing extended qualifiers together, merge together
1595 // into one ExtQuals node.
1596 QualifierCollector Quals;
1597 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001598
John McCall8ccfcb52009-09-24 19:53:00 +00001599 // If this type already has an ObjCGC specified, it cannot get
1600 // another one.
1601 assert(!Quals.hasObjCGCAttr() &&
1602 "Type cannot have multiple ObjCGCs!");
1603 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001604
John McCall8ccfcb52009-09-24 19:53:00 +00001605 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001606}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001607
John McCall4f5019e2010-12-19 02:44:49 +00001608const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1609 FunctionType::ExtInfo Info) {
1610 if (T->getExtInfo() == Info)
1611 return T;
1612
1613 QualType Result;
1614 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1615 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1616 } else {
1617 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1618 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1619 EPI.ExtInfo = Info;
1620 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1621 FPT->getNumArgs(), EPI);
1622 }
1623
1624 return cast<FunctionType>(Result.getTypePtr());
1625}
1626
Chris Lattnerc6395932007-06-22 20:56:16 +00001627/// getComplexType - Return the uniqued reference to the type for a complex
1628/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001629QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001630 // Unique pointers, to guarantee there is only one pointer of a particular
1631 // structure.
1632 llvm::FoldingSetNodeID ID;
1633 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001634
Chris Lattnerc6395932007-06-22 20:56:16 +00001635 void *InsertPos = 0;
1636 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1637 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001638
Chris Lattnerc6395932007-06-22 20:56:16 +00001639 // If the pointee type isn't canonical, this won't be a canonical type either,
1640 // so fill in the canonical type field.
1641 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001642 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001643 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001644
Chris Lattnerc6395932007-06-22 20:56:16 +00001645 // Get the new insert position for the node we care about.
1646 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001647 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001648 }
John McCall90d1c2d2009-09-24 23:30:46 +00001649 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001650 Types.push_back(New);
1651 ComplexTypes.InsertNode(New, InsertPos);
1652 return QualType(New, 0);
1653}
1654
Chris Lattner970e54e2006-11-12 00:37:36 +00001655/// getPointerType - Return the uniqued reference to the type for a pointer to
1656/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001657QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001658 // Unique pointers, to guarantee there is only one pointer of a particular
1659 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001660 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001661 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001662
Chris Lattner67521df2007-01-27 01:29:36 +00001663 void *InsertPos = 0;
1664 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001665 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001666
Chris Lattner7ccecb92006-11-12 08:50:50 +00001667 // If the pointee type isn't canonical, this won't be a canonical type either,
1668 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001669 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001670 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001671 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001672
Chris Lattner67521df2007-01-27 01:29:36 +00001673 // Get the new insert position for the node we care about.
1674 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001675 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001676 }
John McCall90d1c2d2009-09-24 23:30:46 +00001677 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001678 Types.push_back(New);
1679 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001680 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001681}
1682
Mike Stump11289f42009-09-09 15:08:12 +00001683/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001684/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001685QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001686 assert(T->isFunctionType() && "block of function types only");
1687 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001688 // structure.
1689 llvm::FoldingSetNodeID ID;
1690 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001691
Steve Naroffec33ed92008-08-27 16:04:49 +00001692 void *InsertPos = 0;
1693 if (BlockPointerType *PT =
1694 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1695 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001696
1697 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001698 // type either so fill in the canonical type field.
1699 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001700 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001701 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001702
Steve Naroffec33ed92008-08-27 16:04:49 +00001703 // Get the new insert position for the node we care about.
1704 BlockPointerType *NewIP =
1705 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001706 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001707 }
John McCall90d1c2d2009-09-24 23:30:46 +00001708 BlockPointerType *New
1709 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001710 Types.push_back(New);
1711 BlockPointerTypes.InsertNode(New, InsertPos);
1712 return QualType(New, 0);
1713}
1714
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001715/// getLValueReferenceType - Return the uniqued reference to the type for an
1716/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001717QualType
1718ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001719 assert(getCanonicalType(T) != OverloadTy &&
1720 "Unresolved overloaded function type");
1721
Bill Wendling3708c182007-05-27 10:15:43 +00001722 // Unique pointers, to guarantee there is only one pointer of a particular
1723 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001724 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001725 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001726
1727 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001728 if (LValueReferenceType *RT =
1729 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001730 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001731
John McCallfc93cf92009-10-22 22:37:11 +00001732 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1733
Bill Wendling3708c182007-05-27 10:15:43 +00001734 // If the referencee type isn't canonical, this won't be a canonical type
1735 // either, so fill in the canonical type field.
1736 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001737 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1738 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1739 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001740
Bill Wendling3708c182007-05-27 10:15:43 +00001741 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001742 LValueReferenceType *NewIP =
1743 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001744 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001745 }
1746
John McCall90d1c2d2009-09-24 23:30:46 +00001747 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001748 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1749 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001750 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001751 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001752
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001753 return QualType(New, 0);
1754}
1755
1756/// getRValueReferenceType - Return the uniqued reference to the type for an
1757/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001758QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001759 // Unique pointers, to guarantee there is only one pointer of a particular
1760 // structure.
1761 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001762 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001763
1764 void *InsertPos = 0;
1765 if (RValueReferenceType *RT =
1766 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1767 return QualType(RT, 0);
1768
John McCallfc93cf92009-10-22 22:37:11 +00001769 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1770
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001771 // If the referencee type isn't canonical, this won't be a canonical type
1772 // either, so fill in the canonical type field.
1773 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001774 if (InnerRef || !T.isCanonical()) {
1775 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1776 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001777
1778 // Get the new insert position for the node we care about.
1779 RValueReferenceType *NewIP =
1780 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001781 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001782 }
1783
John McCall90d1c2d2009-09-24 23:30:46 +00001784 RValueReferenceType *New
1785 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001786 Types.push_back(New);
1787 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001788 return QualType(New, 0);
1789}
1790
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001791/// getMemberPointerType - Return the uniqued reference to the type for a
1792/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001793QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001794 // Unique pointers, to guarantee there is only one pointer of a particular
1795 // structure.
1796 llvm::FoldingSetNodeID ID;
1797 MemberPointerType::Profile(ID, T, Cls);
1798
1799 void *InsertPos = 0;
1800 if (MemberPointerType *PT =
1801 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1802 return QualType(PT, 0);
1803
1804 // If the pointee or class type isn't canonical, this won't be a canonical
1805 // type either, so fill in the canonical type field.
1806 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001807 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001808 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1809
1810 // Get the new insert position for the node we care about.
1811 MemberPointerType *NewIP =
1812 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001813 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001814 }
John McCall90d1c2d2009-09-24 23:30:46 +00001815 MemberPointerType *New
1816 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001817 Types.push_back(New);
1818 MemberPointerTypes.InsertNode(New, InsertPos);
1819 return QualType(New, 0);
1820}
1821
Mike Stump11289f42009-09-09 15:08:12 +00001822/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001823/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001824QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001825 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001826 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001827 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001828 assert((EltTy->isDependentType() ||
1829 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001830 "Constant array of VLAs is illegal!");
1831
Chris Lattnere2df3f92009-05-13 04:12:56 +00001832 // Convert the array size into a canonical width matching the pointer size for
1833 // the target.
1834 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001835 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001836 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001837
Chris Lattner23b7eb62007-06-15 23:05:46 +00001838 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001839 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001840
Chris Lattner36f8e652007-01-27 08:31:04 +00001841 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001842 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001843 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001844 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001845
John McCall33ddac02011-01-19 10:06:00 +00001846 // If the element type isn't canonical or has qualifiers, this won't
1847 // be a canonical type either, so fill in the canonical type field.
1848 QualType Canon;
1849 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1850 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001851 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001852 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001853 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001854
Chris Lattner36f8e652007-01-27 08:31:04 +00001855 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001856 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001857 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001858 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001859 }
Mike Stump11289f42009-09-09 15:08:12 +00001860
John McCall90d1c2d2009-09-24 23:30:46 +00001861 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001862 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001863 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001864 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001865 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001866}
1867
John McCall06549462011-01-18 08:40:38 +00001868/// getVariableArrayDecayedType - Turns the given type, which may be
1869/// variably-modified, into the corresponding type with all the known
1870/// sizes replaced with [*].
1871QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1872 // Vastly most common case.
1873 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001874
John McCall06549462011-01-18 08:40:38 +00001875 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001876
John McCall06549462011-01-18 08:40:38 +00001877 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001878 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001879 switch (ty->getTypeClass()) {
1880#define TYPE(Class, Base)
1881#define ABSTRACT_TYPE(Class, Base)
1882#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1883#include "clang/AST/TypeNodes.def"
1884 llvm_unreachable("didn't desugar past all non-canonical types?");
1885
1886 // These types should never be variably-modified.
1887 case Type::Builtin:
1888 case Type::Complex:
1889 case Type::Vector:
1890 case Type::ExtVector:
1891 case Type::DependentSizedExtVector:
1892 case Type::ObjCObject:
1893 case Type::ObjCInterface:
1894 case Type::ObjCObjectPointer:
1895 case Type::Record:
1896 case Type::Enum:
1897 case Type::UnresolvedUsing:
1898 case Type::TypeOfExpr:
1899 case Type::TypeOf:
1900 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001901 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001902 case Type::DependentName:
1903 case Type::InjectedClassName:
1904 case Type::TemplateSpecialization:
1905 case Type::DependentTemplateSpecialization:
1906 case Type::TemplateTypeParm:
1907 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001908 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001909 case Type::PackExpansion:
1910 llvm_unreachable("type should never be variably-modified");
1911
1912 // These types can be variably-modified but should never need to
1913 // further decay.
1914 case Type::FunctionNoProto:
1915 case Type::FunctionProto:
1916 case Type::BlockPointer:
1917 case Type::MemberPointer:
1918 return type;
1919
1920 // These types can be variably-modified. All these modifications
1921 // preserve structure except as noted by comments.
1922 // TODO: if we ever care about optimizing VLAs, there are no-op
1923 // optimizations available here.
1924 case Type::Pointer:
1925 result = getPointerType(getVariableArrayDecayedType(
1926 cast<PointerType>(ty)->getPointeeType()));
1927 break;
1928
1929 case Type::LValueReference: {
1930 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1931 result = getLValueReferenceType(
1932 getVariableArrayDecayedType(lv->getPointeeType()),
1933 lv->isSpelledAsLValue());
1934 break;
1935 }
1936
1937 case Type::RValueReference: {
1938 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1939 result = getRValueReferenceType(
1940 getVariableArrayDecayedType(lv->getPointeeType()));
1941 break;
1942 }
1943
Eli Friedman0dfb8892011-10-06 23:00:33 +00001944 case Type::Atomic: {
1945 const AtomicType *at = cast<AtomicType>(ty);
1946 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1947 break;
1948 }
1949
John McCall06549462011-01-18 08:40:38 +00001950 case Type::ConstantArray: {
1951 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1952 result = getConstantArrayType(
1953 getVariableArrayDecayedType(cat->getElementType()),
1954 cat->getSize(),
1955 cat->getSizeModifier(),
1956 cat->getIndexTypeCVRQualifiers());
1957 break;
1958 }
1959
1960 case Type::DependentSizedArray: {
1961 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1962 result = getDependentSizedArrayType(
1963 getVariableArrayDecayedType(dat->getElementType()),
1964 dat->getSizeExpr(),
1965 dat->getSizeModifier(),
1966 dat->getIndexTypeCVRQualifiers(),
1967 dat->getBracketsRange());
1968 break;
1969 }
1970
1971 // Turn incomplete types into [*] types.
1972 case Type::IncompleteArray: {
1973 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1974 result = getVariableArrayType(
1975 getVariableArrayDecayedType(iat->getElementType()),
1976 /*size*/ 0,
1977 ArrayType::Normal,
1978 iat->getIndexTypeCVRQualifiers(),
1979 SourceRange());
1980 break;
1981 }
1982
1983 // Turn VLA types into [*] types.
1984 case Type::VariableArray: {
1985 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1986 result = getVariableArrayType(
1987 getVariableArrayDecayedType(vat->getElementType()),
1988 /*size*/ 0,
1989 ArrayType::Star,
1990 vat->getIndexTypeCVRQualifiers(),
1991 vat->getBracketsRange());
1992 break;
1993 }
1994 }
1995
1996 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00001997 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00001998}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001999
Steve Naroffcadebd02007-08-30 18:14:25 +00002000/// getVariableArrayType - Returns a non-unique reference to the type for a
2001/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002002QualType ASTContext::getVariableArrayType(QualType EltTy,
2003 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002004 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002005 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002006 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002007 // Since we don't unique expressions, it isn't possible to unique VLA's
2008 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002009 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002010
John McCall33ddac02011-01-19 10:06:00 +00002011 // Be sure to pull qualifiers off the element type.
2012 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2013 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002014 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002015 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002016 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002017 }
2018
John McCall90d1c2d2009-09-24 23:30:46 +00002019 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002020 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002021
2022 VariableArrayTypes.push_back(New);
2023 Types.push_back(New);
2024 return QualType(New, 0);
2025}
2026
Douglas Gregor4619e432008-12-05 23:32:09 +00002027/// getDependentSizedArrayType - Returns a non-unique reference to
2028/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002029/// type.
John McCall33ddac02011-01-19 10:06:00 +00002030QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2031 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002032 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002033 unsigned elementTypeQuals,
2034 SourceRange brackets) const {
2035 assert((!numElements || numElements->isTypeDependent() ||
2036 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002037 "Size must be type- or value-dependent!");
2038
John McCall33ddac02011-01-19 10:06:00 +00002039 // Dependently-sized array types that do not have a specified number
2040 // of elements will have their sizes deduced from a dependent
2041 // initializer. We do no canonicalization here at all, which is okay
2042 // because they can't be used in most locations.
2043 if (!numElements) {
2044 DependentSizedArrayType *newType
2045 = new (*this, TypeAlignment)
2046 DependentSizedArrayType(*this, elementType, QualType(),
2047 numElements, ASM, elementTypeQuals,
2048 brackets);
2049 Types.push_back(newType);
2050 return QualType(newType, 0);
2051 }
2052
2053 // Otherwise, we actually build a new type every time, but we
2054 // also build a canonical type.
2055
2056 SplitQualType canonElementType = getCanonicalType(elementType).split();
2057
2058 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002059 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002060 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002061 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002062 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002063
John McCall33ddac02011-01-19 10:06:00 +00002064 // Look for an existing type with these properties.
2065 DependentSizedArrayType *canonTy =
2066 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002067
John McCall33ddac02011-01-19 10:06:00 +00002068 // If we don't have one, build one.
2069 if (!canonTy) {
2070 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002071 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002072 QualType(), numElements, ASM, elementTypeQuals,
2073 brackets);
2074 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2075 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002076 }
2077
John McCall33ddac02011-01-19 10:06:00 +00002078 // Apply qualifiers from the element type to the array.
2079 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002080 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002081
John McCall33ddac02011-01-19 10:06:00 +00002082 // If we didn't need extra canonicalization for the element type,
2083 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002084 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002085 return canon;
2086
2087 // Otherwise, we need to build a type which follows the spelling
2088 // of the element type.
2089 DependentSizedArrayType *sugaredType
2090 = new (*this, TypeAlignment)
2091 DependentSizedArrayType(*this, elementType, canon, numElements,
2092 ASM, elementTypeQuals, brackets);
2093 Types.push_back(sugaredType);
2094 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002095}
2096
John McCall33ddac02011-01-19 10:06:00 +00002097QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002098 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002099 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002100 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002101 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002102
John McCall33ddac02011-01-19 10:06:00 +00002103 void *insertPos = 0;
2104 if (IncompleteArrayType *iat =
2105 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2106 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002107
2108 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002109 // either, so fill in the canonical type field. We also have to pull
2110 // qualifiers off the element type.
2111 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002112
John McCall33ddac02011-01-19 10:06:00 +00002113 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2114 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002115 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002116 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002117 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002118
2119 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002120 IncompleteArrayType *existing =
2121 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2122 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002123 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002124
John McCall33ddac02011-01-19 10:06:00 +00002125 IncompleteArrayType *newType = new (*this, TypeAlignment)
2126 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002127
John McCall33ddac02011-01-19 10:06:00 +00002128 IncompleteArrayTypes.InsertNode(newType, insertPos);
2129 Types.push_back(newType);
2130 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002131}
2132
Steve Naroff91fcddb2007-07-18 18:00:27 +00002133/// getVectorType - Return the unique reference to a vector type of
2134/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002135QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002136 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002137 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002138
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002139 // Check if we've already instantiated a vector of this type.
2140 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002141 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002142
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002143 void *InsertPos = 0;
2144 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2145 return QualType(VTP, 0);
2146
2147 // If the element type isn't canonical, this won't be a canonical type either,
2148 // so fill in the canonical type field.
2149 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002150 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002151 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002152
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002153 // Get the new insert position for the node we care about.
2154 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002155 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002156 }
John McCall90d1c2d2009-09-24 23:30:46 +00002157 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002158 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002159 VectorTypes.InsertNode(New, InsertPos);
2160 Types.push_back(New);
2161 return QualType(New, 0);
2162}
2163
Nate Begemance4d7fc2008-04-18 23:10:10 +00002164/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002165/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002166QualType
2167ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002168 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002169
Steve Naroff91fcddb2007-07-18 18:00:27 +00002170 // Check if we've already instantiated a vector of this type.
2171 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002172 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002173 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002174 void *InsertPos = 0;
2175 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2176 return QualType(VTP, 0);
2177
2178 // If the element type isn't canonical, this won't be a canonical type either,
2179 // so fill in the canonical type field.
2180 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002181 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002182 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002183
Steve Naroff91fcddb2007-07-18 18:00:27 +00002184 // Get the new insert position for the node we care about.
2185 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002186 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002187 }
John McCall90d1c2d2009-09-24 23:30:46 +00002188 ExtVectorType *New = new (*this, TypeAlignment)
2189 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002190 VectorTypes.InsertNode(New, InsertPos);
2191 Types.push_back(New);
2192 return QualType(New, 0);
2193}
2194
Jay Foad39c79802011-01-12 09:06:06 +00002195QualType
2196ASTContext::getDependentSizedExtVectorType(QualType vecType,
2197 Expr *SizeExpr,
2198 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002199 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002200 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002201 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002202
Douglas Gregor352169a2009-07-31 03:54:25 +00002203 void *InsertPos = 0;
2204 DependentSizedExtVectorType *Canon
2205 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2206 DependentSizedExtVectorType *New;
2207 if (Canon) {
2208 // We already have a canonical version of this array type; use it as
2209 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002210 New = new (*this, TypeAlignment)
2211 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2212 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002213 } else {
2214 QualType CanonVecTy = getCanonicalType(vecType);
2215 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002216 New = new (*this, TypeAlignment)
2217 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2218 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002219
2220 DependentSizedExtVectorType *CanonCheck
2221 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2222 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2223 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002224 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2225 } else {
2226 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2227 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002228 New = new (*this, TypeAlignment)
2229 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002230 }
2231 }
Mike Stump11289f42009-09-09 15:08:12 +00002232
Douglas Gregor758a8692009-06-17 21:51:59 +00002233 Types.push_back(New);
2234 return QualType(New, 0);
2235}
2236
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002237/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002238///
Jay Foad39c79802011-01-12 09:06:06 +00002239QualType
2240ASTContext::getFunctionNoProtoType(QualType ResultTy,
2241 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002242 const CallingConv DefaultCC = Info.getCC();
2243 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2244 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002245 // Unique functions, to guarantee there is only one function of a particular
2246 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002247 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002248 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002249
Chris Lattner47955de2007-01-27 08:37:20 +00002250 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002251 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002252 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002253 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002254
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002255 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002256 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002257 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002258 Canonical =
2259 getFunctionNoProtoType(getCanonicalType(ResultTy),
2260 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002261
Chris Lattner47955de2007-01-27 08:37:20 +00002262 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002263 FunctionNoProtoType *NewIP =
2264 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002265 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002266 }
Mike Stump11289f42009-09-09 15:08:12 +00002267
Roman Divacky65b88cd2011-03-01 17:40:53 +00002268 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002269 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002270 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002271 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002272 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002273 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002274}
2275
2276/// getFunctionType - Return a normal function type with a typed argument
2277/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002278QualType
2279ASTContext::getFunctionType(QualType ResultTy,
2280 const QualType *ArgArray, unsigned NumArgs,
2281 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002282 // Unique functions, to guarantee there is only one function of a particular
2283 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002284 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002285 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002286
2287 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002288 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002289 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002290 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002291
2292 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002293 bool isCanonical =
2294 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2295 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002296 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002297 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002298 isCanonical = false;
2299
Roman Divacky65b88cd2011-03-01 17:40:53 +00002300 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2301 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2302 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002303
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002304 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002305 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002306 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002307 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002308 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002309 CanonicalArgs.reserve(NumArgs);
2310 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002311 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002312
John McCalldb40c7f2010-12-14 08:05:40 +00002313 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002314 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002315 CanonicalEPI.ExceptionSpecType = EST_None;
2316 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002317 CanonicalEPI.ExtInfo
2318 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2319
Chris Lattner76a00cf2008-04-06 22:59:24 +00002320 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002321 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002322 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002323
Chris Lattnerfd4de792007-01-27 01:15:32 +00002324 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002325 FunctionProtoType *NewIP =
2326 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002327 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002328 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002329
John McCall31168b02011-06-15 23:02:42 +00002330 // FunctionProtoType objects are allocated with extra bytes after
2331 // them for three variable size arrays at the end:
2332 // - parameter types
2333 // - exception types
2334 // - consumed-arguments flags
2335 // Instead of the exception types, there could be a noexcept
2336 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002337 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002338 NumArgs * sizeof(QualType);
2339 if (EPI.ExceptionSpecType == EST_Dynamic)
2340 Size += EPI.NumExceptions * sizeof(QualType);
2341 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002342 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002343 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002344 Size += 2 * sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002345 }
John McCall31168b02011-06-15 23:02:42 +00002346 if (EPI.ConsumedArguments)
2347 Size += NumArgs * sizeof(bool);
2348
John McCalldb40c7f2010-12-14 08:05:40 +00002349 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002350 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2351 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002352 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002353 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002354 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002355 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002356}
Chris Lattneref51c202006-11-10 07:17:23 +00002357
John McCalle78aac42010-03-10 03:28:59 +00002358#ifndef NDEBUG
2359static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2360 if (!isa<CXXRecordDecl>(D)) return false;
2361 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2362 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2363 return true;
2364 if (RD->getDescribedClassTemplate() &&
2365 !isa<ClassTemplateSpecializationDecl>(RD))
2366 return true;
2367 return false;
2368}
2369#endif
2370
2371/// getInjectedClassNameType - Return the unique reference to the
2372/// injected class name type for the specified templated declaration.
2373QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002374 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002375 assert(NeedsInjectedClassNameType(Decl));
2376 if (Decl->TypeForDecl) {
2377 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002378 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002379 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2380 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2381 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2382 } else {
John McCall424cec92011-01-19 06:33:43 +00002383 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002384 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002385 Decl->TypeForDecl = newType;
2386 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002387 }
2388 return QualType(Decl->TypeForDecl, 0);
2389}
2390
Douglas Gregor83a586e2008-04-13 21:07:44 +00002391/// getTypeDeclType - Return the unique reference to the type for the
2392/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002393QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002394 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002395 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002396
Richard Smithdda56e42011-04-15 14:24:37 +00002397 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002398 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002399
John McCall96f0b5f2010-03-10 06:48:02 +00002400 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2401 "Template type parameter types are always available.");
2402
John McCall81e38502010-02-16 03:57:14 +00002403 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002404 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002405 "struct/union has previous declaration");
2406 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002407 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002408 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002409 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002410 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002411 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002412 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002413 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002414 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2415 Decl->TypeForDecl = newType;
2416 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002417 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002418 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002419
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002420 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002421}
2422
Chris Lattner32d920b2007-01-26 02:01:53 +00002423/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002424/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002425QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002426ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2427 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002428 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002429
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002430 if (Canonical.isNull())
2431 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002432 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002433 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002434 Decl->TypeForDecl = newType;
2435 Types.push_back(newType);
2436 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002437}
2438
Jay Foad39c79802011-01-12 09:06:06 +00002439QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002440 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2441
Douglas Gregorec9fd132012-01-14 16:38:05 +00002442 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002443 if (PrevDecl->TypeForDecl)
2444 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2445
John McCall424cec92011-01-19 06:33:43 +00002446 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2447 Decl->TypeForDecl = newType;
2448 Types.push_back(newType);
2449 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002450}
2451
Jay Foad39c79802011-01-12 09:06:06 +00002452QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002453 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2454
Douglas Gregorec9fd132012-01-14 16:38:05 +00002455 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002456 if (PrevDecl->TypeForDecl)
2457 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2458
John McCall424cec92011-01-19 06:33:43 +00002459 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2460 Decl->TypeForDecl = newType;
2461 Types.push_back(newType);
2462 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002463}
2464
John McCall81904512011-01-06 01:58:22 +00002465QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2466 QualType modifiedType,
2467 QualType equivalentType) {
2468 llvm::FoldingSetNodeID id;
2469 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2470
2471 void *insertPos = 0;
2472 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2473 if (type) return QualType(type, 0);
2474
2475 QualType canon = getCanonicalType(equivalentType);
2476 type = new (*this, TypeAlignment)
2477 AttributedType(canon, attrKind, modifiedType, equivalentType);
2478
2479 Types.push_back(type);
2480 AttributedTypes.InsertNode(type, insertPos);
2481
2482 return QualType(type, 0);
2483}
2484
2485
John McCallcebee162009-10-18 09:09:24 +00002486/// \brief Retrieve a substitution-result type.
2487QualType
2488ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002489 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002490 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002491 && "replacement types must always be canonical");
2492
2493 llvm::FoldingSetNodeID ID;
2494 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2495 void *InsertPos = 0;
2496 SubstTemplateTypeParmType *SubstParm
2497 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2498
2499 if (!SubstParm) {
2500 SubstParm = new (*this, TypeAlignment)
2501 SubstTemplateTypeParmType(Parm, Replacement);
2502 Types.push_back(SubstParm);
2503 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2504 }
2505
2506 return QualType(SubstParm, 0);
2507}
2508
Douglas Gregorada4b792011-01-14 02:55:32 +00002509/// \brief Retrieve a
2510QualType ASTContext::getSubstTemplateTypeParmPackType(
2511 const TemplateTypeParmType *Parm,
2512 const TemplateArgument &ArgPack) {
2513#ifndef NDEBUG
2514 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2515 PEnd = ArgPack.pack_end();
2516 P != PEnd; ++P) {
2517 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2518 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2519 }
2520#endif
2521
2522 llvm::FoldingSetNodeID ID;
2523 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2524 void *InsertPos = 0;
2525 if (SubstTemplateTypeParmPackType *SubstParm
2526 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2527 return QualType(SubstParm, 0);
2528
2529 QualType Canon;
2530 if (!Parm->isCanonicalUnqualified()) {
2531 Canon = getCanonicalType(QualType(Parm, 0));
2532 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2533 ArgPack);
2534 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2535 }
2536
2537 SubstTemplateTypeParmPackType *SubstParm
2538 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2539 ArgPack);
2540 Types.push_back(SubstParm);
2541 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2542 return QualType(SubstParm, 0);
2543}
2544
Douglas Gregoreff93e02009-02-05 23:33:38 +00002545/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002546/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002547/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002548QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002549 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002550 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002551 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002552 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002553 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002554 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002555 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2556
2557 if (TypeParm)
2558 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002559
Chandler Carruth08836322011-05-01 00:51:33 +00002560 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002561 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002562 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002563
2564 TemplateTypeParmType *TypeCheck
2565 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2566 assert(!TypeCheck && "Template type parameter canonical type broken");
2567 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002568 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002569 TypeParm = new (*this, TypeAlignment)
2570 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002571
2572 Types.push_back(TypeParm);
2573 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2574
2575 return QualType(TypeParm, 0);
2576}
2577
John McCalle78aac42010-03-10 03:28:59 +00002578TypeSourceInfo *
2579ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2580 SourceLocation NameLoc,
2581 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002582 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002583 assert(!Name.getAsDependentTemplateName() &&
2584 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002585 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002586
2587 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2588 TemplateSpecializationTypeLoc TL
2589 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002590 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002591 TL.setTemplateNameLoc(NameLoc);
2592 TL.setLAngleLoc(Args.getLAngleLoc());
2593 TL.setRAngleLoc(Args.getRAngleLoc());
2594 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2595 TL.setArgLocInfo(i, Args[i].getLocInfo());
2596 return DI;
2597}
2598
Mike Stump11289f42009-09-09 15:08:12 +00002599QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002600ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002601 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002602 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002603 assert(!Template.getAsDependentTemplateName() &&
2604 "No dependent template names here!");
2605
John McCall6b51f282009-11-23 01:53:49 +00002606 unsigned NumArgs = Args.size();
2607
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002608 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002609 ArgVec.reserve(NumArgs);
2610 for (unsigned i = 0; i != NumArgs; ++i)
2611 ArgVec.push_back(Args[i].getArgument());
2612
John McCall2408e322010-04-27 00:57:59 +00002613 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002614 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002615}
2616
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002617#ifndef NDEBUG
2618static bool hasAnyPackExpansions(const TemplateArgument *Args,
2619 unsigned NumArgs) {
2620 for (unsigned I = 0; I != NumArgs; ++I)
2621 if (Args[I].isPackExpansion())
2622 return true;
2623
2624 return true;
2625}
2626#endif
2627
John McCall0ad16662009-10-29 08:12:44 +00002628QualType
2629ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002630 const TemplateArgument *Args,
2631 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002632 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002633 assert(!Template.getAsDependentTemplateName() &&
2634 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002635 // Look through qualified template names.
2636 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2637 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002638
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002639 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002640 Template.getAsTemplateDecl() &&
2641 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002642 QualType CanonType;
2643 if (!Underlying.isNull())
2644 CanonType = getCanonicalType(Underlying);
2645 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002646 // We can get here with an alias template when the specialization contains
2647 // a pack expansion that does not match up with a parameter pack.
2648 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2649 "Caller must compute aliased type");
2650 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002651 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2652 NumArgs);
2653 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002654
Douglas Gregora8e02e72009-07-28 23:00:59 +00002655 // Allocate the (non-canonical) template specialization type, but don't
2656 // try to unique it: these types typically have location information that
2657 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002658 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2659 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002660 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002661 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002662 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002663 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2664 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002665
Douglas Gregor8bf42052009-02-09 18:46:07 +00002666 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002667 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002668}
2669
Mike Stump11289f42009-09-09 15:08:12 +00002670QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002671ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2672 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002673 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002674 assert(!Template.getAsDependentTemplateName() &&
2675 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002676
Douglas Gregore29139c2011-03-03 17:04:51 +00002677 // Look through qualified template names.
2678 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2679 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002680
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002681 // Build the canonical template specialization type.
2682 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002683 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002684 CanonArgs.reserve(NumArgs);
2685 for (unsigned I = 0; I != NumArgs; ++I)
2686 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2687
2688 // Determine whether this canonical template specialization type already
2689 // exists.
2690 llvm::FoldingSetNodeID ID;
2691 TemplateSpecializationType::Profile(ID, CanonTemplate,
2692 CanonArgs.data(), NumArgs, *this);
2693
2694 void *InsertPos = 0;
2695 TemplateSpecializationType *Spec
2696 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2697
2698 if (!Spec) {
2699 // Allocate a new canonical template specialization type.
2700 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2701 sizeof(TemplateArgument) * NumArgs),
2702 TypeAlignment);
2703 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2704 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002705 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002706 Types.push_back(Spec);
2707 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2708 }
2709
2710 assert(Spec->isDependentType() &&
2711 "Non-dependent template-id type must have a canonical type");
2712 return QualType(Spec, 0);
2713}
2714
2715QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002716ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2717 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002718 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002719 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002720 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002721
2722 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002723 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002724 if (T)
2725 return QualType(T, 0);
2726
Douglas Gregorc42075a2010-02-04 18:10:26 +00002727 QualType Canon = NamedType;
2728 if (!Canon.isCanonical()) {
2729 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002730 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2731 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002732 (void)CheckT;
2733 }
2734
Abramo Bagnara6150c882010-05-11 21:36:43 +00002735 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002736 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002737 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002738 return QualType(T, 0);
2739}
2740
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002741QualType
Jay Foad39c79802011-01-12 09:06:06 +00002742ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002743 llvm::FoldingSetNodeID ID;
2744 ParenType::Profile(ID, InnerType);
2745
2746 void *InsertPos = 0;
2747 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2748 if (T)
2749 return QualType(T, 0);
2750
2751 QualType Canon = InnerType;
2752 if (!Canon.isCanonical()) {
2753 Canon = getCanonicalType(InnerType);
2754 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2755 assert(!CheckT && "Paren canonical type broken");
2756 (void)CheckT;
2757 }
2758
2759 T = new (*this) ParenType(InnerType, Canon);
2760 Types.push_back(T);
2761 ParenTypes.InsertNode(T, InsertPos);
2762 return QualType(T, 0);
2763}
2764
Douglas Gregor02085352010-03-31 20:19:30 +00002765QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2766 NestedNameSpecifier *NNS,
2767 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002768 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002769 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2770
2771 if (Canon.isNull()) {
2772 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002773 ElaboratedTypeKeyword CanonKeyword = Keyword;
2774 if (Keyword == ETK_None)
2775 CanonKeyword = ETK_Typename;
2776
2777 if (CanonNNS != NNS || CanonKeyword != Keyword)
2778 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002779 }
2780
2781 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002782 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002783
2784 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002785 DependentNameType *T
2786 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002787 if (T)
2788 return QualType(T, 0);
2789
Douglas Gregor02085352010-03-31 20:19:30 +00002790 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002791 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002792 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002793 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002794}
2795
Mike Stump11289f42009-09-09 15:08:12 +00002796QualType
John McCallc392f372010-06-11 00:33:02 +00002797ASTContext::getDependentTemplateSpecializationType(
2798 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002799 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002800 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002801 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002802 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002803 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002804 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2805 ArgCopy.push_back(Args[I].getArgument());
2806 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2807 ArgCopy.size(),
2808 ArgCopy.data());
2809}
2810
2811QualType
2812ASTContext::getDependentTemplateSpecializationType(
2813 ElaboratedTypeKeyword Keyword,
2814 NestedNameSpecifier *NNS,
2815 const IdentifierInfo *Name,
2816 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002817 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002818 assert((!NNS || NNS->isDependent()) &&
2819 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002820
Douglas Gregorc42075a2010-02-04 18:10:26 +00002821 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002822 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2823 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002824
2825 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002826 DependentTemplateSpecializationType *T
2827 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002828 if (T)
2829 return QualType(T, 0);
2830
John McCallc392f372010-06-11 00:33:02 +00002831 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002832
John McCallc392f372010-06-11 00:33:02 +00002833 ElaboratedTypeKeyword CanonKeyword = Keyword;
2834 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2835
2836 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002837 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002838 for (unsigned I = 0; I != NumArgs; ++I) {
2839 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2840 if (!CanonArgs[I].structurallyEquals(Args[I]))
2841 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002842 }
2843
John McCallc392f372010-06-11 00:33:02 +00002844 QualType Canon;
2845 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2846 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2847 Name, NumArgs,
2848 CanonArgs.data());
2849
2850 // Find the insert position again.
2851 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2852 }
2853
2854 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2855 sizeof(TemplateArgument) * NumArgs),
2856 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002857 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002858 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002859 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002860 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002861 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002862}
2863
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002864QualType ASTContext::getPackExpansionType(QualType Pattern,
2865 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002866 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002867 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002868
2869 assert(Pattern->containsUnexpandedParameterPack() &&
2870 "Pack expansions must expand one or more parameter packs");
2871 void *InsertPos = 0;
2872 PackExpansionType *T
2873 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2874 if (T)
2875 return QualType(T, 0);
2876
2877 QualType Canon;
2878 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002879 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002880
2881 // Find the insert position again.
2882 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2883 }
2884
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002885 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002886 Types.push_back(T);
2887 PackExpansionTypes.InsertNode(T, InsertPos);
2888 return QualType(T, 0);
2889}
2890
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002891/// CmpProtocolNames - Comparison predicate for sorting protocols
2892/// alphabetically.
2893static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2894 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002895 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002896}
2897
John McCall8b07ec22010-05-15 11:32:37 +00002898static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002899 unsigned NumProtocols) {
2900 if (NumProtocols == 0) return true;
2901
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002902 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2903 return false;
2904
John McCallfc93cf92009-10-22 22:37:11 +00002905 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002906 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2907 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002908 return false;
2909 return true;
2910}
2911
2912static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002913 unsigned &NumProtocols) {
2914 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002915
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002916 // Sort protocols, keyed by name.
2917 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2918
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002919 // Canonicalize.
2920 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2921 Protocols[I] = Protocols[I]->getCanonicalDecl();
2922
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002923 // Remove duplicates.
2924 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2925 NumProtocols = ProtocolsEnd-Protocols;
2926}
2927
John McCall8b07ec22010-05-15 11:32:37 +00002928QualType ASTContext::getObjCObjectType(QualType BaseType,
2929 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002930 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002931 // If the base type is an interface and there aren't any protocols
2932 // to add, then the interface type will do just fine.
2933 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2934 return BaseType;
2935
2936 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002937 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002938 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002939 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002940 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2941 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002942
John McCall8b07ec22010-05-15 11:32:37 +00002943 // Build the canonical type, which has the canonical base type and
2944 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002945 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002946 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2947 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2948 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002949 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002950 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002951 unsigned UniqueCount = NumProtocols;
2952
John McCallfc93cf92009-10-22 22:37:11 +00002953 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002954 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2955 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002956 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002957 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2958 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002959 }
2960
2961 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002962 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2963 }
2964
2965 unsigned Size = sizeof(ObjCObjectTypeImpl);
2966 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2967 void *Mem = Allocate(Size, TypeAlignment);
2968 ObjCObjectTypeImpl *T =
2969 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2970
2971 Types.push_back(T);
2972 ObjCObjectTypes.InsertNode(T, InsertPos);
2973 return QualType(T, 0);
2974}
2975
2976/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2977/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002978QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002979 llvm::FoldingSetNodeID ID;
2980 ObjCObjectPointerType::Profile(ID, ObjectT);
2981
2982 void *InsertPos = 0;
2983 if (ObjCObjectPointerType *QT =
2984 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2985 return QualType(QT, 0);
2986
2987 // Find the canonical object type.
2988 QualType Canonical;
2989 if (!ObjectT.isCanonical()) {
2990 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2991
2992 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002993 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2994 }
2995
Douglas Gregorf85bee62010-02-08 22:59:26 +00002996 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002997 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2998 ObjCObjectPointerType *QType =
2999 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003000
Steve Narofffb4330f2009-06-17 22:40:22 +00003001 Types.push_back(QType);
3002 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003003 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003004}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003005
Douglas Gregor1c283312010-08-11 12:19:30 +00003006/// getObjCInterfaceType - Return the unique reference to the type for the
3007/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003008QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3009 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003010 if (Decl->TypeForDecl)
3011 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003012
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003013 if (PrevDecl) {
3014 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3015 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3016 return QualType(PrevDecl->TypeForDecl, 0);
3017 }
3018
Douglas Gregor7671e532011-12-16 16:34:57 +00003019 // Prefer the definition, if there is one.
3020 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3021 Decl = Def;
3022
Douglas Gregor1c283312010-08-11 12:19:30 +00003023 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3024 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3025 Decl->TypeForDecl = T;
3026 Types.push_back(T);
3027 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003028}
3029
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003030/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3031/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003032/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003033/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003034/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003035QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003036 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003037 if (tofExpr->isTypeDependent()) {
3038 llvm::FoldingSetNodeID ID;
3039 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003040
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003041 void *InsertPos = 0;
3042 DependentTypeOfExprType *Canon
3043 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3044 if (Canon) {
3045 // We already have a "canonical" version of an identical, dependent
3046 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003047 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003048 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003049 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003050 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003051 Canon
3052 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003053 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3054 toe = Canon;
3055 }
3056 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003057 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003058 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003059 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003060 Types.push_back(toe);
3061 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003062}
3063
Steve Naroffa773cd52007-08-01 18:02:17 +00003064/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3065/// TypeOfType AST's. The only motivation to unique these nodes would be
3066/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003067/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003068/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003069QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003070 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003071 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003072 Types.push_back(tot);
3073 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003074}
3075
Anders Carlssonad6bd352009-06-24 21:24:56 +00003076
Anders Carlsson81df7b82009-06-24 19:06:50 +00003077/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3078/// DecltypeType AST's. The only motivation to unique these nodes would be
3079/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003080/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003081/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003082QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003083 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003084
3085 // C++0x [temp.type]p2:
3086 // If an expression e involves a template parameter, decltype(e) denotes a
3087 // unique dependent type. Two such decltype-specifiers refer to the same
3088 // type only if their expressions are equivalent (14.5.6.1).
3089 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003090 llvm::FoldingSetNodeID ID;
3091 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003092
Douglas Gregora21f6c32009-07-30 23:36:40 +00003093 void *InsertPos = 0;
3094 DependentDecltypeType *Canon
3095 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3096 if (Canon) {
3097 // We already have a "canonical" version of an equivalent, dependent
3098 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003099 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003100 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003101 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003102 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003103 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003104 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3105 dt = Canon;
3106 }
3107 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003108 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3109 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003110 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003111 Types.push_back(dt);
3112 return QualType(dt, 0);
3113}
3114
Alexis Hunte852b102011-05-24 22:41:36 +00003115/// getUnaryTransformationType - We don't unique these, since the memory
3116/// savings are minimal and these are rare.
3117QualType ASTContext::getUnaryTransformType(QualType BaseType,
3118 QualType UnderlyingType,
3119 UnaryTransformType::UTTKind Kind)
3120 const {
3121 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003122 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3123 Kind,
3124 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003125 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003126 Types.push_back(Ty);
3127 return QualType(Ty, 0);
3128}
3129
Richard Smithb2bc2e62011-02-21 20:05:19 +00003130/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003131QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003132 void *InsertPos = 0;
3133 if (!DeducedType.isNull()) {
3134 // Look in the folding set for an existing type.
3135 llvm::FoldingSetNodeID ID;
3136 AutoType::Profile(ID, DeducedType);
3137 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3138 return QualType(AT, 0);
3139 }
3140
3141 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3142 Types.push_back(AT);
3143 if (InsertPos)
3144 AutoTypes.InsertNode(AT, InsertPos);
3145 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003146}
3147
Eli Friedman0dfb8892011-10-06 23:00:33 +00003148/// getAtomicType - Return the uniqued reference to the atomic type for
3149/// the given value type.
3150QualType ASTContext::getAtomicType(QualType T) const {
3151 // Unique pointers, to guarantee there is only one pointer of a particular
3152 // structure.
3153 llvm::FoldingSetNodeID ID;
3154 AtomicType::Profile(ID, T);
3155
3156 void *InsertPos = 0;
3157 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3158 return QualType(AT, 0);
3159
3160 // If the atomic value type isn't canonical, this won't be a canonical type
3161 // either, so fill in the canonical type field.
3162 QualType Canonical;
3163 if (!T.isCanonical()) {
3164 Canonical = getAtomicType(getCanonicalType(T));
3165
3166 // Get the new insert position for the node we care about.
3167 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3168 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3169 }
3170 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3171 Types.push_back(New);
3172 AtomicTypes.InsertNode(New, InsertPos);
3173 return QualType(New, 0);
3174}
3175
Richard Smith02e85f32011-04-14 22:09:26 +00003176/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3177QualType ASTContext::getAutoDeductType() const {
3178 if (AutoDeductTy.isNull())
3179 AutoDeductTy = getAutoType(QualType());
3180 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3181 return AutoDeductTy;
3182}
3183
3184/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3185QualType ASTContext::getAutoRRefDeductType() const {
3186 if (AutoRRefDeductTy.isNull())
3187 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3188 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3189 return AutoRRefDeductTy;
3190}
3191
Chris Lattnerfb072462007-01-23 05:45:31 +00003192/// getTagDeclType - Return the unique reference to the type for the
3193/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003194QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003195 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003196 // FIXME: What is the design on getTagDeclType when it requires casting
3197 // away const? mutable?
3198 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003199}
3200
Mike Stump11289f42009-09-09 15:08:12 +00003201/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3202/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3203/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003204CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003205 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003206}
Chris Lattnerfb072462007-01-23 05:45:31 +00003207
Hans Wennborg27541db2011-10-27 08:29:09 +00003208/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3209CanQualType ASTContext::getIntMaxType() const {
3210 return getFromTargetType(Target->getIntMaxType());
3211}
3212
3213/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3214CanQualType ASTContext::getUIntMaxType() const {
3215 return getFromTargetType(Target->getUIntMaxType());
3216}
3217
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003218/// getSignedWCharType - Return the type of "signed wchar_t".
3219/// Used when in C++, as a GCC extension.
3220QualType ASTContext::getSignedWCharType() const {
3221 // FIXME: derive from "Target" ?
3222 return WCharTy;
3223}
3224
3225/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3226/// Used when in C++, as a GCC extension.
3227QualType ASTContext::getUnsignedWCharType() const {
3228 // FIXME: derive from "Target" ?
3229 return UnsignedIntTy;
3230}
3231
Hans Wennborg27541db2011-10-27 08:29:09 +00003232/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003233/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3234QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003235 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003236}
3237
Chris Lattnera21ad802008-04-02 05:18:44 +00003238//===----------------------------------------------------------------------===//
3239// Type Operators
3240//===----------------------------------------------------------------------===//
3241
Jay Foad39c79802011-01-12 09:06:06 +00003242CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003243 // Push qualifiers into arrays, and then discard any remaining
3244 // qualifiers.
3245 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003246 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003247 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003248 QualType Result;
3249 if (isa<ArrayType>(Ty)) {
3250 Result = getArrayDecayedType(QualType(Ty,0));
3251 } else if (isa<FunctionType>(Ty)) {
3252 Result = getPointerType(QualType(Ty, 0));
3253 } else {
3254 Result = QualType(Ty, 0);
3255 }
3256
3257 return CanQualType::CreateUnsafe(Result);
3258}
3259
John McCall6c9dd522011-01-18 07:41:22 +00003260QualType ASTContext::getUnqualifiedArrayType(QualType type,
3261 Qualifiers &quals) {
3262 SplitQualType splitType = type.getSplitUnqualifiedType();
3263
3264 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3265 // the unqualified desugared type and then drops it on the floor.
3266 // We then have to strip that sugar back off with
3267 // getUnqualifiedDesugaredType(), which is silly.
3268 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003269 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003270
3271 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003272 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003273 quals = splitType.Quals;
3274 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003275 }
3276
John McCall6c9dd522011-01-18 07:41:22 +00003277 // Otherwise, recurse on the array's element type.
3278 QualType elementType = AT->getElementType();
3279 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3280
3281 // If that didn't change the element type, AT has no qualifiers, so we
3282 // can just use the results in splitType.
3283 if (elementType == unqualElementType) {
3284 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003285 quals = splitType.Quals;
3286 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003287 }
3288
3289 // Otherwise, add in the qualifiers from the outermost type, then
3290 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003291 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003292
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003293 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003294 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003295 CAT->getSizeModifier(), 0);
3296 }
3297
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003298 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003299 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003300 }
3301
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003302 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003303 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003304 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003305 VAT->getSizeModifier(),
3306 VAT->getIndexTypeCVRQualifiers(),
3307 VAT->getBracketsRange());
3308 }
3309
3310 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003311 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003312 DSAT->getSizeModifier(), 0,
3313 SourceRange());
3314}
3315
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003316/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3317/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3318/// they point to and return true. If T1 and T2 aren't pointer types
3319/// or pointer-to-member types, or if they are not similar at this
3320/// level, returns false and leaves T1 and T2 unchanged. Top-level
3321/// qualifiers on T1 and T2 are ignored. This function will typically
3322/// be called in a loop that successively "unwraps" pointer and
3323/// pointer-to-member types to compare them at each level.
3324bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3325 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3326 *T2PtrType = T2->getAs<PointerType>();
3327 if (T1PtrType && T2PtrType) {
3328 T1 = T1PtrType->getPointeeType();
3329 T2 = T2PtrType->getPointeeType();
3330 return true;
3331 }
3332
3333 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3334 *T2MPType = T2->getAs<MemberPointerType>();
3335 if (T1MPType && T2MPType &&
3336 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3337 QualType(T2MPType->getClass(), 0))) {
3338 T1 = T1MPType->getPointeeType();
3339 T2 = T2MPType->getPointeeType();
3340 return true;
3341 }
3342
David Blaikiebbafb8a2012-03-11 07:00:24 +00003343 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003344 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3345 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3346 if (T1OPType && T2OPType) {
3347 T1 = T1OPType->getPointeeType();
3348 T2 = T2OPType->getPointeeType();
3349 return true;
3350 }
3351 }
3352
3353 // FIXME: Block pointers, too?
3354
3355 return false;
3356}
3357
Jay Foad39c79802011-01-12 09:06:06 +00003358DeclarationNameInfo
3359ASTContext::getNameForTemplate(TemplateName Name,
3360 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003361 switch (Name.getKind()) {
3362 case TemplateName::QualifiedTemplate:
3363 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003364 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003365 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3366 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003367
John McCalld9dfe3a2011-06-30 08:33:18 +00003368 case TemplateName::OverloadedTemplate: {
3369 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3370 // DNInfo work in progress: CHECKME: what about DNLoc?
3371 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3372 }
3373
3374 case TemplateName::DependentTemplate: {
3375 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003376 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003377 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003378 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3379 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003380 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003381 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3382 // DNInfo work in progress: FIXME: source locations?
3383 DeclarationNameLoc DNLoc;
3384 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3385 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3386 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003387 }
3388 }
3389
John McCalld9dfe3a2011-06-30 08:33:18 +00003390 case TemplateName::SubstTemplateTemplateParm: {
3391 SubstTemplateTemplateParmStorage *subst
3392 = Name.getAsSubstTemplateTemplateParm();
3393 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3394 NameLoc);
3395 }
3396
3397 case TemplateName::SubstTemplateTemplateParmPack: {
3398 SubstTemplateTemplateParmPackStorage *subst
3399 = Name.getAsSubstTemplateTemplateParmPack();
3400 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3401 NameLoc);
3402 }
3403 }
3404
3405 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003406}
3407
Jay Foad39c79802011-01-12 09:06:06 +00003408TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003409 switch (Name.getKind()) {
3410 case TemplateName::QualifiedTemplate:
3411 case TemplateName::Template: {
3412 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003413 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003414 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003415 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3416
3417 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003418 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003419 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003420
John McCalld9dfe3a2011-06-30 08:33:18 +00003421 case TemplateName::OverloadedTemplate:
3422 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003423
John McCalld9dfe3a2011-06-30 08:33:18 +00003424 case TemplateName::DependentTemplate: {
3425 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3426 assert(DTN && "Non-dependent template names must refer to template decls.");
3427 return DTN->CanonicalTemplateName;
3428 }
3429
3430 case TemplateName::SubstTemplateTemplateParm: {
3431 SubstTemplateTemplateParmStorage *subst
3432 = Name.getAsSubstTemplateTemplateParm();
3433 return getCanonicalTemplateName(subst->getReplacement());
3434 }
3435
3436 case TemplateName::SubstTemplateTemplateParmPack: {
3437 SubstTemplateTemplateParmPackStorage *subst
3438 = Name.getAsSubstTemplateTemplateParmPack();
3439 TemplateTemplateParmDecl *canonParameter
3440 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3441 TemplateArgument canonArgPack
3442 = getCanonicalTemplateArgument(subst->getArgumentPack());
3443 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3444 }
3445 }
3446
3447 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003448}
3449
Douglas Gregoradee3e32009-11-11 23:06:43 +00003450bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3451 X = getCanonicalTemplateName(X);
3452 Y = getCanonicalTemplateName(Y);
3453 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3454}
3455
Mike Stump11289f42009-09-09 15:08:12 +00003456TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003457ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003458 switch (Arg.getKind()) {
3459 case TemplateArgument::Null:
3460 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003461
Douglas Gregora8e02e72009-07-28 23:00:59 +00003462 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003463 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003464
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003465 case TemplateArgument::Declaration: {
3466 if (Decl *D = Arg.getAsDecl())
3467 return TemplateArgument(D->getCanonicalDecl());
3468 return TemplateArgument((Decl*)0);
3469 }
Mike Stump11289f42009-09-09 15:08:12 +00003470
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003471 case TemplateArgument::Template:
3472 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003473
3474 case TemplateArgument::TemplateExpansion:
3475 return TemplateArgument(getCanonicalTemplateName(
3476 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003477 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003478
Douglas Gregora8e02e72009-07-28 23:00:59 +00003479 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003480 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003481
Douglas Gregora8e02e72009-07-28 23:00:59 +00003482 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003483 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003484
Douglas Gregora8e02e72009-07-28 23:00:59 +00003485 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003486 if (Arg.pack_size() == 0)
3487 return Arg;
3488
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003489 TemplateArgument *CanonArgs
3490 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003491 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003492 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003493 AEnd = Arg.pack_end();
3494 A != AEnd; (void)++A, ++Idx)
3495 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003496
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003497 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003498 }
3499 }
3500
3501 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003502 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003503}
3504
Douglas Gregor333489b2009-03-27 23:10:48 +00003505NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003506ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003507 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003508 return 0;
3509
3510 switch (NNS->getKind()) {
3511 case NestedNameSpecifier::Identifier:
3512 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003513 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003514 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3515 NNS->getAsIdentifier());
3516
3517 case NestedNameSpecifier::Namespace:
3518 // A namespace is canonical; build a nested-name-specifier with
3519 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003520 return NestedNameSpecifier::Create(*this, 0,
3521 NNS->getAsNamespace()->getOriginalNamespace());
3522
3523 case NestedNameSpecifier::NamespaceAlias:
3524 // A namespace is canonical; build a nested-name-specifier with
3525 // this namespace and no prefix.
3526 return NestedNameSpecifier::Create(*this, 0,
3527 NNS->getAsNamespaceAlias()->getNamespace()
3528 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003529
3530 case NestedNameSpecifier::TypeSpec:
3531 case NestedNameSpecifier::TypeSpecWithTemplate: {
3532 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003533
3534 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3535 // break it apart into its prefix and identifier, then reconsititute those
3536 // as the canonical nested-name-specifier. This is required to canonicalize
3537 // a dependent nested-name-specifier involving typedefs of dependent-name
3538 // types, e.g.,
3539 // typedef typename T::type T1;
3540 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003541 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3542 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003543 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003544
Eli Friedman5358a0a2012-03-03 04:09:56 +00003545 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3546 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3547 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003548 return NestedNameSpecifier::Create(*this, 0, false,
3549 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003550 }
3551
3552 case NestedNameSpecifier::Global:
3553 // The global specifier is canonical and unique.
3554 return NNS;
3555 }
3556
David Blaikie8a40f702012-01-17 06:56:22 +00003557 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003558}
3559
Chris Lattner7adf0762008-08-04 07:31:14 +00003560
Jay Foad39c79802011-01-12 09:06:06 +00003561const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003562 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003563 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003564 // Handle the common positive case fast.
3565 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3566 return AT;
3567 }
Mike Stump11289f42009-09-09 15:08:12 +00003568
John McCall8ccfcb52009-09-24 19:53:00 +00003569 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003570 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003571 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003572
John McCall8ccfcb52009-09-24 19:53:00 +00003573 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003574 // implements C99 6.7.3p8: "If the specification of an array type includes
3575 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003576
Chris Lattner7adf0762008-08-04 07:31:14 +00003577 // If we get here, we either have type qualifiers on the type, or we have
3578 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003579 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003580
John McCall33ddac02011-01-19 10:06:00 +00003581 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003582 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003583
Chris Lattner7adf0762008-08-04 07:31:14 +00003584 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003585 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003586 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003587 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003588
Chris Lattner7adf0762008-08-04 07:31:14 +00003589 // Otherwise, we have an array and we have qualifiers on it. Push the
3590 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003591 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003592
Chris Lattner7adf0762008-08-04 07:31:14 +00003593 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3594 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3595 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003596 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003597 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3598 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3599 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003600 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003601
Mike Stump11289f42009-09-09 15:08:12 +00003602 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003603 = dyn_cast<DependentSizedArrayType>(ATy))
3604 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003605 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003606 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003607 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003608 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003609 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003610
Chris Lattner7adf0762008-08-04 07:31:14 +00003611 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003612 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003613 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003614 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003615 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003616 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003617}
3618
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003619QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003620 // C99 6.7.5.3p7:
3621 // A declaration of a parameter as "array of type" shall be
3622 // adjusted to "qualified pointer to type", where the type
3623 // qualifiers (if any) are those specified within the [ and ] of
3624 // the array type derivation.
3625 if (T->isArrayType())
3626 return getArrayDecayedType(T);
3627
3628 // C99 6.7.5.3p8:
3629 // A declaration of a parameter as "function returning type"
3630 // shall be adjusted to "pointer to function returning type", as
3631 // in 6.3.2.1.
3632 if (T->isFunctionType())
3633 return getPointerType(T);
3634
3635 return T;
3636}
3637
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003638QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003639 T = getVariableArrayDecayedType(T);
3640 T = getAdjustedParameterType(T);
3641 return T.getUnqualifiedType();
3642}
3643
Chris Lattnera21ad802008-04-02 05:18:44 +00003644/// getArrayDecayedType - Return the properly qualified result of decaying the
3645/// specified array type to a pointer. This operation is non-trivial when
3646/// handling typedefs etc. The canonical type of "T" must be an array type,
3647/// this returns a pointer to a properly qualified element of the array.
3648///
3649/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003650QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003651 // Get the element type with 'getAsArrayType' so that we don't lose any
3652 // typedefs in the element type of the array. This also handles propagation
3653 // of type qualifiers from the array type into the element type if present
3654 // (C99 6.7.3p8).
3655 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3656 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003657
Chris Lattner7adf0762008-08-04 07:31:14 +00003658 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003659
3660 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003661 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003662}
3663
John McCall33ddac02011-01-19 10:06:00 +00003664QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3665 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003666}
3667
John McCall33ddac02011-01-19 10:06:00 +00003668QualType ASTContext::getBaseElementType(QualType type) const {
3669 Qualifiers qs;
3670 while (true) {
3671 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003672 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003673 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003674
John McCall33ddac02011-01-19 10:06:00 +00003675 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003676 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003677 }
Mike Stump11289f42009-09-09 15:08:12 +00003678
John McCall33ddac02011-01-19 10:06:00 +00003679 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003680}
3681
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003682/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003683uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003684ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3685 uint64_t ElementCount = 1;
3686 do {
3687 ElementCount *= CA->getSize().getZExtValue();
3688 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3689 } while (CA);
3690 return ElementCount;
3691}
3692
Steve Naroff0af91202007-04-27 21:51:21 +00003693/// getFloatingRank - Return a relative rank for floating point types.
3694/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003695static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003696 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003697 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003698
John McCall9dd450b2009-09-21 23:43:11 +00003699 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3700 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003701 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003702 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003703 case BuiltinType::Float: return FloatRank;
3704 case BuiltinType::Double: return DoubleRank;
3705 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003706 }
3707}
3708
Mike Stump11289f42009-09-09 15:08:12 +00003709/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3710/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003711/// 'typeDomain' is a real floating point or complex type.
3712/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003713QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3714 QualType Domain) const {
3715 FloatingRank EltRank = getFloatingRank(Size);
3716 if (Domain->isComplexType()) {
3717 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003718 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003719 case FloatRank: return FloatComplexTy;
3720 case DoubleRank: return DoubleComplexTy;
3721 case LongDoubleRank: return LongDoubleComplexTy;
3722 }
Steve Naroff0af91202007-04-27 21:51:21 +00003723 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003724
3725 assert(Domain->isRealFloatingType() && "Unknown domain!");
3726 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003727 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003728 case FloatRank: return FloatTy;
3729 case DoubleRank: return DoubleTy;
3730 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003731 }
David Blaikief47fa302012-01-17 02:30:50 +00003732 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003733}
3734
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003735/// getFloatingTypeOrder - Compare the rank of the two specified floating
3736/// point types, ignoring the domain of the type (i.e. 'double' ==
3737/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003738/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003739int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003740 FloatingRank LHSR = getFloatingRank(LHS);
3741 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003742
Chris Lattnerb90739d2008-04-06 23:38:49 +00003743 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003744 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003745 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003746 return 1;
3747 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003748}
3749
Chris Lattner76a00cf2008-04-06 22:59:24 +00003750/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3751/// routine will assert if passed a built-in type that isn't an integer or enum,
3752/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003753unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003754 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003755
Chris Lattner76a00cf2008-04-06 22:59:24 +00003756 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003757 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003758 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003759 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003760 case BuiltinType::Char_S:
3761 case BuiltinType::Char_U:
3762 case BuiltinType::SChar:
3763 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003764 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003765 case BuiltinType::Short:
3766 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003767 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003768 case BuiltinType::Int:
3769 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003770 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003771 case BuiltinType::Long:
3772 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003773 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003774 case BuiltinType::LongLong:
3775 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003776 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003777 case BuiltinType::Int128:
3778 case BuiltinType::UInt128:
3779 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003780 }
3781}
3782
Eli Friedman629ffb92009-08-20 04:21:42 +00003783/// \brief Whether this is a promotable bitfield reference according
3784/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3785///
3786/// \returns the type this bit-field will promote to, or NULL if no
3787/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003788QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003789 if (E->isTypeDependent() || E->isValueDependent())
3790 return QualType();
3791
Eli Friedman629ffb92009-08-20 04:21:42 +00003792 FieldDecl *Field = E->getBitField();
3793 if (!Field)
3794 return QualType();
3795
3796 QualType FT = Field->getType();
3797
Richard Smithcaf33902011-10-10 18:28:20 +00003798 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003799 uint64_t IntSize = getTypeSize(IntTy);
3800 // GCC extension compatibility: if the bit-field size is less than or equal
3801 // to the size of int, it gets promoted no matter what its type is.
3802 // For instance, unsigned long bf : 4 gets promoted to signed int.
3803 if (BitWidth < IntSize)
3804 return IntTy;
3805
3806 if (BitWidth == IntSize)
3807 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3808
3809 // Types bigger than int are not subject to promotions, and therefore act
3810 // like the base type.
3811 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3812 // is ridiculous.
3813 return QualType();
3814}
3815
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003816/// getPromotedIntegerType - Returns the type that Promotable will
3817/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3818/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003819QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003820 assert(!Promotable.isNull());
3821 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003822 if (const EnumType *ET = Promotable->getAs<EnumType>())
3823 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003824
3825 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3826 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3827 // (3.9.1) can be converted to a prvalue of the first of the following
3828 // types that can represent all the values of its underlying type:
3829 // int, unsigned int, long int, unsigned long int, long long int, or
3830 // unsigned long long int [...]
3831 // FIXME: Is there some better way to compute this?
3832 if (BT->getKind() == BuiltinType::WChar_S ||
3833 BT->getKind() == BuiltinType::WChar_U ||
3834 BT->getKind() == BuiltinType::Char16 ||
3835 BT->getKind() == BuiltinType::Char32) {
3836 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3837 uint64_t FromSize = getTypeSize(BT);
3838 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3839 LongLongTy, UnsignedLongLongTy };
3840 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3841 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3842 if (FromSize < ToSize ||
3843 (FromSize == ToSize &&
3844 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3845 return PromoteTypes[Idx];
3846 }
3847 llvm_unreachable("char type should fit into long long");
3848 }
3849 }
3850
3851 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003852 if (Promotable->isSignedIntegerType())
3853 return IntTy;
3854 uint64_t PromotableSize = getTypeSize(Promotable);
3855 uint64_t IntSize = getTypeSize(IntTy);
3856 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3857 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3858}
3859
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003860/// \brief Recurses in pointer/array types until it finds an objc retainable
3861/// type and returns its ownership.
3862Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3863 while (!T.isNull()) {
3864 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3865 return T.getObjCLifetime();
3866 if (T->isArrayType())
3867 T = getBaseElementType(T);
3868 else if (const PointerType *PT = T->getAs<PointerType>())
3869 T = PT->getPointeeType();
3870 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003871 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003872 else
3873 break;
3874 }
3875
3876 return Qualifiers::OCL_None;
3877}
3878
Mike Stump11289f42009-09-09 15:08:12 +00003879/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003880/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003881/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003882int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003883 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3884 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003885 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003886
Chris Lattner76a00cf2008-04-06 22:59:24 +00003887 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3888 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003889
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003890 unsigned LHSRank = getIntegerRank(LHSC);
3891 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003892
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003893 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3894 if (LHSRank == RHSRank) return 0;
3895 return LHSRank > RHSRank ? 1 : -1;
3896 }
Mike Stump11289f42009-09-09 15:08:12 +00003897
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003898 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3899 if (LHSUnsigned) {
3900 // If the unsigned [LHS] type is larger, return it.
3901 if (LHSRank >= RHSRank)
3902 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003903
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003904 // If the signed type can represent all values of the unsigned type, it
3905 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003906 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003907 return -1;
3908 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003909
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003910 // If the unsigned [RHS] type is larger, return it.
3911 if (RHSRank >= LHSRank)
3912 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003913
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003914 // If the signed type can represent all values of the unsigned type, it
3915 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003916 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003917 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003918}
Anders Carlsson98f07902007-08-17 05:31:46 +00003919
Anders Carlsson6d417272009-11-14 21:45:58 +00003920static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003921CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3922 DeclContext *DC, IdentifierInfo *Id) {
3923 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003924 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003925 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003926 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003927 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003928}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003929
Mike Stump11289f42009-09-09 15:08:12 +00003930// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003931QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003932 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003933 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003934 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003935 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003936 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003937
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003938 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003939
Anders Carlsson98f07902007-08-17 05:31:46 +00003940 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003941 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003942 // int flags;
3943 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003944 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003945 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003946 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003947 FieldTypes[3] = LongTy;
3948
Anders Carlsson98f07902007-08-17 05:31:46 +00003949 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003950 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003951 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003952 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003953 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003954 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003955 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003956 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003957 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003958 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003959 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003960 }
3961
Douglas Gregord5058122010-02-11 01:19:42 +00003962 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003963 }
Mike Stump11289f42009-09-09 15:08:12 +00003964
Anders Carlsson98f07902007-08-17 05:31:46 +00003965 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003966}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003967
Douglas Gregor512b0772009-04-23 22:29:11 +00003968void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003969 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003970 assert(Rec && "Invalid CFConstantStringType");
3971 CFConstantStringTypeDecl = Rec->getDecl();
3972}
3973
Jay Foad39c79802011-01-12 09:06:06 +00003974QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003975 if (BlockDescriptorType)
3976 return getTagDeclType(BlockDescriptorType);
3977
3978 RecordDecl *T;
3979 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003980 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003981 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003982 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003983
3984 QualType FieldTypes[] = {
3985 UnsignedLongTy,
3986 UnsignedLongTy,
3987 };
3988
3989 const char *FieldNames[] = {
3990 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003991 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003992 };
3993
3994 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003995 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003996 SourceLocation(),
3997 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003998 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +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);
Mike Stumpd0153282009-10-20 02:12:22 +00004003 T->addDecl(Field);
4004 }
4005
Douglas Gregord5058122010-02-11 01:19:42 +00004006 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004007
4008 BlockDescriptorType = T;
4009
4010 return getTagDeclType(BlockDescriptorType);
4011}
4012
Jay Foad39c79802011-01-12 09:06:06 +00004013QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004014 if (BlockDescriptorExtendedType)
4015 return getTagDeclType(BlockDescriptorExtendedType);
4016
4017 RecordDecl *T;
4018 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004019 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004020 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004021 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004022
4023 QualType FieldTypes[] = {
4024 UnsignedLongTy,
4025 UnsignedLongTy,
4026 getPointerType(VoidPtrTy),
4027 getPointerType(VoidPtrTy)
4028 };
4029
4030 const char *FieldNames[] = {
4031 "reserved",
4032 "Size",
4033 "CopyFuncPtr",
4034 "DestroyFuncPtr"
4035 };
4036
4037 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004038 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004039 SourceLocation(),
4040 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004041 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004042 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004043 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004044 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004045 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004046 T->addDecl(Field);
4047 }
4048
Douglas Gregord5058122010-02-11 01:19:42 +00004049 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004050
4051 BlockDescriptorExtendedType = T;
4052
4053 return getTagDeclType(BlockDescriptorExtendedType);
4054}
4055
Jay Foad39c79802011-01-12 09:06:06 +00004056bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004057 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004058 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004059 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004060 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4061 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004062 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004063
4064 }
4065 }
Mike Stump94967902009-10-21 18:16:27 +00004066 return false;
4067}
4068
Jay Foad39c79802011-01-12 09:06:06 +00004069QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004070ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004071 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004072 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004073 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004074 // unsigned int __flags;
4075 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004076 // void *__copy_helper; // as needed
4077 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004078 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004079 // } *
4080
Mike Stump94967902009-10-21 18:16:27 +00004081 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4082
4083 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004084 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004085 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4086 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004087 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004088 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004089 T->startDefinition();
4090 QualType Int32Ty = IntTy;
4091 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4092 QualType FieldTypes[] = {
4093 getPointerType(VoidPtrTy),
4094 getPointerType(getTagDeclType(T)),
4095 Int32Ty,
4096 Int32Ty,
4097 getPointerType(VoidPtrTy),
4098 getPointerType(VoidPtrTy),
4099 Ty
4100 };
4101
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004102 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004103 "__isa",
4104 "__forwarding",
4105 "__flags",
4106 "__size",
4107 "__copy_helper",
4108 "__destroy_helper",
4109 DeclName,
4110 };
4111
4112 for (size_t i = 0; i < 7; ++i) {
4113 if (!HasCopyAndDispose && i >=4 && i <= 5)
4114 continue;
4115 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004116 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004117 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004118 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004119 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004120 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004121 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004122 T->addDecl(Field);
4123 }
4124
Douglas Gregord5058122010-02-11 01:19:42 +00004125 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004126
4127 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004128}
4129
Douglas Gregorbab8a962011-09-08 01:46:34 +00004130TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4131 if (!ObjCInstanceTypeDecl)
4132 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4133 getTranslationUnitDecl(),
4134 SourceLocation(),
4135 SourceLocation(),
4136 &Idents.get("instancetype"),
4137 getTrivialTypeSourceInfo(getObjCIdType()));
4138 return ObjCInstanceTypeDecl;
4139}
4140
Anders Carlsson18acd442007-10-29 06:33:42 +00004141// This returns true if a type has been typedefed to BOOL:
4142// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004143static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004144 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004145 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4146 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004147
Anders Carlssond8499822007-10-29 05:01:08 +00004148 return false;
4149}
4150
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004151/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004152/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004153CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004154 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4155 return CharUnits::Zero();
4156
Ken Dyck40775002010-01-11 17:06:35 +00004157 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004158
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004159 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004160 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004161 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004162 // Treat arrays as pointers, since that's how they're passed in.
4163 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004164 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004165 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004166}
4167
4168static inline
4169std::string charUnitsToString(const CharUnits &CU) {
4170 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004171}
4172
John McCall351762c2011-02-07 10:33:21 +00004173/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004174/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004175std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4176 std::string S;
4177
David Chisnall950a9512009-11-17 19:33:30 +00004178 const BlockDecl *Decl = Expr->getBlockDecl();
4179 QualType BlockTy =
4180 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4181 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004182 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004183 // Compute size of all parameters.
4184 // Start with computing size of a pointer in number of bytes.
4185 // FIXME: There might(should) be a better way of doing this computation!
4186 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004187 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4188 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004189 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004190 E = Decl->param_end(); PI != E; ++PI) {
4191 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004192 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004193 if (sz.isZero())
4194 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004195 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004196 ParmOffset += sz;
4197 }
4198 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004199 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004200 // Block pointer and offset.
4201 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004202
4203 // Argument types.
4204 ParmOffset = PtrSize;
4205 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4206 Decl->param_end(); PI != E; ++PI) {
4207 ParmVarDecl *PVDecl = *PI;
4208 QualType PType = PVDecl->getOriginalType();
4209 if (const ArrayType *AT =
4210 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4211 // Use array's original type only if it has known number of
4212 // elements.
4213 if (!isa<ConstantArrayType>(AT))
4214 PType = PVDecl->getType();
4215 } else if (PType->isFunctionType())
4216 PType = PVDecl->getType();
4217 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004218 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004219 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004220 }
John McCall351762c2011-02-07 10:33:21 +00004221
4222 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004223}
4224
Douglas Gregora9d84932011-05-27 01:19:52 +00004225bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004226 std::string& S) {
4227 // Encode result type.
4228 getObjCEncodingForType(Decl->getResultType(), S);
4229 CharUnits ParmOffset;
4230 // Compute size of all parameters.
4231 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4232 E = Decl->param_end(); PI != E; ++PI) {
4233 QualType PType = (*PI)->getType();
4234 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004235 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004236 continue;
4237
David Chisnall50e4eba2010-12-30 14:05:53 +00004238 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004239 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004240 ParmOffset += sz;
4241 }
4242 S += charUnitsToString(ParmOffset);
4243 ParmOffset = CharUnits::Zero();
4244
4245 // Argument types.
4246 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4247 E = Decl->param_end(); PI != E; ++PI) {
4248 ParmVarDecl *PVDecl = *PI;
4249 QualType PType = PVDecl->getOriginalType();
4250 if (const ArrayType *AT =
4251 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4252 // Use array's original type only if it has known number of
4253 // elements.
4254 if (!isa<ConstantArrayType>(AT))
4255 PType = PVDecl->getType();
4256 } else if (PType->isFunctionType())
4257 PType = PVDecl->getType();
4258 getObjCEncodingForType(PType, S);
4259 S += charUnitsToString(ParmOffset);
4260 ParmOffset += getObjCEncodingTypeSize(PType);
4261 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004262
4263 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004264}
4265
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004266/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4267/// method parameter or return type. If Extended, include class names and
4268/// block object types.
4269void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4270 QualType T, std::string& S,
4271 bool Extended) const {
4272 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4273 getObjCEncodingForTypeQualifier(QT, S);
4274 // Encode parameter type.
4275 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4276 true /*OutermostType*/,
4277 false /*EncodingProperty*/,
4278 false /*StructField*/,
4279 Extended /*EncodeBlockParameters*/,
4280 Extended /*EncodeClassNames*/);
4281}
4282
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004283/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004284/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004285bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004286 std::string& S,
4287 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004288 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004289 // Encode return type.
4290 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4291 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004292 // Compute size of all parameters.
4293 // Start with computing size of a pointer in number of bytes.
4294 // FIXME: There might(should) be a better way of doing this computation!
4295 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004296 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004297 // The first two arguments (self and _cmd) are pointers; account for
4298 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004299 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004300 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004301 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004302 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004303 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004304 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004305 continue;
4306
Ken Dyck40775002010-01-11 17:06:35 +00004307 assert (sz.isPositive() &&
4308 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004309 ParmOffset += sz;
4310 }
Ken Dyck40775002010-01-11 17:06:35 +00004311 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004312 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004313 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004314
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004315 // Argument types.
4316 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004317 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004318 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004319 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004320 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004321 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004322 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4323 // Use array's original type only if it has known number of
4324 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004325 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004326 PType = PVDecl->getType();
4327 } else if (PType->isFunctionType())
4328 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004329 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4330 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004331 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004332 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004333 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004334
4335 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004336}
4337
Daniel Dunbar4932b362008-08-28 04:38:10 +00004338/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004339/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004340/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4341/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004342/// Property attributes are stored as a comma-delimited C string. The simple
4343/// attributes readonly and bycopy are encoded as single characters. The
4344/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4345/// encoded as single characters, followed by an identifier. Property types
4346/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004347/// these attributes are defined by the following enumeration:
4348/// @code
4349/// enum PropertyAttributes {
4350/// kPropertyReadOnly = 'R', // property is read-only.
4351/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4352/// kPropertyByref = '&', // property is a reference to the value last assigned
4353/// kPropertyDynamic = 'D', // property is dynamic
4354/// kPropertyGetter = 'G', // followed by getter selector name
4355/// kPropertySetter = 'S', // followed by setter selector name
4356/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004357/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004358/// kPropertyWeak = 'W' // 'weak' property
4359/// kPropertyStrong = 'P' // property GC'able
4360/// kPropertyNonAtomic = 'N' // property non-atomic
4361/// };
4362/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004363void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004364 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004365 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004366 // Collect information from the property implementation decl(s).
4367 bool Dynamic = false;
4368 ObjCPropertyImplDecl *SynthesizePID = 0;
4369
4370 // FIXME: Duplicated code due to poor abstraction.
4371 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004372 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004373 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4374 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004375 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004376 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004377 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004378 if (PID->getPropertyDecl() == PD) {
4379 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4380 Dynamic = true;
4381 } else {
4382 SynthesizePID = PID;
4383 }
4384 }
4385 }
4386 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004387 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004388 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004389 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004390 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004391 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004392 if (PID->getPropertyDecl() == PD) {
4393 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4394 Dynamic = true;
4395 } else {
4396 SynthesizePID = PID;
4397 }
4398 }
Mike Stump11289f42009-09-09 15:08:12 +00004399 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004400 }
4401 }
4402
4403 // FIXME: This is not very efficient.
4404 S = "T";
4405
4406 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004407 // GCC has some special rules regarding encoding of properties which
4408 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004409 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004410 true /* outermost type */,
4411 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004412
4413 if (PD->isReadOnly()) {
4414 S += ",R";
4415 } else {
4416 switch (PD->getSetterKind()) {
4417 case ObjCPropertyDecl::Assign: break;
4418 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004419 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004420 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004421 }
4422 }
4423
4424 // It really isn't clear at all what this means, since properties
4425 // are "dynamic by default".
4426 if (Dynamic)
4427 S += ",D";
4428
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004429 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4430 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004431
Daniel Dunbar4932b362008-08-28 04:38:10 +00004432 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4433 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004434 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004435 }
4436
4437 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4438 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004439 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004440 }
4441
4442 if (SynthesizePID) {
4443 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4444 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004445 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004446 }
4447
4448 // FIXME: OBJCGC: weak & strong
4449}
4450
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004451/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004452/// Another legacy compatibility encoding: 32-bit longs are encoded as
4453/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004454/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4455///
4456void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004457 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004458 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004459 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004460 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004461 else
Jay Foad39c79802011-01-12 09:06:06 +00004462 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004463 PointeeTy = IntTy;
4464 }
4465 }
4466}
4467
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004468void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004469 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004470 // We follow the behavior of gcc, expanding structures which are
4471 // directly pointed to, and expanding embedded structures. Note that
4472 // these rules are sufficient to prevent recursive encoding of the
4473 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004474 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004475 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004476}
4477
David Chisnallb190a2c2010-06-04 01:10:52 +00004478static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4479 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004480 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004481 case BuiltinType::Void: return 'v';
4482 case BuiltinType::Bool: return 'B';
4483 case BuiltinType::Char_U:
4484 case BuiltinType::UChar: return 'C';
4485 case BuiltinType::UShort: return 'S';
4486 case BuiltinType::UInt: return 'I';
4487 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004488 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004489 case BuiltinType::UInt128: return 'T';
4490 case BuiltinType::ULongLong: return 'Q';
4491 case BuiltinType::Char_S:
4492 case BuiltinType::SChar: return 'c';
4493 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004494 case BuiltinType::WChar_S:
4495 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004496 case BuiltinType::Int: return 'i';
4497 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004498 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004499 case BuiltinType::LongLong: return 'q';
4500 case BuiltinType::Int128: return 't';
4501 case BuiltinType::Float: return 'f';
4502 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004503 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004504 }
4505}
4506
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004507static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4508 EnumDecl *Enum = ET->getDecl();
4509
4510 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4511 if (!Enum->isFixed())
4512 return 'i';
4513
4514 // The encoding of a fixed enum type matches its fixed underlying type.
4515 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4516}
4517
Jay Foad39c79802011-01-12 09:06:06 +00004518static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004519 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004520 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004521 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004522 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4523 // The GNU runtime requires more information; bitfields are encoded as b,
4524 // then the offset (in bits) of the first element, then the type of the
4525 // bitfield, then the size in bits. For example, in this structure:
4526 //
4527 // struct
4528 // {
4529 // int integer;
4530 // int flags:2;
4531 // };
4532 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4533 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4534 // information is not especially sensible, but we're stuck with it for
4535 // compatibility with GCC, although providing it breaks anything that
4536 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004537 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004538 const RecordDecl *RD = FD->getParent();
4539 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004540 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004541 if (const EnumType *ET = T->getAs<EnumType>())
4542 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004543 else
Jay Foad39c79802011-01-12 09:06:06 +00004544 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004545 }
Richard Smithcaf33902011-10-10 18:28:20 +00004546 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004547}
4548
Daniel Dunbar07d07852009-10-18 21:17:35 +00004549// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004550void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4551 bool ExpandPointedToStructures,
4552 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004553 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004554 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004555 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004556 bool StructField,
4557 bool EncodeBlockParameters,
4558 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004559 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004560 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004561 return EncodeBitField(this, S, T, FD);
4562 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004563 return;
4564 }
Mike Stump11289f42009-09-09 15:08:12 +00004565
John McCall9dd450b2009-09-21 23:43:11 +00004566 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004567 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004568 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004569 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004570 return;
4571 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004572
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004573 // encoding for pointer or r3eference types.
4574 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004575 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004576 if (PT->isObjCSelType()) {
4577 S += ':';
4578 return;
4579 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004580 PointeeTy = PT->getPointeeType();
4581 }
4582 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4583 PointeeTy = RT->getPointeeType();
4584 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004585 bool isReadOnly = false;
4586 // For historical/compatibility reasons, the read-only qualifier of the
4587 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4588 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004589 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004590 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004591 if (OutermostType && T.isConstQualified()) {
4592 isReadOnly = true;
4593 S += 'r';
4594 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004595 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004596 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004597 while (P->getAs<PointerType>())
4598 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004599 if (P.isConstQualified()) {
4600 isReadOnly = true;
4601 S += 'r';
4602 }
4603 }
4604 if (isReadOnly) {
4605 // Another legacy compatibility encoding. Some ObjC qualifier and type
4606 // combinations need to be rearranged.
4607 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004608 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004609 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004610 }
Mike Stump11289f42009-09-09 15:08:12 +00004611
Anders Carlssond8499822007-10-29 05:01:08 +00004612 if (PointeeTy->isCharType()) {
4613 // char pointer types should be encoded as '*' unless it is a
4614 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004615 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004616 S += '*';
4617 return;
4618 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004619 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004620 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4621 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4622 S += '#';
4623 return;
4624 }
4625 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4626 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4627 S += '@';
4628 return;
4629 }
4630 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004631 }
Anders Carlssond8499822007-10-29 05:01:08 +00004632 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004633 getLegacyIntegralTypeEncoding(PointeeTy);
4634
Mike Stump11289f42009-09-09 15:08:12 +00004635 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004636 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004637 return;
4638 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004639
Chris Lattnere7cabb92009-07-13 00:10:46 +00004640 if (const ArrayType *AT =
4641 // Ignore type qualifiers etc.
4642 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004643 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004644 // Incomplete arrays are encoded as a pointer to the array element.
4645 S += '^';
4646
Mike Stump11289f42009-09-09 15:08:12 +00004647 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004648 false, ExpandStructures, FD);
4649 } else {
4650 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004651
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004652 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4653 if (getTypeSize(CAT->getElementType()) == 0)
4654 S += '0';
4655 else
4656 S += llvm::utostr(CAT->getSize().getZExtValue());
4657 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004658 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004659 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4660 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004661 S += '0';
4662 }
Mike Stump11289f42009-09-09 15:08:12 +00004663
4664 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004665 false, ExpandStructures, FD);
4666 S += ']';
4667 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004668 return;
4669 }
Mike Stump11289f42009-09-09 15:08:12 +00004670
John McCall9dd450b2009-09-21 23:43:11 +00004671 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004672 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004673 return;
4674 }
Mike Stump11289f42009-09-09 15:08:12 +00004675
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004676 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004677 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004678 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004679 // Anonymous structures print as '?'
4680 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4681 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004682 if (ClassTemplateSpecializationDecl *Spec
4683 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4684 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4685 std::string TemplateArgsStr
4686 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004687 TemplateArgs.data(),
4688 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004689 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004690
4691 S += TemplateArgsStr;
4692 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004693 } else {
4694 S += '?';
4695 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004696 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004697 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004698 if (!RDecl->isUnion()) {
4699 getObjCEncodingForStructureImpl(RDecl, S, FD);
4700 } else {
4701 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4702 FieldEnd = RDecl->field_end();
4703 Field != FieldEnd; ++Field) {
4704 if (FD) {
4705 S += '"';
4706 S += Field->getNameAsString();
4707 S += '"';
4708 }
Mike Stump11289f42009-09-09 15:08:12 +00004709
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004710 // Special case bit-fields.
4711 if (Field->isBitField()) {
4712 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004713 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004714 } else {
4715 QualType qt = Field->getType();
4716 getLegacyIntegralTypeEncoding(qt);
4717 getObjCEncodingForTypeImpl(qt, S, false, true,
4718 FD, /*OutermostType*/false,
4719 /*EncodingProperty*/false,
4720 /*StructField*/true);
4721 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004722 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004723 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004724 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004725 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004726 return;
4727 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004728
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004729 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004730 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004731 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004732 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004733 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004734 return;
4735 }
Mike Stump11289f42009-09-09 15:08:12 +00004736
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004737 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004738 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004739 if (EncodeBlockParameters) {
4740 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4741
4742 S += '<';
4743 // Block return type
4744 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4745 ExpandPointedToStructures, ExpandStructures,
4746 FD,
4747 false /* OutermostType */,
4748 EncodingProperty,
4749 false /* StructField */,
4750 EncodeBlockParameters,
4751 EncodeClassNames);
4752 // Block self
4753 S += "@?";
4754 // Block parameters
4755 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4756 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4757 E = FPT->arg_type_end(); I && (I != E); ++I) {
4758 getObjCEncodingForTypeImpl(*I, S,
4759 ExpandPointedToStructures,
4760 ExpandStructures,
4761 FD,
4762 false /* OutermostType */,
4763 EncodingProperty,
4764 false /* StructField */,
4765 EncodeBlockParameters,
4766 EncodeClassNames);
4767 }
4768 }
4769 S += '>';
4770 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004771 return;
4772 }
Mike Stump11289f42009-09-09 15:08:12 +00004773
John McCall8b07ec22010-05-15 11:32:37 +00004774 // Ignore protocol qualifiers when mangling at this level.
4775 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4776 T = OT->getBaseType();
4777
John McCall8ccfcb52009-09-24 19:53:00 +00004778 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004779 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004780 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004781 S += '{';
4782 const IdentifierInfo *II = OI->getIdentifier();
4783 S += II->getName();
4784 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004785 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004786 DeepCollectObjCIvars(OI, true, Ivars);
4787 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004788 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004789 if (Field->isBitField())
4790 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004791 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004792 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004793 }
4794 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004795 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004796 }
Mike Stump11289f42009-09-09 15:08:12 +00004797
John McCall9dd450b2009-09-21 23:43:11 +00004798 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004799 if (OPT->isObjCIdType()) {
4800 S += '@';
4801 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004802 }
Mike Stump11289f42009-09-09 15:08:12 +00004803
Steve Narofff0c86112009-10-28 22:03:49 +00004804 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4805 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4806 // Since this is a binary compatibility issue, need to consult with runtime
4807 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004808 S += '#';
4809 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004810 }
Mike Stump11289f42009-09-09 15:08:12 +00004811
Chris Lattnere7cabb92009-07-13 00:10:46 +00004812 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004813 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004814 ExpandPointedToStructures,
4815 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004816 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004817 // Note that we do extended encoding of protocol qualifer list
4818 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004819 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004820 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4821 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004822 S += '<';
4823 S += (*I)->getNameAsString();
4824 S += '>';
4825 }
4826 S += '"';
4827 }
4828 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004829 }
Mike Stump11289f42009-09-09 15:08:12 +00004830
Chris Lattnere7cabb92009-07-13 00:10:46 +00004831 QualType PointeeTy = OPT->getPointeeType();
4832 if (!EncodingProperty &&
4833 isa<TypedefType>(PointeeTy.getTypePtr())) {
4834 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004835 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004836 // {...};
4837 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004838 getObjCEncodingForTypeImpl(PointeeTy, S,
4839 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004840 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004841 return;
4842 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004843
4844 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004845 if (OPT->getInterfaceDecl() &&
4846 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004847 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004848 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004849 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4850 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004851 S += '<';
4852 S += (*I)->getNameAsString();
4853 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004854 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004855 S += '"';
4856 }
4857 return;
4858 }
Mike Stump11289f42009-09-09 15:08:12 +00004859
John McCalla9e6e8d2010-05-17 23:56:34 +00004860 // gcc just blithely ignores member pointers.
4861 // TODO: maybe there should be a mangling for these
4862 if (T->getAs<MemberPointerType>())
4863 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004864
4865 if (T->isVectorType()) {
4866 // This matches gcc's encoding, even though technically it is
4867 // insufficient.
4868 // FIXME. We should do a better job than gcc.
4869 return;
4870 }
4871
David Blaikie83d382b2011-09-23 05:06:16 +00004872 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004873}
4874
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004875void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4876 std::string &S,
4877 const FieldDecl *FD,
4878 bool includeVBases) const {
4879 assert(RDecl && "Expected non-null RecordDecl");
4880 assert(!RDecl->isUnion() && "Should not be called for unions");
4881 if (!RDecl->getDefinition())
4882 return;
4883
4884 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4885 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4886 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4887
4888 if (CXXRec) {
4889 for (CXXRecordDecl::base_class_iterator
4890 BI = CXXRec->bases_begin(),
4891 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4892 if (!BI->isVirtual()) {
4893 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004894 if (base->isEmpty())
4895 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00004896 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004897 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4898 std::make_pair(offs, base));
4899 }
4900 }
4901 }
4902
4903 unsigned i = 0;
4904 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4905 FieldEnd = RDecl->field_end();
4906 Field != FieldEnd; ++Field, ++i) {
4907 uint64_t offs = layout.getFieldOffset(i);
4908 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00004909 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004910 }
4911
4912 if (CXXRec && includeVBases) {
4913 for (CXXRecordDecl::base_class_iterator
4914 BI = CXXRec->vbases_begin(),
4915 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4916 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004917 if (base->isEmpty())
4918 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00004919 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004920 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4921 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4922 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004923 }
4924 }
4925
4926 CharUnits size;
4927 if (CXXRec) {
4928 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4929 } else {
4930 size = layout.getSize();
4931 }
4932
4933 uint64_t CurOffs = 0;
4934 std::multimap<uint64_t, NamedDecl *>::iterator
4935 CurLayObj = FieldOrBaseOffsets.begin();
4936
Douglas Gregorf5d6c742012-04-27 22:30:01 +00004937 if (CXXRec && CXXRec->isDynamicClass() &&
4938 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004939 if (FD) {
4940 S += "\"_vptr$";
4941 std::string recname = CXXRec->getNameAsString();
4942 if (recname.empty()) recname = "?";
4943 S += recname;
4944 S += '"';
4945 }
4946 S += "^^?";
4947 CurOffs += getTypeSize(VoidPtrTy);
4948 }
4949
4950 if (!RDecl->hasFlexibleArrayMember()) {
4951 // Mark the end of the structure.
4952 uint64_t offs = toBits(size);
4953 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4954 std::make_pair(offs, (NamedDecl*)0));
4955 }
4956
4957 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4958 assert(CurOffs <= CurLayObj->first);
4959
4960 if (CurOffs < CurLayObj->first) {
4961 uint64_t padding = CurLayObj->first - CurOffs;
4962 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4963 // packing/alignment of members is different that normal, in which case
4964 // the encoding will be out-of-sync with the real layout.
4965 // If the runtime switches to just consider the size of types without
4966 // taking into account alignment, we could make padding explicit in the
4967 // encoding (e.g. using arrays of chars). The encoding strings would be
4968 // longer then though.
4969 CurOffs += padding;
4970 }
4971
4972 NamedDecl *dcl = CurLayObj->second;
4973 if (dcl == 0)
4974 break; // reached end of structure.
4975
4976 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4977 // We expand the bases without their virtual bases since those are going
4978 // in the initial structure. Note that this differs from gcc which
4979 // expands virtual bases each time one is encountered in the hierarchy,
4980 // making the encoding type bigger than it really is.
4981 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004982 assert(!base->isEmpty());
4983 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004984 } else {
4985 FieldDecl *field = cast<FieldDecl>(dcl);
4986 if (FD) {
4987 S += '"';
4988 S += field->getNameAsString();
4989 S += '"';
4990 }
4991
4992 if (field->isBitField()) {
4993 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004994 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004995 } else {
4996 QualType qt = field->getType();
4997 getLegacyIntegralTypeEncoding(qt);
4998 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4999 /*OutermostType*/false,
5000 /*EncodingProperty*/false,
5001 /*StructField*/true);
5002 CurOffs += getTypeSize(field->getType());
5003 }
5004 }
5005 }
5006}
5007
Mike Stump11289f42009-09-09 15:08:12 +00005008void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005009 std::string& S) const {
5010 if (QT & Decl::OBJC_TQ_In)
5011 S += 'n';
5012 if (QT & Decl::OBJC_TQ_Inout)
5013 S += 'N';
5014 if (QT & Decl::OBJC_TQ_Out)
5015 S += 'o';
5016 if (QT & Decl::OBJC_TQ_Bycopy)
5017 S += 'O';
5018 if (QT & Decl::OBJC_TQ_Byref)
5019 S += 'R';
5020 if (QT & Decl::OBJC_TQ_Oneway)
5021 S += 'V';
5022}
5023
Douglas Gregor3ea72692011-08-12 05:46:01 +00005024TypedefDecl *ASTContext::getObjCIdDecl() const {
5025 if (!ObjCIdDecl) {
5026 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5027 T = getObjCObjectPointerType(T);
5028 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5029 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5030 getTranslationUnitDecl(),
5031 SourceLocation(), SourceLocation(),
5032 &Idents.get("id"), IdInfo);
5033 }
5034
5035 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005036}
5037
Douglas Gregor52e02802011-08-12 06:17:30 +00005038TypedefDecl *ASTContext::getObjCSelDecl() const {
5039 if (!ObjCSelDecl) {
5040 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5041 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5042 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5043 getTranslationUnitDecl(),
5044 SourceLocation(), SourceLocation(),
5045 &Idents.get("SEL"), SelInfo);
5046 }
5047 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005048}
5049
Douglas Gregor0a586182011-08-12 05:59:41 +00005050TypedefDecl *ASTContext::getObjCClassDecl() const {
5051 if (!ObjCClassDecl) {
5052 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5053 T = getObjCObjectPointerType(T);
5054 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5055 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5056 getTranslationUnitDecl(),
5057 SourceLocation(), SourceLocation(),
5058 &Idents.get("Class"), ClassInfo);
5059 }
5060
5061 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005062}
5063
Douglas Gregord53ae832012-01-17 18:09:05 +00005064ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5065 if (!ObjCProtocolClassDecl) {
5066 ObjCProtocolClassDecl
5067 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5068 SourceLocation(),
5069 &Idents.get("Protocol"),
5070 /*PrevDecl=*/0,
5071 SourceLocation(), true);
5072 }
5073
5074 return ObjCProtocolClassDecl;
5075}
5076
Meador Inge5d3fb222012-06-16 03:34:49 +00005077//===----------------------------------------------------------------------===//
5078// __builtin_va_list Construction Functions
5079//===----------------------------------------------------------------------===//
5080
5081static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5082 // typedef char* __builtin_va_list;
5083 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5084 TypeSourceInfo *TInfo
5085 = Context->getTrivialTypeSourceInfo(CharPtrType);
5086
5087 TypedefDecl *VaListTypeDecl
5088 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5089 Context->getTranslationUnitDecl(),
5090 SourceLocation(), SourceLocation(),
5091 &Context->Idents.get("__builtin_va_list"),
5092 TInfo);
5093 return VaListTypeDecl;
5094}
5095
5096static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5097 // typedef void* __builtin_va_list;
5098 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5099 TypeSourceInfo *TInfo
5100 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5101
5102 TypedefDecl *VaListTypeDecl
5103 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5104 Context->getTranslationUnitDecl(),
5105 SourceLocation(), SourceLocation(),
5106 &Context->Idents.get("__builtin_va_list"),
5107 TInfo);
5108 return VaListTypeDecl;
5109}
5110
5111static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5112 // typedef struct __va_list_tag {
5113 RecordDecl *VaListTagDecl;
5114
5115 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5116 Context->getTranslationUnitDecl(),
5117 &Context->Idents.get("__va_list_tag"));
5118 VaListTagDecl->startDefinition();
5119
5120 const size_t NumFields = 5;
5121 QualType FieldTypes[NumFields];
5122 const char *FieldNames[NumFields];
5123
5124 // unsigned char gpr;
5125 FieldTypes[0] = Context->UnsignedCharTy;
5126 FieldNames[0] = "gpr";
5127
5128 // unsigned char fpr;
5129 FieldTypes[1] = Context->UnsignedCharTy;
5130 FieldNames[1] = "fpr";
5131
5132 // unsigned short reserved;
5133 FieldTypes[2] = Context->UnsignedShortTy;
5134 FieldNames[2] = "reserved";
5135
5136 // void* overflow_arg_area;
5137 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5138 FieldNames[3] = "overflow_arg_area";
5139
5140 // void* reg_save_area;
5141 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5142 FieldNames[4] = "reg_save_area";
5143
5144 // Create fields
5145 for (unsigned i = 0; i < NumFields; ++i) {
5146 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5147 SourceLocation(),
5148 SourceLocation(),
5149 &Context->Idents.get(FieldNames[i]),
5150 FieldTypes[i], /*TInfo=*/0,
5151 /*BitWidth=*/0,
5152 /*Mutable=*/false,
5153 ICIS_NoInit);
5154 Field->setAccess(AS_public);
5155 VaListTagDecl->addDecl(Field);
5156 }
5157 VaListTagDecl->completeDefinition();
5158 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005159 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005160
5161 // } __va_list_tag;
5162 TypedefDecl *VaListTagTypedefDecl
5163 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5164 Context->getTranslationUnitDecl(),
5165 SourceLocation(), SourceLocation(),
5166 &Context->Idents.get("__va_list_tag"),
5167 Context->getTrivialTypeSourceInfo(VaListTagType));
5168 QualType VaListTagTypedefType =
5169 Context->getTypedefType(VaListTagTypedefDecl);
5170
5171 // typedef __va_list_tag __builtin_va_list[1];
5172 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5173 QualType VaListTagArrayType
5174 = Context->getConstantArrayType(VaListTagTypedefType,
5175 Size, ArrayType::Normal, 0);
5176 TypeSourceInfo *TInfo
5177 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5178 TypedefDecl *VaListTypedefDecl
5179 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5180 Context->getTranslationUnitDecl(),
5181 SourceLocation(), SourceLocation(),
5182 &Context->Idents.get("__builtin_va_list"),
5183 TInfo);
5184
5185 return VaListTypedefDecl;
5186}
5187
5188static TypedefDecl *
5189CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5190 // typedef struct __va_list_tag {
5191 RecordDecl *VaListTagDecl;
5192 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5193 Context->getTranslationUnitDecl(),
5194 &Context->Idents.get("__va_list_tag"));
5195 VaListTagDecl->startDefinition();
5196
5197 const size_t NumFields = 4;
5198 QualType FieldTypes[NumFields];
5199 const char *FieldNames[NumFields];
5200
5201 // unsigned gp_offset;
5202 FieldTypes[0] = Context->UnsignedIntTy;
5203 FieldNames[0] = "gp_offset";
5204
5205 // unsigned fp_offset;
5206 FieldTypes[1] = Context->UnsignedIntTy;
5207 FieldNames[1] = "fp_offset";
5208
5209 // void* overflow_arg_area;
5210 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5211 FieldNames[2] = "overflow_arg_area";
5212
5213 // void* reg_save_area;
5214 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5215 FieldNames[3] = "reg_save_area";
5216
5217 // Create fields
5218 for (unsigned i = 0; i < NumFields; ++i) {
5219 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5220 VaListTagDecl,
5221 SourceLocation(),
5222 SourceLocation(),
5223 &Context->Idents.get(FieldNames[i]),
5224 FieldTypes[i], /*TInfo=*/0,
5225 /*BitWidth=*/0,
5226 /*Mutable=*/false,
5227 ICIS_NoInit);
5228 Field->setAccess(AS_public);
5229 VaListTagDecl->addDecl(Field);
5230 }
5231 VaListTagDecl->completeDefinition();
5232 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005233 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005234
5235 // } __va_list_tag;
5236 TypedefDecl *VaListTagTypedefDecl
5237 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5238 Context->getTranslationUnitDecl(),
5239 SourceLocation(), SourceLocation(),
5240 &Context->Idents.get("__va_list_tag"),
5241 Context->getTrivialTypeSourceInfo(VaListTagType));
5242 QualType VaListTagTypedefType =
5243 Context->getTypedefType(VaListTagTypedefDecl);
5244
5245 // typedef __va_list_tag __builtin_va_list[1];
5246 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5247 QualType VaListTagArrayType
5248 = Context->getConstantArrayType(VaListTagTypedefType,
5249 Size, ArrayType::Normal,0);
5250 TypeSourceInfo *TInfo
5251 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5252 TypedefDecl *VaListTypedefDecl
5253 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5254 Context->getTranslationUnitDecl(),
5255 SourceLocation(), SourceLocation(),
5256 &Context->Idents.get("__builtin_va_list"),
5257 TInfo);
5258
5259 return VaListTypedefDecl;
5260}
5261
5262static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5263 // typedef int __builtin_va_list[4];
5264 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5265 QualType IntArrayType
5266 = Context->getConstantArrayType(Context->IntTy,
5267 Size, ArrayType::Normal, 0);
5268 TypedefDecl *VaListTypedefDecl
5269 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5270 Context->getTranslationUnitDecl(),
5271 SourceLocation(), SourceLocation(),
5272 &Context->Idents.get("__builtin_va_list"),
5273 Context->getTrivialTypeSourceInfo(IntArrayType));
5274
5275 return VaListTypedefDecl;
5276}
5277
5278static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5279 TargetInfo::BuiltinVaListKind Kind) {
5280 switch (Kind) {
5281 case TargetInfo::CharPtrBuiltinVaList:
5282 return CreateCharPtrBuiltinVaListDecl(Context);
5283 case TargetInfo::VoidPtrBuiltinVaList:
5284 return CreateVoidPtrBuiltinVaListDecl(Context);
5285 case TargetInfo::PowerABIBuiltinVaList:
5286 return CreatePowerABIBuiltinVaListDecl(Context);
5287 case TargetInfo::X86_64ABIBuiltinVaList:
5288 return CreateX86_64ABIBuiltinVaListDecl(Context);
5289 case TargetInfo::PNaClABIBuiltinVaList:
5290 return CreatePNaClABIBuiltinVaListDecl(Context);
5291 }
5292
5293 llvm_unreachable("Unhandled __builtin_va_list type kind");
5294}
5295
5296TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5297 if (!BuiltinVaListDecl)
5298 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5299
5300 return BuiltinVaListDecl;
5301}
5302
Meador Ingecfb60902012-07-01 15:57:25 +00005303QualType ASTContext::getVaListTagType() const {
5304 // Force the creation of VaListTagTy by building the __builtin_va_list
5305 // declaration.
5306 if (VaListTagTy.isNull())
5307 (void) getBuiltinVaListDecl();
5308
5309 return VaListTagTy;
5310}
5311
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005312void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005313 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005314 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005315
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005316 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005317}
5318
John McCalld28ae272009-12-02 08:04:21 +00005319/// \brief Retrieve the template name that corresponds to a non-empty
5320/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005321TemplateName
5322ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5323 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005324 unsigned size = End - Begin;
5325 assert(size > 1 && "set is not overloaded!");
5326
5327 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5328 size * sizeof(FunctionTemplateDecl*));
5329 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5330
5331 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005332 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005333 NamedDecl *D = *I;
5334 assert(isa<FunctionTemplateDecl>(D) ||
5335 (isa<UsingShadowDecl>(D) &&
5336 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5337 *Storage++ = D;
5338 }
5339
5340 return TemplateName(OT);
5341}
5342
Douglas Gregordc572a32009-03-30 22:58:21 +00005343/// \brief Retrieve the template name that represents a qualified
5344/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005345TemplateName
5346ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5347 bool TemplateKeyword,
5348 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005349 assert(NNS && "Missing nested-name-specifier in qualified template name");
5350
Douglas Gregorc42075a2010-02-04 18:10:26 +00005351 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005352 llvm::FoldingSetNodeID ID;
5353 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5354
5355 void *InsertPos = 0;
5356 QualifiedTemplateName *QTN =
5357 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5358 if (!QTN) {
5359 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5360 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5361 }
5362
5363 return TemplateName(QTN);
5364}
5365
5366/// \brief Retrieve the template name that represents a dependent
5367/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005368TemplateName
5369ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5370 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005371 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005372 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005373
5374 llvm::FoldingSetNodeID ID;
5375 DependentTemplateName::Profile(ID, NNS, Name);
5376
5377 void *InsertPos = 0;
5378 DependentTemplateName *QTN =
5379 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5380
5381 if (QTN)
5382 return TemplateName(QTN);
5383
5384 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5385 if (CanonNNS == NNS) {
5386 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5387 } else {
5388 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5389 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005390 DependentTemplateName *CheckQTN =
5391 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5392 assert(!CheckQTN && "Dependent type name canonicalization broken");
5393 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005394 }
5395
5396 DependentTemplateNames.InsertNode(QTN, InsertPos);
5397 return TemplateName(QTN);
5398}
5399
Douglas Gregor71395fa2009-11-04 00:56:37 +00005400/// \brief Retrieve the template name that represents a dependent
5401/// template name such as \c MetaFun::template operator+.
5402TemplateName
5403ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005404 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005405 assert((!NNS || NNS->isDependent()) &&
5406 "Nested name specifier must be dependent");
5407
5408 llvm::FoldingSetNodeID ID;
5409 DependentTemplateName::Profile(ID, NNS, Operator);
5410
5411 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005412 DependentTemplateName *QTN
5413 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005414
5415 if (QTN)
5416 return TemplateName(QTN);
5417
5418 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5419 if (CanonNNS == NNS) {
5420 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5421 } else {
5422 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5423 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005424
5425 DependentTemplateName *CheckQTN
5426 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5427 assert(!CheckQTN && "Dependent template name canonicalization broken");
5428 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005429 }
5430
5431 DependentTemplateNames.InsertNode(QTN, InsertPos);
5432 return TemplateName(QTN);
5433}
5434
Douglas Gregor5590be02011-01-15 06:45:20 +00005435TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005436ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5437 TemplateName replacement) const {
5438 llvm::FoldingSetNodeID ID;
5439 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5440
5441 void *insertPos = 0;
5442 SubstTemplateTemplateParmStorage *subst
5443 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5444
5445 if (!subst) {
5446 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5447 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5448 }
5449
5450 return TemplateName(subst);
5451}
5452
5453TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005454ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5455 const TemplateArgument &ArgPack) const {
5456 ASTContext &Self = const_cast<ASTContext &>(*this);
5457 llvm::FoldingSetNodeID ID;
5458 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5459
5460 void *InsertPos = 0;
5461 SubstTemplateTemplateParmPackStorage *Subst
5462 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5463
5464 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005465 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005466 ArgPack.pack_size(),
5467 ArgPack.pack_begin());
5468 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5469 }
5470
5471 return TemplateName(Subst);
5472}
5473
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005474/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005475/// TargetInfo, produce the corresponding type. The unsigned @p Type
5476/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005477CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005478 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005479 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005480 case TargetInfo::SignedShort: return ShortTy;
5481 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5482 case TargetInfo::SignedInt: return IntTy;
5483 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5484 case TargetInfo::SignedLong: return LongTy;
5485 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5486 case TargetInfo::SignedLongLong: return LongLongTy;
5487 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5488 }
5489
David Blaikie83d382b2011-09-23 05:06:16 +00005490 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005491}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005492
5493//===----------------------------------------------------------------------===//
5494// Type Predicates.
5495//===----------------------------------------------------------------------===//
5496
Fariborz Jahanian96207692009-02-18 21:49:28 +00005497/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5498/// garbage collection attribute.
5499///
John McCall553d45a2011-01-12 00:34:59 +00005500Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005501 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005502 return Qualifiers::GCNone;
5503
David Blaikiebbafb8a2012-03-11 07:00:24 +00005504 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005505 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5506
5507 // Default behaviour under objective-C's gc is for ObjC pointers
5508 // (or pointers to them) be treated as though they were declared
5509 // as __strong.
5510 if (GCAttrs == Qualifiers::GCNone) {
5511 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5512 return Qualifiers::Strong;
5513 else if (Ty->isPointerType())
5514 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5515 } else {
5516 // It's not valid to set GC attributes on anything that isn't a
5517 // pointer.
5518#ifndef NDEBUG
5519 QualType CT = Ty->getCanonicalTypeInternal();
5520 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5521 CT = AT->getElementType();
5522 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5523#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005524 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005525 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005526}
5527
Chris Lattner49af6a42008-04-07 06:51:04 +00005528//===----------------------------------------------------------------------===//
5529// Type Compatibility Testing
5530//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005531
Mike Stump11289f42009-09-09 15:08:12 +00005532/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005533/// compatible.
5534static bool areCompatVectorTypes(const VectorType *LHS,
5535 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005536 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005537 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005538 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005539}
5540
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005541bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5542 QualType SecondVec) {
5543 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5544 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5545
5546 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5547 return true;
5548
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005549 // Treat Neon vector types and most AltiVec vector types as if they are the
5550 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005551 const VectorType *First = FirstVec->getAs<VectorType>();
5552 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005553 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005554 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005555 First->getVectorKind() != VectorType::AltiVecPixel &&
5556 First->getVectorKind() != VectorType::AltiVecBool &&
5557 Second->getVectorKind() != VectorType::AltiVecPixel &&
5558 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005559 return true;
5560
5561 return false;
5562}
5563
Steve Naroff8e6aee52009-07-23 01:01:38 +00005564//===----------------------------------------------------------------------===//
5565// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5566//===----------------------------------------------------------------------===//
5567
5568/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5569/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005570bool
5571ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5572 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005573 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005574 return true;
5575 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5576 E = rProto->protocol_end(); PI != E; ++PI)
5577 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5578 return true;
5579 return false;
5580}
5581
Steve Naroff8e6aee52009-07-23 01:01:38 +00005582/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5583/// return true if lhs's protocols conform to rhs's protocol; false
5584/// otherwise.
5585bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5586 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5587 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5588 return false;
5589}
5590
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005591/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5592/// Class<p1, ...>.
5593bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5594 QualType rhs) {
5595 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5596 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5597 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5598
5599 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5600 E = lhsQID->qual_end(); I != E; ++I) {
5601 bool match = false;
5602 ObjCProtocolDecl *lhsProto = *I;
5603 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5604 E = rhsOPT->qual_end(); J != E; ++J) {
5605 ObjCProtocolDecl *rhsProto = *J;
5606 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5607 match = true;
5608 break;
5609 }
5610 }
5611 if (!match)
5612 return false;
5613 }
5614 return true;
5615}
5616
Steve Naroff8e6aee52009-07-23 01:01:38 +00005617/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5618/// ObjCQualifiedIDType.
5619bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5620 bool compare) {
5621 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005622 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005623 lhs->isObjCIdType() || lhs->isObjCClassType())
5624 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005625 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005626 rhs->isObjCIdType() || rhs->isObjCClassType())
5627 return true;
5628
5629 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005630 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005631
Steve Naroff8e6aee52009-07-23 01:01:38 +00005632 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005633
Steve Naroff8e6aee52009-07-23 01:01:38 +00005634 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005635 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005636 // make sure we check the class hierarchy.
5637 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5638 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5639 E = lhsQID->qual_end(); I != E; ++I) {
5640 // when comparing an id<P> on lhs with a static type on rhs,
5641 // see if static class implements all of id's protocols, directly or
5642 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005643 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005644 return false;
5645 }
5646 }
5647 // If there are no qualifiers and no interface, we have an 'id'.
5648 return true;
5649 }
Mike Stump11289f42009-09-09 15:08:12 +00005650 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005651 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5652 E = lhsQID->qual_end(); I != E; ++I) {
5653 ObjCProtocolDecl *lhsProto = *I;
5654 bool match = false;
5655
5656 // when comparing an id<P> on lhs with a static type on rhs,
5657 // see if static class implements all of id's protocols, directly or
5658 // through its super class and categories.
5659 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5660 E = rhsOPT->qual_end(); J != E; ++J) {
5661 ObjCProtocolDecl *rhsProto = *J;
5662 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5663 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5664 match = true;
5665 break;
5666 }
5667 }
Mike Stump11289f42009-09-09 15:08:12 +00005668 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005669 // make sure we check the class hierarchy.
5670 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5671 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5672 E = lhsQID->qual_end(); I != E; ++I) {
5673 // when comparing an id<P> on lhs with a static type on rhs,
5674 // see if static class implements all of id's protocols, directly or
5675 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005676 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005677 match = true;
5678 break;
5679 }
5680 }
5681 }
5682 if (!match)
5683 return false;
5684 }
Mike Stump11289f42009-09-09 15:08:12 +00005685
Steve Naroff8e6aee52009-07-23 01:01:38 +00005686 return true;
5687 }
Mike Stump11289f42009-09-09 15:08:12 +00005688
Steve Naroff8e6aee52009-07-23 01:01:38 +00005689 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5690 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5691
Mike Stump11289f42009-09-09 15:08:12 +00005692 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005693 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005694 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005695 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5696 E = lhsOPT->qual_end(); I != E; ++I) {
5697 ObjCProtocolDecl *lhsProto = *I;
5698 bool match = false;
5699
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005700 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005701 // see if static class implements all of id's protocols, directly or
5702 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005703 // First, lhs protocols in the qualifier list must be found, direct
5704 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005705 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5706 E = rhsQID->qual_end(); J != E; ++J) {
5707 ObjCProtocolDecl *rhsProto = *J;
5708 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5709 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5710 match = true;
5711 break;
5712 }
5713 }
5714 if (!match)
5715 return false;
5716 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005717
5718 // Static class's protocols, or its super class or category protocols
5719 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5720 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5721 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5722 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5723 // This is rather dubious but matches gcc's behavior. If lhs has
5724 // no type qualifier and its class has no static protocol(s)
5725 // assume that it is mismatch.
5726 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5727 return false;
5728 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5729 LHSInheritedProtocols.begin(),
5730 E = LHSInheritedProtocols.end(); I != E; ++I) {
5731 bool match = false;
5732 ObjCProtocolDecl *lhsProto = (*I);
5733 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5734 E = rhsQID->qual_end(); J != E; ++J) {
5735 ObjCProtocolDecl *rhsProto = *J;
5736 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5737 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5738 match = true;
5739 break;
5740 }
5741 }
5742 if (!match)
5743 return false;
5744 }
5745 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005746 return true;
5747 }
5748 return false;
5749}
5750
Eli Friedman47f77112008-08-22 00:56:42 +00005751/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005752/// compatible for assignment from RHS to LHS. This handles validation of any
5753/// protocol qualifiers on the LHS or RHS.
5754///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005755bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5756 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005757 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5758 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5759
Steve Naroff1329fa02009-07-15 18:40:39 +00005760 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005761 if (LHS->isObjCUnqualifiedIdOrClass() ||
5762 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005763 return true;
5764
John McCall8b07ec22010-05-15 11:32:37 +00005765 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005766 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5767 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005768 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005769
5770 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5771 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5772 QualType(RHSOPT,0));
5773
John McCall8b07ec22010-05-15 11:32:37 +00005774 // If we have 2 user-defined types, fall into that path.
5775 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005776 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005777
Steve Naroff8e6aee52009-07-23 01:01:38 +00005778 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005779}
5780
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005781/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005782/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005783/// arguments in block literals. When passed as arguments, passing 'A*' where
5784/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5785/// not OK. For the return type, the opposite is not OK.
5786bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5787 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005788 const ObjCObjectPointerType *RHSOPT,
5789 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005790 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005791 return true;
5792
5793 if (LHSOPT->isObjCBuiltinType()) {
5794 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5795 }
5796
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005797 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005798 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5799 QualType(RHSOPT,0),
5800 false);
5801
5802 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5803 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5804 if (LHS && RHS) { // We have 2 user-defined types.
5805 if (LHS != RHS) {
5806 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005807 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005808 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005809 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005810 }
5811 else
5812 return true;
5813 }
5814 return false;
5815}
5816
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005817/// getIntersectionOfProtocols - This routine finds the intersection of set
5818/// of protocols inherited from two distinct objective-c pointer objects.
5819/// It is used to build composite qualifier list of the composite type of
5820/// the conditional expression involving two objective-c pointer objects.
5821static
5822void getIntersectionOfProtocols(ASTContext &Context,
5823 const ObjCObjectPointerType *LHSOPT,
5824 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005825 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005826
John McCall8b07ec22010-05-15 11:32:37 +00005827 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5828 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5829 assert(LHS->getInterface() && "LHS must have an interface base");
5830 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005831
5832 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5833 unsigned LHSNumProtocols = LHS->getNumProtocols();
5834 if (LHSNumProtocols > 0)
5835 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5836 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005837 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005838 Context.CollectInheritedProtocols(LHS->getInterface(),
5839 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005840 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5841 LHSInheritedProtocols.end());
5842 }
5843
5844 unsigned RHSNumProtocols = RHS->getNumProtocols();
5845 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005846 ObjCProtocolDecl **RHSProtocols =
5847 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005848 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5849 if (InheritedProtocolSet.count(RHSProtocols[i]))
5850 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005851 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005852 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005853 Context.CollectInheritedProtocols(RHS->getInterface(),
5854 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005855 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5856 RHSInheritedProtocols.begin(),
5857 E = RHSInheritedProtocols.end(); I != E; ++I)
5858 if (InheritedProtocolSet.count((*I)))
5859 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005860 }
5861}
5862
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005863/// areCommonBaseCompatible - Returns common base class of the two classes if
5864/// one found. Note that this is O'2 algorithm. But it will be called as the
5865/// last type comparison in a ?-exp of ObjC pointer types before a
5866/// warning is issued. So, its invokation is extremely rare.
5867QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005868 const ObjCObjectPointerType *Lptr,
5869 const ObjCObjectPointerType *Rptr) {
5870 const ObjCObjectType *LHS = Lptr->getObjectType();
5871 const ObjCObjectType *RHS = Rptr->getObjectType();
5872 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5873 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005874 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005875 return QualType();
5876
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005877 do {
John McCall8b07ec22010-05-15 11:32:37 +00005878 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005879 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005880 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005881 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5882
5883 QualType Result = QualType(LHS, 0);
5884 if (!Protocols.empty())
5885 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5886 Result = getObjCObjectPointerType(Result);
5887 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005888 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005889 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005890
5891 return QualType();
5892}
5893
John McCall8b07ec22010-05-15 11:32:37 +00005894bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5895 const ObjCObjectType *RHS) {
5896 assert(LHS->getInterface() && "LHS is not an interface type");
5897 assert(RHS->getInterface() && "RHS is not an interface type");
5898
Chris Lattner49af6a42008-04-07 06:51:04 +00005899 // Verify that the base decls are compatible: the RHS must be a subclass of
5900 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005901 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005902 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005903
Chris Lattner49af6a42008-04-07 06:51:04 +00005904 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5905 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005906 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005907 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005908
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005909 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5910 // more detailed analysis is required.
5911 if (RHS->getNumProtocols() == 0) {
5912 // OK, if LHS is a superclass of RHS *and*
5913 // this superclass is assignment compatible with LHS.
5914 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005915 bool IsSuperClass =
5916 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5917 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005918 // OK if conversion of LHS to SuperClass results in narrowing of types
5919 // ; i.e., SuperClass may implement at least one of the protocols
5920 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5921 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5922 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005923 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005924 // If super class has no protocols, it is not a match.
5925 if (SuperClassInheritedProtocols.empty())
5926 return false;
5927
5928 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5929 LHSPE = LHS->qual_end();
5930 LHSPI != LHSPE; LHSPI++) {
5931 bool SuperImplementsProtocol = false;
5932 ObjCProtocolDecl *LHSProto = (*LHSPI);
5933
5934 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5935 SuperClassInheritedProtocols.begin(),
5936 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5937 ObjCProtocolDecl *SuperClassProto = (*I);
5938 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5939 SuperImplementsProtocol = true;
5940 break;
5941 }
5942 }
5943 if (!SuperImplementsProtocol)
5944 return false;
5945 }
5946 return true;
5947 }
5948 return false;
5949 }
Mike Stump11289f42009-09-09 15:08:12 +00005950
John McCall8b07ec22010-05-15 11:32:37 +00005951 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5952 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005953 LHSPI != LHSPE; LHSPI++) {
5954 bool RHSImplementsProtocol = false;
5955
5956 // If the RHS doesn't implement the protocol on the left, the types
5957 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005958 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5959 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005960 RHSPI != RHSPE; RHSPI++) {
5961 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005962 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005963 break;
5964 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005965 }
5966 // FIXME: For better diagnostics, consider passing back the protocol name.
5967 if (!RHSImplementsProtocol)
5968 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005969 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005970 // The RHS implements all protocols listed on the LHS.
5971 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005972}
5973
Steve Naroffb7605152009-02-12 17:52:19 +00005974bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5975 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005976 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5977 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005978
Steve Naroff7cae42b2009-07-10 23:34:53 +00005979 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005980 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005981
5982 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5983 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005984}
5985
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005986bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5987 return canAssignObjCInterfaces(
5988 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5989 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5990}
5991
Mike Stump11289f42009-09-09 15:08:12 +00005992/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005993/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005994/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005995/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005996bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5997 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005998 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00005999 return hasSameType(LHS, RHS);
6000
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006001 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006002}
6003
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006004bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006005 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006006}
6007
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006008bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6009 return !mergeTypes(LHS, RHS, true).isNull();
6010}
6011
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006012/// mergeTransparentUnionType - if T is a transparent union type and a member
6013/// of T is compatible with SubType, return the merged type, else return
6014/// QualType()
6015QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6016 bool OfBlockPointer,
6017 bool Unqualified) {
6018 if (const RecordType *UT = T->getAsUnionType()) {
6019 RecordDecl *UD = UT->getDecl();
6020 if (UD->hasAttr<TransparentUnionAttr>()) {
6021 for (RecordDecl::field_iterator it = UD->field_begin(),
6022 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006023 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006024 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6025 if (!MT.isNull())
6026 return MT;
6027 }
6028 }
6029 }
6030
6031 return QualType();
6032}
6033
6034/// mergeFunctionArgumentTypes - merge two types which appear as function
6035/// argument types
6036QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6037 bool OfBlockPointer,
6038 bool Unqualified) {
6039 // GNU extension: two types are compatible if they appear as a function
6040 // argument, one of the types is a transparent union type and the other
6041 // type is compatible with a union member
6042 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6043 Unqualified);
6044 if (!lmerge.isNull())
6045 return lmerge;
6046
6047 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6048 Unqualified);
6049 if (!rmerge.isNull())
6050 return rmerge;
6051
6052 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6053}
6054
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006055QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006056 bool OfBlockPointer,
6057 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006058 const FunctionType *lbase = lhs->getAs<FunctionType>();
6059 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006060 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6061 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006062 bool allLTypes = true;
6063 bool allRTypes = true;
6064
6065 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006066 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006067 if (OfBlockPointer) {
6068 QualType RHS = rbase->getResultType();
6069 QualType LHS = lbase->getResultType();
6070 bool UnqualifiedResult = Unqualified;
6071 if (!UnqualifiedResult)
6072 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006073 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006074 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006075 else
John McCall8c6b56f2010-12-15 01:06:38 +00006076 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6077 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006078 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006079
6080 if (Unqualified)
6081 retType = retType.getUnqualifiedType();
6082
6083 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6084 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6085 if (Unqualified) {
6086 LRetType = LRetType.getUnqualifiedType();
6087 RRetType = RRetType.getUnqualifiedType();
6088 }
6089
6090 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006091 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006092 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006093 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006094
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006095 // FIXME: double check this
6096 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6097 // rbase->getRegParmAttr() != 0 &&
6098 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006099 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6100 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006101
Douglas Gregor8c940862010-01-18 17:14:39 +00006102 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006103 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006104 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006105
John McCall8c6b56f2010-12-15 01:06:38 +00006106 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006107 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6108 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006109 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6110 return QualType();
6111
John McCall31168b02011-06-15 23:02:42 +00006112 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6113 return QualType();
6114
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006115 // functypes which return are preferred over those that do not.
6116 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6117 allLTypes = false;
6118 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6119 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006120 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6121 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006122
John McCall31168b02011-06-15 23:02:42 +00006123 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006124
Eli Friedman47f77112008-08-22 00:56:42 +00006125 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006126 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6127 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006128 unsigned lproto_nargs = lproto->getNumArgs();
6129 unsigned rproto_nargs = rproto->getNumArgs();
6130
6131 // Compatible functions must have the same number of arguments
6132 if (lproto_nargs != rproto_nargs)
6133 return QualType();
6134
6135 // Variadic and non-variadic functions aren't compatible
6136 if (lproto->isVariadic() != rproto->isVariadic())
6137 return QualType();
6138
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006139 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6140 return QualType();
6141
Fariborz Jahanian97676972011-09-28 21:52:05 +00006142 if (LangOpts.ObjCAutoRefCount &&
6143 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6144 return QualType();
6145
Eli Friedman47f77112008-08-22 00:56:42 +00006146 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006147 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006148 for (unsigned i = 0; i < lproto_nargs; i++) {
6149 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6150 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006151 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6152 OfBlockPointer,
6153 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006154 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006155
6156 if (Unqualified)
6157 argtype = argtype.getUnqualifiedType();
6158
Eli Friedman47f77112008-08-22 00:56:42 +00006159 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006160 if (Unqualified) {
6161 largtype = largtype.getUnqualifiedType();
6162 rargtype = rargtype.getUnqualifiedType();
6163 }
6164
Chris Lattner465fa322008-10-05 17:34:18 +00006165 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6166 allLTypes = false;
6167 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6168 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006169 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006170
Eli Friedman47f77112008-08-22 00:56:42 +00006171 if (allLTypes) return lhs;
6172 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006173
6174 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6175 EPI.ExtInfo = einfo;
6176 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006177 }
6178
6179 if (lproto) allRTypes = false;
6180 if (rproto) allLTypes = false;
6181
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006182 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006183 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006184 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006185 if (proto->isVariadic()) return QualType();
6186 // Check that the types are compatible with the types that
6187 // would result from default argument promotions (C99 6.7.5.3p15).
6188 // The only types actually affected are promotable integer
6189 // types and floats, which would be passed as a different
6190 // type depending on whether the prototype is visible.
6191 unsigned proto_nargs = proto->getNumArgs();
6192 for (unsigned i = 0; i < proto_nargs; ++i) {
6193 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006194
6195 // Look at the promotion type of enum types, since that is the type used
6196 // to pass enum values.
6197 if (const EnumType *Enum = argTy->getAs<EnumType>())
6198 argTy = Enum->getDecl()->getPromotionType();
6199
Eli Friedman47f77112008-08-22 00:56:42 +00006200 if (argTy->isPromotableIntegerType() ||
6201 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6202 return QualType();
6203 }
6204
6205 if (allLTypes) return lhs;
6206 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006207
6208 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6209 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006210 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006211 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006212 }
6213
6214 if (allLTypes) return lhs;
6215 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006216 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006217}
6218
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006219QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006220 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006221 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006222 // C++ [expr]: If an expression initially has the type "reference to T", the
6223 // type is adjusted to "T" prior to any further analysis, the expression
6224 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006225 // expression is an lvalue unless the reference is an rvalue reference and
6226 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006227 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6228 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006229
6230 if (Unqualified) {
6231 LHS = LHS.getUnqualifiedType();
6232 RHS = RHS.getUnqualifiedType();
6233 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006234
Eli Friedman47f77112008-08-22 00:56:42 +00006235 QualType LHSCan = getCanonicalType(LHS),
6236 RHSCan = getCanonicalType(RHS);
6237
6238 // If two types are identical, they are compatible.
6239 if (LHSCan == RHSCan)
6240 return LHS;
6241
John McCall8ccfcb52009-09-24 19:53:00 +00006242 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006243 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6244 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006245 if (LQuals != RQuals) {
6246 // If any of these qualifiers are different, we have a type
6247 // mismatch.
6248 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006249 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6250 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006251 return QualType();
6252
6253 // Exactly one GC qualifier difference is allowed: __strong is
6254 // okay if the other type has no GC qualifier but is an Objective
6255 // C object pointer (i.e. implicitly strong by default). We fix
6256 // this by pretending that the unqualified type was actually
6257 // qualified __strong.
6258 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6259 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6260 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6261
6262 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6263 return QualType();
6264
6265 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6266 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6267 }
6268 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6269 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6270 }
Eli Friedman47f77112008-08-22 00:56:42 +00006271 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006272 }
6273
6274 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006275
Eli Friedmandcca6332009-06-01 01:22:52 +00006276 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6277 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006278
Chris Lattnerfd652912008-01-14 05:45:46 +00006279 // We want to consider the two function types to be the same for these
6280 // comparisons, just force one to the other.
6281 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6282 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006283
6284 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006285 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6286 LHSClass = Type::ConstantArray;
6287 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6288 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006289
John McCall8b07ec22010-05-15 11:32:37 +00006290 // ObjCInterfaces are just specialized ObjCObjects.
6291 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6292 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6293
Nate Begemance4d7fc2008-04-18 23:10:10 +00006294 // Canonicalize ExtVector -> Vector.
6295 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6296 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006297
Chris Lattner95554662008-04-07 05:43:21 +00006298 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006299 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006300 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006301 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006302 // Compatibility is based on the underlying type, not the promotion
6303 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006304 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006305 QualType TINT = ETy->getDecl()->getIntegerType();
6306 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006307 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006308 }
John McCall9dd450b2009-09-21 23:43:11 +00006309 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006310 QualType TINT = ETy->getDecl()->getIntegerType();
6311 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006312 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006313 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006314 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006315 if (OfBlockPointer && !BlockReturnType) {
6316 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6317 return LHS;
6318 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6319 return RHS;
6320 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006321
Eli Friedman47f77112008-08-22 00:56:42 +00006322 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006323 }
Eli Friedman47f77112008-08-22 00:56:42 +00006324
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006325 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006326 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006327#define TYPE(Class, Base)
6328#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006329#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006330#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6331#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6332#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006333 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006334
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006335 case Type::LValueReference:
6336 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006337 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006338 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006339
John McCall8b07ec22010-05-15 11:32:37 +00006340 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006341 case Type::IncompleteArray:
6342 case Type::VariableArray:
6343 case Type::FunctionProto:
6344 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006345 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006346
Chris Lattnerfd652912008-01-14 05:45:46 +00006347 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006348 {
6349 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006350 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6351 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006352 if (Unqualified) {
6353 LHSPointee = LHSPointee.getUnqualifiedType();
6354 RHSPointee = RHSPointee.getUnqualifiedType();
6355 }
6356 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6357 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006358 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006359 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006360 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006361 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006362 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006363 return getPointerType(ResultType);
6364 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006365 case Type::BlockPointer:
6366 {
6367 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006368 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6369 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006370 if (Unqualified) {
6371 LHSPointee = LHSPointee.getUnqualifiedType();
6372 RHSPointee = RHSPointee.getUnqualifiedType();
6373 }
6374 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6375 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006376 if (ResultType.isNull()) return QualType();
6377 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6378 return LHS;
6379 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6380 return RHS;
6381 return getBlockPointerType(ResultType);
6382 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006383 case Type::Atomic:
6384 {
6385 // Merge two pointer types, while trying to preserve typedef info
6386 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6387 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6388 if (Unqualified) {
6389 LHSValue = LHSValue.getUnqualifiedType();
6390 RHSValue = RHSValue.getUnqualifiedType();
6391 }
6392 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6393 Unqualified);
6394 if (ResultType.isNull()) return QualType();
6395 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6396 return LHS;
6397 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6398 return RHS;
6399 return getAtomicType(ResultType);
6400 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006401 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006402 {
6403 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6404 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6405 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6406 return QualType();
6407
6408 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6409 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006410 if (Unqualified) {
6411 LHSElem = LHSElem.getUnqualifiedType();
6412 RHSElem = RHSElem.getUnqualifiedType();
6413 }
6414
6415 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006416 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006417 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6418 return LHS;
6419 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6420 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006421 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6422 ArrayType::ArraySizeModifier(), 0);
6423 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6424 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006425 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6426 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006427 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6428 return LHS;
6429 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6430 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006431 if (LVAT) {
6432 // FIXME: This isn't correct! But tricky to implement because
6433 // the array's size has to be the size of LHS, but the type
6434 // has to be different.
6435 return LHS;
6436 }
6437 if (RVAT) {
6438 // FIXME: This isn't correct! But tricky to implement because
6439 // the array's size has to be the size of RHS, but the type
6440 // has to be different.
6441 return RHS;
6442 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006443 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6444 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006445 return getIncompleteArrayType(ResultType,
6446 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006447 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006448 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006449 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006450 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006451 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006452 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006453 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006454 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006455 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006456 case Type::Complex:
6457 // Distinct complex types are incompatible.
6458 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006459 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006460 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006461 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6462 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006463 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006464 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006465 case Type::ObjCObject: {
6466 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006467 // FIXME: This should be type compatibility, e.g. whether
6468 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006469 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6470 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6471 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006472 return LHS;
6473
Eli Friedman47f77112008-08-22 00:56:42 +00006474 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006475 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006476 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006477 if (OfBlockPointer) {
6478 if (canAssignObjCInterfacesInBlockPointer(
6479 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006480 RHS->getAs<ObjCObjectPointerType>(),
6481 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006482 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006483 return QualType();
6484 }
John McCall9dd450b2009-09-21 23:43:11 +00006485 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6486 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006487 return LHS;
6488
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006489 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006490 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006491 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006492
David Blaikie8a40f702012-01-17 06:56:22 +00006493 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006494}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006495
Fariborz Jahanian97676972011-09-28 21:52:05 +00006496bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6497 const FunctionProtoType *FromFunctionType,
6498 const FunctionProtoType *ToFunctionType) {
6499 if (FromFunctionType->hasAnyConsumedArgs() !=
6500 ToFunctionType->hasAnyConsumedArgs())
6501 return false;
6502 FunctionProtoType::ExtProtoInfo FromEPI =
6503 FromFunctionType->getExtProtoInfo();
6504 FunctionProtoType::ExtProtoInfo ToEPI =
6505 ToFunctionType->getExtProtoInfo();
6506 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6507 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6508 ArgIdx != NumArgs; ++ArgIdx) {
6509 if (FromEPI.ConsumedArguments[ArgIdx] !=
6510 ToEPI.ConsumedArguments[ArgIdx])
6511 return false;
6512 }
6513 return true;
6514}
6515
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006516/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6517/// 'RHS' attributes and returns the merged version; including for function
6518/// return types.
6519QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6520 QualType LHSCan = getCanonicalType(LHS),
6521 RHSCan = getCanonicalType(RHS);
6522 // If two types are identical, they are compatible.
6523 if (LHSCan == RHSCan)
6524 return LHS;
6525 if (RHSCan->isFunctionType()) {
6526 if (!LHSCan->isFunctionType())
6527 return QualType();
6528 QualType OldReturnType =
6529 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6530 QualType NewReturnType =
6531 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6532 QualType ResReturnType =
6533 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6534 if (ResReturnType.isNull())
6535 return QualType();
6536 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6537 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6538 // In either case, use OldReturnType to build the new function type.
6539 const FunctionType *F = LHS->getAs<FunctionType>();
6540 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006541 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6542 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006543 QualType ResultType
6544 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006545 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006546 return ResultType;
6547 }
6548 }
6549 return QualType();
6550 }
6551
6552 // If the qualifiers are different, the types can still be merged.
6553 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6554 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6555 if (LQuals != RQuals) {
6556 // If any of these qualifiers are different, we have a type mismatch.
6557 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6558 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6559 return QualType();
6560
6561 // Exactly one GC qualifier difference is allowed: __strong is
6562 // okay if the other type has no GC qualifier but is an Objective
6563 // C object pointer (i.e. implicitly strong by default). We fix
6564 // this by pretending that the unqualified type was actually
6565 // qualified __strong.
6566 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6567 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6568 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6569
6570 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6571 return QualType();
6572
6573 if (GC_L == Qualifiers::Strong)
6574 return LHS;
6575 if (GC_R == Qualifiers::Strong)
6576 return RHS;
6577 return QualType();
6578 }
6579
6580 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6581 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6582 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6583 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6584 if (ResQT == LHSBaseQT)
6585 return LHS;
6586 if (ResQT == RHSBaseQT)
6587 return RHS;
6588 }
6589 return QualType();
6590}
6591
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006592//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006593// Integer Predicates
6594//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006595
Jay Foad39c79802011-01-12 09:06:06 +00006596unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006597 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006598 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006599 if (T->isBooleanType())
6600 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006601 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006602 return (unsigned)getTypeSize(T);
6603}
6604
6605QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006606 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006607
6608 // Turn <4 x signed int> -> <4 x unsigned int>
6609 if (const VectorType *VTy = T->getAs<VectorType>())
6610 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006611 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006612
6613 // For enums, we return the unsigned version of the base type.
6614 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006615 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006616
6617 const BuiltinType *BTy = T->getAs<BuiltinType>();
6618 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006619 switch (BTy->getKind()) {
6620 case BuiltinType::Char_S:
6621 case BuiltinType::SChar:
6622 return UnsignedCharTy;
6623 case BuiltinType::Short:
6624 return UnsignedShortTy;
6625 case BuiltinType::Int:
6626 return UnsignedIntTy;
6627 case BuiltinType::Long:
6628 return UnsignedLongTy;
6629 case BuiltinType::LongLong:
6630 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006631 case BuiltinType::Int128:
6632 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006633 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006634 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006635 }
6636}
6637
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006638ASTMutationListener::~ASTMutationListener() { }
6639
Chris Lattnerecd79c62009-06-14 00:45:47 +00006640
6641//===----------------------------------------------------------------------===//
6642// Builtin Type Computation
6643//===----------------------------------------------------------------------===//
6644
6645/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006646/// pointer over the consumed characters. This returns the resultant type. If
6647/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6648/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6649/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006650///
6651/// RequiresICE is filled in on return to indicate whether the value is required
6652/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006653static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006654 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006655 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006656 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006657 // Modifiers.
6658 int HowLong = 0;
6659 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006660 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006661
Chris Lattnerdc226c22010-10-01 22:42:38 +00006662 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006663 bool Done = false;
6664 while (!Done) {
6665 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006666 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006667 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006668 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006669 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006670 case 'S':
6671 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6672 assert(!Signed && "Can't use 'S' modifier multiple times!");
6673 Signed = true;
6674 break;
6675 case 'U':
6676 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6677 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6678 Unsigned = true;
6679 break;
6680 case 'L':
6681 assert(HowLong <= 2 && "Can't have LLLL modifier");
6682 ++HowLong;
6683 break;
6684 }
6685 }
6686
6687 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006688
Chris Lattnerecd79c62009-06-14 00:45:47 +00006689 // Read the base type.
6690 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006691 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006692 case 'v':
6693 assert(HowLong == 0 && !Signed && !Unsigned &&
6694 "Bad modifiers used with 'v'!");
6695 Type = Context.VoidTy;
6696 break;
6697 case 'f':
6698 assert(HowLong == 0 && !Signed && !Unsigned &&
6699 "Bad modifiers used with 'f'!");
6700 Type = Context.FloatTy;
6701 break;
6702 case 'd':
6703 assert(HowLong < 2 && !Signed && !Unsigned &&
6704 "Bad modifiers used with 'd'!");
6705 if (HowLong)
6706 Type = Context.LongDoubleTy;
6707 else
6708 Type = Context.DoubleTy;
6709 break;
6710 case 's':
6711 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6712 if (Unsigned)
6713 Type = Context.UnsignedShortTy;
6714 else
6715 Type = Context.ShortTy;
6716 break;
6717 case 'i':
6718 if (HowLong == 3)
6719 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6720 else if (HowLong == 2)
6721 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6722 else if (HowLong == 1)
6723 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6724 else
6725 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6726 break;
6727 case 'c':
6728 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6729 if (Signed)
6730 Type = Context.SignedCharTy;
6731 else if (Unsigned)
6732 Type = Context.UnsignedCharTy;
6733 else
6734 Type = Context.CharTy;
6735 break;
6736 case 'b': // boolean
6737 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6738 Type = Context.BoolTy;
6739 break;
6740 case 'z': // size_t.
6741 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6742 Type = Context.getSizeType();
6743 break;
6744 case 'F':
6745 Type = Context.getCFConstantStringType();
6746 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006747 case 'G':
6748 Type = Context.getObjCIdType();
6749 break;
6750 case 'H':
6751 Type = Context.getObjCSelType();
6752 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006753 case 'a':
6754 Type = Context.getBuiltinVaListType();
6755 assert(!Type.isNull() && "builtin va list type not initialized!");
6756 break;
6757 case 'A':
6758 // This is a "reference" to a va_list; however, what exactly
6759 // this means depends on how va_list is defined. There are two
6760 // different kinds of va_list: ones passed by value, and ones
6761 // passed by reference. An example of a by-value va_list is
6762 // x86, where va_list is a char*. An example of by-ref va_list
6763 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6764 // we want this argument to be a char*&; for x86-64, we want
6765 // it to be a __va_list_tag*.
6766 Type = Context.getBuiltinVaListType();
6767 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006768 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006769 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006770 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006771 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006772 break;
6773 case 'V': {
6774 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006775 unsigned NumElements = strtoul(Str, &End, 10);
6776 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006777 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006778
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006779 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6780 RequiresICE, false);
6781 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006782
6783 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006784 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006785 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006786 break;
6787 }
Douglas Gregorfed66992012-06-07 18:08:25 +00006788 case 'E': {
6789 char *End;
6790
6791 unsigned NumElements = strtoul(Str, &End, 10);
6792 assert(End != Str && "Missing vector size");
6793
6794 Str = End;
6795
6796 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6797 false);
6798 Type = Context.getExtVectorType(ElementType, NumElements);
6799 break;
6800 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006801 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006802 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6803 false);
6804 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006805 Type = Context.getComplexType(ElementType);
6806 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006807 }
6808 case 'Y' : {
6809 Type = Context.getPointerDiffType();
6810 break;
6811 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006812 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006813 Type = Context.getFILEType();
6814 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006815 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006816 return QualType();
6817 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006818 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006819 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006820 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006821 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006822 else
6823 Type = Context.getjmp_bufType();
6824
Mike Stump2adb4da2009-07-28 23:47:15 +00006825 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006826 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006827 return QualType();
6828 }
6829 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006830 case 'K':
6831 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6832 Type = Context.getucontext_tType();
6833
6834 if (Type.isNull()) {
6835 Error = ASTContext::GE_Missing_ucontext;
6836 return QualType();
6837 }
6838 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006839 }
Mike Stump11289f42009-09-09 15:08:12 +00006840
Chris Lattnerdc226c22010-10-01 22:42:38 +00006841 // If there are modifiers and if we're allowed to parse them, go for it.
6842 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006843 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006844 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006845 default: Done = true; --Str; break;
6846 case '*':
6847 case '&': {
6848 // Both pointers and references can have their pointee types
6849 // qualified with an address space.
6850 char *End;
6851 unsigned AddrSpace = strtoul(Str, &End, 10);
6852 if (End != Str && AddrSpace != 0) {
6853 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6854 Str = End;
6855 }
6856 if (c == '*')
6857 Type = Context.getPointerType(Type);
6858 else
6859 Type = Context.getLValueReferenceType(Type);
6860 break;
6861 }
6862 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6863 case 'C':
6864 Type = Type.withConst();
6865 break;
6866 case 'D':
6867 Type = Context.getVolatileType(Type);
6868 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006869 case 'R':
6870 Type = Type.withRestrict();
6871 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006872 }
6873 }
Chris Lattner84733392010-10-01 07:13:18 +00006874
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006875 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006876 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006877
Chris Lattnerecd79c62009-06-14 00:45:47 +00006878 return Type;
6879}
6880
6881/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006882QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006883 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006884 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006885 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006886
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006887 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006888
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006889 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006890 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006891 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6892 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006893 if (Error != GE_None)
6894 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006895
6896 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6897
Chris Lattnerecd79c62009-06-14 00:45:47 +00006898 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006899 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006900 if (Error != GE_None)
6901 return QualType();
6902
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006903 // If this argument is required to be an IntegerConstantExpression and the
6904 // caller cares, fill in the bitmask we return.
6905 if (RequiresICE && IntegerConstantArgs)
6906 *IntegerConstantArgs |= 1 << ArgTypes.size();
6907
Chris Lattnerecd79c62009-06-14 00:45:47 +00006908 // Do array -> pointer decay. The builtin should use the decayed type.
6909 if (Ty->isArrayType())
6910 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006911
Chris Lattnerecd79c62009-06-14 00:45:47 +00006912 ArgTypes.push_back(Ty);
6913 }
6914
6915 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6916 "'.' should only occur at end of builtin type list!");
6917
John McCall991eb4b2010-12-21 00:44:39 +00006918 FunctionType::ExtInfo EI;
6919 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6920
6921 bool Variadic = (TypeStr[0] == '.');
6922
6923 // We really shouldn't be making a no-proto type here, especially in C++.
6924 if (ArgTypes.empty() && Variadic)
6925 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006926
John McCalldb40c7f2010-12-14 08:05:40 +00006927 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006928 EPI.ExtInfo = EI;
6929 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006930
6931 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006932}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006933
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006934GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6935 GVALinkage External = GVA_StrongExternal;
6936
6937 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006938 switch (L) {
6939 case NoLinkage:
6940 case InternalLinkage:
6941 case UniqueExternalLinkage:
6942 return GVA_Internal;
6943
6944 case ExternalLinkage:
6945 switch (FD->getTemplateSpecializationKind()) {
6946 case TSK_Undeclared:
6947 case TSK_ExplicitSpecialization:
6948 External = GVA_StrongExternal;
6949 break;
6950
6951 case TSK_ExplicitInstantiationDefinition:
6952 return GVA_ExplicitTemplateInstantiation;
6953
6954 case TSK_ExplicitInstantiationDeclaration:
6955 case TSK_ImplicitInstantiation:
6956 External = GVA_TemplateInstantiation;
6957 break;
6958 }
6959 }
6960
6961 if (!FD->isInlined())
6962 return External;
6963
David Blaikiebbafb8a2012-03-11 07:00:24 +00006964 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006965 // GNU or C99 inline semantics. Determine whether this symbol should be
6966 // externally visible.
6967 if (FD->isInlineDefinitionExternallyVisible())
6968 return External;
6969
6970 // C99 inline semantics, where the symbol is not externally visible.
6971 return GVA_C99Inline;
6972 }
6973
6974 // C++0x [temp.explicit]p9:
6975 // [ Note: The intent is that an inline function that is the subject of
6976 // an explicit instantiation declaration will still be implicitly
6977 // instantiated when used so that the body can be considered for
6978 // inlining, but that no out-of-line copy of the inline function would be
6979 // generated in the translation unit. -- end note ]
6980 if (FD->getTemplateSpecializationKind()
6981 == TSK_ExplicitInstantiationDeclaration)
6982 return GVA_C99Inline;
6983
6984 return GVA_CXXInline;
6985}
6986
6987GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6988 // If this is a static data member, compute the kind of template
6989 // specialization. Otherwise, this variable is not part of a
6990 // template.
6991 TemplateSpecializationKind TSK = TSK_Undeclared;
6992 if (VD->isStaticDataMember())
6993 TSK = VD->getTemplateSpecializationKind();
6994
6995 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006996 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006997 VD->getType()->getLinkage() == UniqueExternalLinkage)
6998 L = UniqueExternalLinkage;
6999
7000 switch (L) {
7001 case NoLinkage:
7002 case InternalLinkage:
7003 case UniqueExternalLinkage:
7004 return GVA_Internal;
7005
7006 case ExternalLinkage:
7007 switch (TSK) {
7008 case TSK_Undeclared:
7009 case TSK_ExplicitSpecialization:
7010 return GVA_StrongExternal;
7011
7012 case TSK_ExplicitInstantiationDeclaration:
7013 llvm_unreachable("Variable should not be instantiated");
7014 // Fall through to treat this like any other instantiation.
7015
7016 case TSK_ExplicitInstantiationDefinition:
7017 return GVA_ExplicitTemplateInstantiation;
7018
7019 case TSK_ImplicitInstantiation:
7020 return GVA_TemplateInstantiation;
7021 }
7022 }
7023
David Blaikie8a40f702012-01-17 06:56:22 +00007024 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007025}
7026
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007027bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007028 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7029 if (!VD->isFileVarDecl())
7030 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007031 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007032 return false;
7033
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007034 // Weak references don't produce any output by themselves.
7035 if (D->hasAttr<WeakRefAttr>())
7036 return false;
7037
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007038 // Aliases and used decls are required.
7039 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7040 return true;
7041
7042 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7043 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007044 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007045 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007046
7047 // Constructors and destructors are required.
7048 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7049 return true;
7050
7051 // The key function for a class is required.
7052 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7053 const CXXRecordDecl *RD = MD->getParent();
7054 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7055 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7056 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7057 return true;
7058 }
7059 }
7060
7061 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7062
7063 // static, static inline, always_inline, and extern inline functions can
7064 // always be deferred. Normal inline functions can be deferred in C99/C++.
7065 // Implicit template instantiations can also be deferred in C++.
7066 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007067 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007068 return false;
7069 return true;
7070 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007071
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007072 const VarDecl *VD = cast<VarDecl>(D);
7073 assert(VD->isFileVarDecl() && "Expected file scoped var");
7074
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007075 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7076 return false;
7077
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007078 // Structs that have non-trivial constructors or destructors are required.
7079
7080 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007081 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007082 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7083 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007084 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7085 RD->hasTrivialCopyConstructor() &&
7086 RD->hasTrivialMoveConstructor() &&
7087 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007088 return true;
7089 }
7090 }
7091
7092 GVALinkage L = GetGVALinkageForVariable(VD);
7093 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7094 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7095 return false;
7096 }
7097
7098 return true;
7099}
Charles Davis53c59df2010-08-16 03:33:14 +00007100
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007101CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007102 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007103 return ABI->getDefaultMethodCallConv(isVariadic);
7104}
7105
7106CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7107 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7108 return CC_Default;
7109 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007110}
7111
Jay Foad39c79802011-01-12 09:06:06 +00007112bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007113 // Pass through to the C++ ABI object
7114 return ABI->isNearlyEmpty(RD);
7115}
7116
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007117MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007118 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007119 case CXXABI_ARM:
7120 case CXXABI_Itanium:
7121 return createItaniumMangleContext(*this, getDiagnostics());
7122 case CXXABI_Microsoft:
7123 return createMicrosoftMangleContext(*this, getDiagnostics());
7124 }
David Blaikie83d382b2011-09-23 05:06:16 +00007125 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007126}
7127
Charles Davis53c59df2010-08-16 03:33:14 +00007128CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007129
7130size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007131 return ASTRecordLayouts.getMemorySize()
7132 + llvm::capacity_in_bytes(ObjCLayouts)
7133 + llvm::capacity_in_bytes(KeyFunctions)
7134 + llvm::capacity_in_bytes(ObjCImpls)
7135 + llvm::capacity_in_bytes(BlockVarCopyInits)
7136 + llvm::capacity_in_bytes(DeclAttrs)
7137 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7138 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7139 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7140 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7141 + llvm::capacity_in_bytes(OverriddenMethods)
7142 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007143 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007144 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007145}
Ted Kremenek540017e2011-10-06 05:00:56 +00007146
Douglas Gregor63798542012-02-20 19:44:39 +00007147unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7148 CXXRecordDecl *Lambda = CallOperator->getParent();
7149 return LambdaMangleContexts[Lambda->getDeclContext()]
7150 .getManglingNumber(CallOperator);
7151}
7152
7153
Ted Kremenek540017e2011-10-06 05:00:56 +00007154void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7155 ParamIndices[D] = index;
7156}
7157
7158unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7159 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7160 assert(I != ParamIndices.end() &&
7161 "ParmIndices lacks entry set by ParmVarDecl");
7162 return I->second;
7163}