blob: b0351d69adb5ab183627655aca049ae89b5e3c36 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Dmitri Gribenkoec925312012-07-06 00:28:32 +000016#include "clang/AST/CommentLexer.h"
17#include "clang/AST/CommentSema.h"
18#include "clang/AST/CommentParser.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000019#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000021#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000022#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000023#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000024#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000025#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000026#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000027#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000029#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000031#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000033#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000034#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000035#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000036#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000037#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000038#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000039
Chris Lattnerddc135e2006-11-10 06:34:16 +000040using namespace clang;
41
Douglas Gregor9672f922010-07-03 00:47:00 +000042unsigned ASTContext::NumImplicitDefaultConstructors;
43unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000044unsigned ASTContext::NumImplicitCopyConstructors;
45unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveConstructors;
47unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000048unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000052unsigned ASTContext::NumImplicitDestructors;
53unsigned ASTContext::NumImplicitDestructorsDeclared;
54
Steve Naroff0af91202007-04-27 21:51:21 +000055enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000056 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000057};
58
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000059RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000060 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
63 }
64
65 assert(D);
66
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000067 // User can not attach documentation to implicit declarations.
68 if (D->isImplicit())
69 return NULL;
70
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000071 // TODO: handle comments for function parameters properly.
72 if (isa<ParmVarDecl>(D))
73 return NULL;
74
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +000075 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000076
77 // If there are no comments anywhere, we won't find anything.
78 if (RawComments.empty())
79 return NULL;
80
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +000081 // Find declaration location.
82 // For Objective-C declarations we generally don't expect to have multiple
83 // declarators, thus use declaration starting location as the "declaration
84 // location".
85 // For all other declarations multiple declarators are used quite frequently,
86 // so we use the location of the identifier as the "declaration location".
87 SourceLocation DeclLoc;
88 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
89 isa<ObjCPropertyDecl>(D))
90 DeclLoc = D->getLocStart();
91 else
92 DeclLoc = D->getLocation();
93
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000094 // If the declaration doesn't map directly to a location in a file, we
95 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000096 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
97 return NULL;
98
99 // Find the comment that occurs just after this declaration.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000100 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
101 ArrayRef<RawComment *>::iterator Comment
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000102 = std::lower_bound(RawComments.begin(),
103 RawComments.end(),
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000104 &CommentAtDeclLoc,
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000105 BeforeThanCompare<RawComment>(SourceMgr));
106
107 // Decompose the location for the declaration and find the beginning of the
108 // file buffer.
109 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
110
111 // First check whether we have a trailing comment.
112 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000113 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000114 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000115 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000116 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000117 // Check that Doxygen trailing comment comes after the declaration, starts
118 // on the same line and in the same file as the declaration.
119 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
120 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
121 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
122 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000123 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000124 }
125 }
126
127 // The comment just after the declaration was not a trailing comment.
128 // Let's look at the previous comment.
129 if (Comment == RawComments.begin())
130 return NULL;
131 --Comment;
132
133 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000134 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000135 return NULL;
136
137 // Decompose the end of the comment.
138 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000139 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000140
141 // If the comment and the declaration aren't in the same file, then they
142 // aren't related.
143 if (DeclLocDecomp.first != CommentEndDecomp.first)
144 return NULL;
145
146 // Get the corresponding buffer.
147 bool Invalid = false;
148 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
149 &Invalid).data();
150 if (Invalid)
151 return NULL;
152
153 // Extract text between the comment and declaration.
154 StringRef Text(Buffer + CommentEndDecomp.second,
155 DeclLocDecomp.second - CommentEndDecomp.second);
156
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000157 // There should be no other declarations or preprocessor directives between
158 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000159 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000160 return NULL;
161
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000162 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000163}
164
165const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const {
166 // Check whether we have cached a comment string for this declaration
167 // already.
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000168 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000169 = DeclComments.find(D);
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000170 if (Pos != DeclComments.end()) {
171 RawAndParsedComment C = Pos->second;
172 return C.first;
173 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000174
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000175 RawComment *RC = getRawCommentForDeclNoCache(D);
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000176 // If we found a comment, it should be a documentation comment.
177 assert(!RC || RC->isDocumentation());
Dmitri Gribenko08630052012-07-06 15:40:08 +0000178 DeclComments[D] =
179 RawAndParsedComment(RC, static_cast<comments::FullComment *>(NULL));
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000180 if (RC)
181 RC->setAttached();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000182 return RC;
183}
184
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000185comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const {
186 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
187 = DeclComments.find(D);
188 const RawComment *RC;
189 if (Pos != DeclComments.end()) {
190 RawAndParsedComment C = Pos->second;
191 if (comments::FullComment *FC = C.second)
192 return FC;
193 RC = C.first;
194 } else
195 RC = getRawCommentForDecl(D);
196
197 if (!RC)
198 return NULL;
199
200 const StringRef RawText = RC->getRawText(SourceMgr);
201 comments::Lexer L(RC->getSourceRange().getBegin(), comments::CommentOptions(),
202 RawText.begin(), RawText.end());
203
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000204 comments::Sema S(getAllocator(), getSourceManager(), getDiagnostics());
205 S.setDecl(D);
206 comments::Parser P(L, S, getAllocator(), getSourceManager(),
207 getDiagnostics());
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000208
209 comments::FullComment *FC = P.parseFullComment();
210 DeclComments[D].second = FC;
211 return FC;
212}
213
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000214void
215ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
216 TemplateTemplateParmDecl *Parm) {
217 ID.AddInteger(Parm->getDepth());
218 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000219 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000220
221 TemplateParameterList *Params = Parm->getTemplateParameters();
222 ID.AddInteger(Params->size());
223 for (TemplateParameterList::const_iterator P = Params->begin(),
224 PEnd = Params->end();
225 P != PEnd; ++P) {
226 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
227 ID.AddInteger(0);
228 ID.AddBoolean(TTP->isParameterPack());
229 continue;
230 }
231
232 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
233 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000234 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000235 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000236 if (NTTP->isExpandedParameterPack()) {
237 ID.AddBoolean(true);
238 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000239 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
240 QualType T = NTTP->getExpansionType(I);
241 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
242 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000243 } else
244 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000245 continue;
246 }
247
248 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
249 ID.AddInteger(2);
250 Profile(ID, TTP);
251 }
252}
253
254TemplateTemplateParmDecl *
255ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000256 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000257 // Check if we already have a canonical template template parameter.
258 llvm::FoldingSetNodeID ID;
259 CanonicalTemplateTemplateParm::Profile(ID, TTP);
260 void *InsertPos = 0;
261 CanonicalTemplateTemplateParm *Canonical
262 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
263 if (Canonical)
264 return Canonical->getParam();
265
266 // Build a canonical template parameter list.
267 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000268 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000269 CanonParams.reserve(Params->size());
270 for (TemplateParameterList::const_iterator P = Params->begin(),
271 PEnd = Params->end();
272 P != PEnd; ++P) {
273 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
274 CanonParams.push_back(
275 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000276 SourceLocation(),
277 SourceLocation(),
278 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000279 TTP->getIndex(), 0, false,
280 TTP->isParameterPack()));
281 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000282 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
283 QualType T = getCanonicalType(NTTP->getType());
284 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
285 NonTypeTemplateParmDecl *Param;
286 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000287 SmallVector<QualType, 2> ExpandedTypes;
288 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000289 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
290 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
291 ExpandedTInfos.push_back(
292 getTrivialTypeSourceInfo(ExpandedTypes.back()));
293 }
294
295 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000296 SourceLocation(),
297 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000298 NTTP->getDepth(),
299 NTTP->getPosition(), 0,
300 T,
301 TInfo,
302 ExpandedTypes.data(),
303 ExpandedTypes.size(),
304 ExpandedTInfos.data());
305 } else {
306 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000307 SourceLocation(),
308 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000309 NTTP->getDepth(),
310 NTTP->getPosition(), 0,
311 T,
312 NTTP->isParameterPack(),
313 TInfo);
314 }
315 CanonParams.push_back(Param);
316
317 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000318 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
319 cast<TemplateTemplateParmDecl>(*P)));
320 }
321
322 TemplateTemplateParmDecl *CanonTTP
323 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
324 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000325 TTP->getPosition(),
326 TTP->isParameterPack(),
327 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000328 TemplateParameterList::Create(*this, SourceLocation(),
329 SourceLocation(),
330 CanonParams.data(),
331 CanonParams.size(),
332 SourceLocation()));
333
334 // Get the new insert position for the node we care about.
335 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
336 assert(Canonical == 0 && "Shouldn't be in the map!");
337 (void)Canonical;
338
339 // Create the canonical template template parameter entry.
340 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
341 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
342 return CanonTTP;
343}
344
Charles Davis53c59df2010-08-16 03:33:14 +0000345CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000346 if (!LangOpts.CPlusPlus) return 0;
347
Charles Davis6bcb07a2010-08-19 02:18:14 +0000348 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000349 case CXXABI_ARM:
350 return CreateARMCXXABI(*this);
351 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000352 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000353 case CXXABI_Microsoft:
354 return CreateMicrosoftCXXABI(*this);
355 }
David Blaikie8a40f702012-01-17 06:56:22 +0000356 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000357}
358
Douglas Gregore8bbc122011-09-02 00:18:52 +0000359static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000360 const LangOptions &LOpts) {
361 if (LOpts.FakeAddressSpaceMap) {
362 // The fake address space map must have a distinct entry for each
363 // language-specific address space.
364 static const unsigned FakeAddrSpaceMap[] = {
365 1, // opencl_global
366 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000367 3, // opencl_constant
368 4, // cuda_device
369 5, // cuda_constant
370 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000371 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000372 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000373 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000374 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000375 }
376}
377
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000378ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000379 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000380 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000381 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000382 unsigned size_reserve,
383 bool DelayInitialization)
384 : FunctionProtoTypes(this_()),
385 TemplateSpecializationTypes(this_()),
386 DependentTemplateSpecializationTypes(this_()),
387 SubstTemplateTemplateParmPacks(this_()),
388 GlobalNestedNameSpecifier(0),
389 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000390 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000391 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000392 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000393 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000394 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
395 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
396 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000397 NullTypeSourceInfo(QualType()),
398 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000399 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000400 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000401 Idents(idents), Selectors(sels),
402 BuiltinInfo(builtins),
403 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000404 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000405 Comments(SM), CommentsLoaded(false),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000406 LastSDM(0, 0),
407 UniqueBlockByRefTypeID(0)
408{
Mike Stump11289f42009-09-09 15:08:12 +0000409 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000410 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000411
412 if (!DelayInitialization) {
413 assert(t && "No target supplied for ASTContext initialization");
414 InitBuiltinTypes(*t);
415 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000416}
417
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000418ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000419 // Release the DenseMaps associated with DeclContext objects.
420 // FIXME: Is this the ideal solution?
421 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000422
Douglas Gregor5b11d492010-07-25 17:53:33 +0000423 // Call all of the deallocation functions.
424 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
425 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000426
Ted Kremenek076baeb2010-06-08 23:00:58 +0000427 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000428 // because they can contain DenseMaps.
429 for (llvm::DenseMap<const ObjCContainerDecl*,
430 const ASTRecordLayout*>::iterator
431 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
432 // Increment in loop to prevent using deallocated memory.
433 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
434 R->Destroy(*this);
435
Ted Kremenek076baeb2010-06-08 23:00:58 +0000436 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
437 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
438 // Increment in loop to prevent using deallocated memory.
439 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
440 R->Destroy(*this);
441 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000442
443 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
444 AEnd = DeclAttrs.end();
445 A != AEnd; ++A)
446 A->second->~AttrVec();
447}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000448
Douglas Gregor1a809332010-05-23 18:26:36 +0000449void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
450 Deallocations.push_back(std::make_pair(Callback, Data));
451}
452
Mike Stump11289f42009-09-09 15:08:12 +0000453void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000454ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000455 ExternalSource.reset(Source.take());
456}
457
Chris Lattner4eb445d2007-01-26 01:27:23 +0000458void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000459 llvm::errs() << "\n*** AST Context Stats:\n";
460 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000461
Douglas Gregora30d0462009-05-26 14:40:08 +0000462 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000463#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000464#define ABSTRACT_TYPE(Name, Parent)
465#include "clang/AST/TypeNodes.def"
466 0 // Extra
467 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000468
Chris Lattner4eb445d2007-01-26 01:27:23 +0000469 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
470 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000471 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000472 }
473
Douglas Gregora30d0462009-05-26 14:40:08 +0000474 unsigned Idx = 0;
475 unsigned TotalBytes = 0;
476#define TYPE(Name, Parent) \
477 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000478 llvm::errs() << " " << counts[Idx] << " " << #Name \
479 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000480 TotalBytes += counts[Idx] * sizeof(Name##Type); \
481 ++Idx;
482#define ABSTRACT_TYPE(Name, Parent)
483#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000484
Chandler Carruth3c147a72011-07-04 05:32:14 +0000485 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
486
Douglas Gregor7454c562010-07-02 20:37:36 +0000487 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000488 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
489 << NumImplicitDefaultConstructors
490 << " implicit default constructors created\n";
491 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
492 << NumImplicitCopyConstructors
493 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000494 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000495 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
496 << NumImplicitMoveConstructors
497 << " implicit move constructors created\n";
498 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
499 << NumImplicitCopyAssignmentOperators
500 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000501 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000502 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
503 << NumImplicitMoveAssignmentOperators
504 << " implicit move assignment operators created\n";
505 llvm::errs() << NumImplicitDestructorsDeclared << "/"
506 << NumImplicitDestructors
507 << " implicit destructors created\n";
508
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000509 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000510 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000511 ExternalSource->PrintStats();
512 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000513
Douglas Gregor5b11d492010-07-25 17:53:33 +0000514 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000515}
516
Douglas Gregor801c99d2011-08-12 06:49:56 +0000517TypedefDecl *ASTContext::getInt128Decl() const {
518 if (!Int128Decl) {
519 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
520 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
521 getTranslationUnitDecl(),
522 SourceLocation(),
523 SourceLocation(),
524 &Idents.get("__int128_t"),
525 TInfo);
526 }
527
528 return Int128Decl;
529}
530
531TypedefDecl *ASTContext::getUInt128Decl() const {
532 if (!UInt128Decl) {
533 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
534 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
535 getTranslationUnitDecl(),
536 SourceLocation(),
537 SourceLocation(),
538 &Idents.get("__uint128_t"),
539 TInfo);
540 }
541
542 return UInt128Decl;
543}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000544
John McCall48f2d582009-10-23 23:03:21 +0000545void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000546 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000547 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000548 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000549}
550
Douglas Gregore8bbc122011-09-02 00:18:52 +0000551void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
552 assert((!this->Target || this->Target == &Target) &&
553 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000554 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000555
Douglas Gregore8bbc122011-09-02 00:18:52 +0000556 this->Target = &Target;
557
558 ABI.reset(createCXXABI(Target));
559 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
560
Chris Lattner970e54e2006-11-12 00:37:36 +0000561 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000562 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000563
Chris Lattner970e54e2006-11-12 00:37:36 +0000564 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000565 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000566 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000567 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000568 InitBuiltinType(CharTy, BuiltinType::Char_S);
569 else
570 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000571 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000572 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
573 InitBuiltinType(ShortTy, BuiltinType::Short);
574 InitBuiltinType(IntTy, BuiltinType::Int);
575 InitBuiltinType(LongTy, BuiltinType::Long);
576 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000577
Chris Lattner970e54e2006-11-12 00:37:36 +0000578 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000579 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
580 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
581 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
582 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
583 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000584
Chris Lattner970e54e2006-11-12 00:37:36 +0000585 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000586 InitBuiltinType(FloatTy, BuiltinType::Float);
587 InitBuiltinType(DoubleTy, BuiltinType::Double);
588 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000589
Chris Lattnerf122cef2009-04-30 02:43:43 +0000590 // GNU extension, 128-bit integers.
591 InitBuiltinType(Int128Ty, BuiltinType::Int128);
592 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
593
Chris Lattnerad3467e2010-12-25 23:25:43 +0000594 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000595 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000596 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
597 else // -fshort-wchar makes wchar_t be unsigned.
598 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
599 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000600 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000601
James Molloy36365542012-05-04 10:55:22 +0000602 WIntTy = getFromTargetType(Target.getWIntType());
603
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000604 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
605 InitBuiltinType(Char16Ty, BuiltinType::Char16);
606 else // C99
607 Char16Ty = getFromTargetType(Target.getChar16Type());
608
609 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
610 InitBuiltinType(Char32Ty, BuiltinType::Char32);
611 else // C99
612 Char32Ty = getFromTargetType(Target.getChar32Type());
613
Douglas Gregor4619e432008-12-05 23:32:09 +0000614 // Placeholder type for type-dependent expressions whose type is
615 // completely unknown. No code should ever check a type against
616 // DependentTy and users should never see it; however, it is here to
617 // help diagnose failures to properly check for type-dependent
618 // expressions.
619 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000620
John McCall36e7fe32010-10-12 00:20:44 +0000621 // Placeholder type for functions.
622 InitBuiltinType(OverloadTy, BuiltinType::Overload);
623
John McCall0009fcc2011-04-26 20:42:42 +0000624 // Placeholder type for bound members.
625 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
626
John McCall526ab472011-10-25 17:37:35 +0000627 // Placeholder type for pseudo-objects.
628 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
629
John McCall31996342011-04-07 08:22:57 +0000630 // "any" type; useful for debugger-like clients.
631 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
632
John McCall8a6b59a2011-10-17 18:09:15 +0000633 // Placeholder type for unbridged ARC casts.
634 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
635
Chris Lattner970e54e2006-11-12 00:37:36 +0000636 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000637 FloatComplexTy = getComplexType(FloatTy);
638 DoubleComplexTy = getComplexType(DoubleTy);
639 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000640
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000641 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000642 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
643 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000644 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000645
646 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000647 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
648 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000649
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000650 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000651
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000652 // void * type
653 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000654
655 // nullptr type (C++0x 2.14.7)
656 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000657
658 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
659 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000660
661 // Builtin type used to help define __builtin_va_list.
662 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000663}
664
David Blaikie9c902b52011-09-25 23:23:43 +0000665DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000666 return SourceMgr.getDiagnostics();
667}
668
Douglas Gregor561eceb2010-08-30 16:49:28 +0000669AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
670 AttrVec *&Result = DeclAttrs[D];
671 if (!Result) {
672 void *Mem = Allocate(sizeof(AttrVec));
673 Result = new (Mem) AttrVec;
674 }
675
676 return *Result;
677}
678
679/// \brief Erase the attributes corresponding to the given declaration.
680void ASTContext::eraseDeclAttrs(const Decl *D) {
681 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
682 if (Pos != DeclAttrs.end()) {
683 Pos->second->~AttrVec();
684 DeclAttrs.erase(Pos);
685 }
686}
687
Douglas Gregor86d142a2009-10-08 07:24:58 +0000688MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000689ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000690 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000691 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000692 = InstantiatedFromStaticDataMember.find(Var);
693 if (Pos == InstantiatedFromStaticDataMember.end())
694 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000695
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000696 return Pos->second;
697}
698
Mike Stump11289f42009-09-09 15:08:12 +0000699void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000700ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000701 TemplateSpecializationKind TSK,
702 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000703 assert(Inst->isStaticDataMember() && "Not a static data member");
704 assert(Tmpl->isStaticDataMember() && "Not a static data member");
705 assert(!InstantiatedFromStaticDataMember[Inst] &&
706 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000707 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000708 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000709}
710
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000711FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
712 const FunctionDecl *FD){
713 assert(FD && "Specialization is 0");
714 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000715 = ClassScopeSpecializationPattern.find(FD);
716 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000717 return 0;
718
719 return Pos->second;
720}
721
722void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
723 FunctionDecl *Pattern) {
724 assert(FD && "Specialization is 0");
725 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000726 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000727}
728
John McCalle61f2ba2009-11-18 02:36:19 +0000729NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000730ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000731 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000732 = InstantiatedFromUsingDecl.find(UUD);
733 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000734 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000735
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000736 return Pos->second;
737}
738
739void
John McCallb96ec562009-12-04 22:46:56 +0000740ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
741 assert((isa<UsingDecl>(Pattern) ||
742 isa<UnresolvedUsingValueDecl>(Pattern) ||
743 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
744 "pattern decl is not a using decl");
745 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
746 InstantiatedFromUsingDecl[Inst] = Pattern;
747}
748
749UsingShadowDecl *
750ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
751 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
752 = InstantiatedFromUsingShadowDecl.find(Inst);
753 if (Pos == InstantiatedFromUsingShadowDecl.end())
754 return 0;
755
756 return Pos->second;
757}
758
759void
760ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
761 UsingShadowDecl *Pattern) {
762 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
763 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000764}
765
Anders Carlsson5da84842009-09-01 04:26:58 +0000766FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
767 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
768 = InstantiatedFromUnnamedFieldDecl.find(Field);
769 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
770 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000771
Anders Carlsson5da84842009-09-01 04:26:58 +0000772 return Pos->second;
773}
774
775void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
776 FieldDecl *Tmpl) {
777 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
778 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
779 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
780 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000781
Anders Carlsson5da84842009-09-01 04:26:58 +0000782 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
783}
784
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000785bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
786 const FieldDecl *LastFD) const {
787 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000788 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000789}
790
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000791bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
792 const FieldDecl *LastFD) const {
793 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000794 FD->getBitWidthValue(*this) == 0 &&
795 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000796}
797
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000798bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
799 const FieldDecl *LastFD) const {
800 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000801 FD->getBitWidthValue(*this) &&
802 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000803}
804
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000805bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000806 const FieldDecl *LastFD) const {
807 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000808 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000809}
810
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000811bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000812 const FieldDecl *LastFD) const {
813 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000814 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000815}
816
Douglas Gregor832940b2010-03-02 23:58:15 +0000817ASTContext::overridden_cxx_method_iterator
818ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
819 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
820 = OverriddenMethods.find(Method);
821 if (Pos == OverriddenMethods.end())
822 return 0;
823
824 return Pos->second.begin();
825}
826
827ASTContext::overridden_cxx_method_iterator
828ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
829 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
830 = OverriddenMethods.find(Method);
831 if (Pos == OverriddenMethods.end())
832 return 0;
833
834 return Pos->second.end();
835}
836
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000837unsigned
838ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
839 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
840 = OverriddenMethods.find(Method);
841 if (Pos == OverriddenMethods.end())
842 return 0;
843
844 return Pos->second.size();
845}
846
Douglas Gregor832940b2010-03-02 23:58:15 +0000847void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
848 const CXXMethodDecl *Overridden) {
849 OverriddenMethods[Method].push_back(Overridden);
850}
851
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000852void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
853 assert(!Import->NextLocalImport && "Import declaration already in the chain");
854 assert(!Import->isFromASTFile() && "Non-local import declaration");
855 if (!FirstLocalImport) {
856 FirstLocalImport = Import;
857 LastLocalImport = Import;
858 return;
859 }
860
861 LastLocalImport->NextLocalImport = Import;
862 LastLocalImport = Import;
863}
864
Chris Lattner53cfe802007-07-18 17:52:12 +0000865//===----------------------------------------------------------------------===//
866// Type Sizing and Analysis
867//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000868
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000869/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
870/// scalar floating point type.
871const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000872 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000873 assert(BT && "Not a floating point type!");
874 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000875 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000876 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000877 case BuiltinType::Float: return Target->getFloatFormat();
878 case BuiltinType::Double: return Target->getDoubleFormat();
879 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000880 }
881}
882
Ken Dyck160146e2010-01-27 17:10:57 +0000883/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000884/// specified decl. Note that bitfields do not have a valid alignment, so
885/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000886/// If @p RefAsPointee, references are treated like their underlying type
887/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000888CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000889 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000890
John McCall94268702010-10-08 18:24:19 +0000891 bool UseAlignAttrOnly = false;
892 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
893 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000894
John McCall94268702010-10-08 18:24:19 +0000895 // __attribute__((aligned)) can increase or decrease alignment
896 // *except* on a struct or struct member, where it only increases
897 // alignment unless 'packed' is also specified.
898 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000899 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000900 // ignore that possibility; Sema should diagnose it.
901 if (isa<FieldDecl>(D)) {
902 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
903 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
904 } else {
905 UseAlignAttrOnly = true;
906 }
907 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000908 else if (isa<FieldDecl>(D))
909 UseAlignAttrOnly =
910 D->hasAttr<PackedAttr>() ||
911 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000912
John McCall4e819612011-01-20 07:57:12 +0000913 // If we're using the align attribute only, just ignore everything
914 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000915 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000916 // do nothing
917
John McCall94268702010-10-08 18:24:19 +0000918 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000919 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000920 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000921 if (RefAsPointee)
922 T = RT->getPointeeType();
923 else
924 T = getPointerType(RT->getPointeeType());
925 }
926 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000927 // Adjust alignments of declarations with array type by the
928 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000929 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000930 const ArrayType *arrayType;
931 if (MinWidth && (arrayType = getAsArrayType(T))) {
932 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000933 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000934 else if (isa<ConstantArrayType>(arrayType) &&
935 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000936 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000937
John McCall33ddac02011-01-19 10:06:00 +0000938 // Walk through any array types while we're at it.
939 T = getBaseElementType(arrayType);
940 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000941 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000942 }
John McCall4e819612011-01-20 07:57:12 +0000943
944 // Fields can be subject to extra alignment constraints, like if
945 // the field is packed, the struct is packed, or the struct has a
946 // a max-field-alignment constraint (#pragma pack). So calculate
947 // the actual alignment of the field within the struct, and then
948 // (as we're expected to) constrain that by the alignment of the type.
949 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
950 // So calculate the alignment of the field.
951 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
952
953 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000954 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000955
956 // Use the GCD of that and the offset within the record.
957 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
958 if (offset > 0) {
959 // Alignment is always a power of 2, so the GCD will be a power of 2,
960 // which means we get to do this crazy thing instead of Euclid's.
961 uint64_t lowBitOfOffset = offset & (~offset + 1);
962 if (lowBitOfOffset < fieldAlign)
963 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
964 }
965
966 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000967 }
Chris Lattner68061312009-01-24 21:53:27 +0000968 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000969
Ken Dyckcc56c542011-01-15 18:38:59 +0000970 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000971}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000972
John McCall87fe5d52010-05-20 01:18:31 +0000973std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000974ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000975 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000976 return std::make_pair(toCharUnitsFromBits(Info.first),
977 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000978}
979
980std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000981ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000982 return getTypeInfoInChars(T.getTypePtr());
983}
984
Daniel Dunbarc6475872012-03-09 04:12:54 +0000985std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
986 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
987 if (it != MemoizedTypeInfo.end())
988 return it->second;
989
990 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
991 MemoizedTypeInfo.insert(std::make_pair(T, Info));
992 return Info;
993}
994
995/// getTypeInfoImpl - Return the size of the specified type, in bits. This
996/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000997///
998/// FIXME: Pointers into different addr spaces could have different sizes and
999/// alignment requirements: getPointerInfo should take an AddrSpace, this
1000/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001001std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001002ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001003 uint64_t Width=0;
1004 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001005 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001006#define TYPE(Class, Base)
1007#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001008#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001009#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1010#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001011 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001012
Chris Lattner355332d2007-07-13 22:27:08 +00001013 case Type::FunctionNoProto:
1014 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001015 // GCC extension: alignof(function) = 32 bits
1016 Width = 0;
1017 Align = 32;
1018 break;
1019
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001020 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001021 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001022 Width = 0;
1023 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1024 break;
1025
Steve Naroff5c131802007-08-30 01:06:46 +00001026 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001027 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001028
Chris Lattner37e05872008-03-05 18:54:05 +00001029 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001030 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001031 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1032 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001033 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001034 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001035 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001036 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001037 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001038 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001039 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001040 const VectorType *VT = cast<VectorType>(T);
1041 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1042 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001043 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001044 // If the alignment is not a power of 2, round up to the next power of 2.
1045 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001046 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001047 Align = llvm::NextPowerOf2(Align);
1048 Width = llvm::RoundUpToAlignment(Width, Align);
1049 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001050 // Adjust the alignment based on the target max.
1051 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1052 if (TargetVectorAlign && TargetVectorAlign < Align)
1053 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001054 break;
1055 }
Chris Lattner647fb222007-07-18 18:26:58 +00001056
Chris Lattner7570e9c2008-03-08 08:52:55 +00001057 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001058 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001059 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001060 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001061 // GCC extension: alignof(void) = 8 bits.
1062 Width = 0;
1063 Align = 8;
1064 break;
1065
Chris Lattner6a4f7452007-12-19 19:23:28 +00001066 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001067 Width = Target->getBoolWidth();
1068 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001069 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001070 case BuiltinType::Char_S:
1071 case BuiltinType::Char_U:
1072 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001073 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001074 Width = Target->getCharWidth();
1075 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001076 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001077 case BuiltinType::WChar_S:
1078 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001079 Width = Target->getWCharWidth();
1080 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001081 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001082 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001083 Width = Target->getChar16Width();
1084 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001085 break;
1086 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001087 Width = Target->getChar32Width();
1088 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001089 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001090 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001091 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001092 Width = Target->getShortWidth();
1093 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001094 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001095 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001096 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001097 Width = Target->getIntWidth();
1098 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001099 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001100 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001101 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001102 Width = Target->getLongWidth();
1103 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001104 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001105 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001106 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001107 Width = Target->getLongLongWidth();
1108 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001109 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001110 case BuiltinType::Int128:
1111 case BuiltinType::UInt128:
1112 Width = 128;
1113 Align = 128; // int128_t is 128-bit aligned on all targets.
1114 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001115 case BuiltinType::Half:
1116 Width = Target->getHalfWidth();
1117 Align = Target->getHalfAlign();
1118 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001119 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001120 Width = Target->getFloatWidth();
1121 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001122 break;
1123 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001124 Width = Target->getDoubleWidth();
1125 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001126 break;
1127 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001128 Width = Target->getLongDoubleWidth();
1129 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001130 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001131 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001132 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1133 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001134 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001135 case BuiltinType::ObjCId:
1136 case BuiltinType::ObjCClass:
1137 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001138 Width = Target->getPointerWidth(0);
1139 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001140 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001141 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001142 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001143 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001144 Width = Target->getPointerWidth(0);
1145 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001146 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001147 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001148 unsigned AS = getTargetAddressSpace(
1149 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001150 Width = Target->getPointerWidth(AS);
1151 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001152 break;
1153 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001154 case Type::LValueReference:
1155 case Type::RValueReference: {
1156 // alignof and sizeof should never enter this code path here, so we go
1157 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001158 unsigned AS = getTargetAddressSpace(
1159 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001160 Width = Target->getPointerWidth(AS);
1161 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001162 break;
1163 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001164 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001165 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001166 Width = Target->getPointerWidth(AS);
1167 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001168 break;
1169 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001170 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001171 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001172 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001173 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001174 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001175 Align = PtrDiffInfo.second;
1176 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001177 }
Chris Lattner647fb222007-07-18 18:26:58 +00001178 case Type::Complex: {
1179 // Complex types have the same alignment as their elements, but twice the
1180 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001181 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001182 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001183 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001184 Align = EltInfo.second;
1185 break;
1186 }
John McCall8b07ec22010-05-15 11:32:37 +00001187 case Type::ObjCObject:
1188 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001189 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001190 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001191 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001192 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001193 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001194 break;
1195 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001196 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001197 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001198 const TagType *TT = cast<TagType>(T);
1199
1200 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001201 Width = 8;
1202 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001203 break;
1204 }
Mike Stump11289f42009-09-09 15:08:12 +00001205
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001206 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001207 return getTypeInfo(ET->getDecl()->getIntegerType());
1208
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001209 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001210 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001211 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001212 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001213 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001214 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001215
Chris Lattner63d2b362009-10-22 05:17:15 +00001216 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001217 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1218 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001219
Richard Smith30482bc2011-02-20 03:19:35 +00001220 case Type::Auto: {
1221 const AutoType *A = cast<AutoType>(T);
1222 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001223 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001224 }
1225
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001226 case Type::Paren:
1227 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1228
Douglas Gregoref462e62009-04-30 17:32:17 +00001229 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001230 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001231 std::pair<uint64_t, unsigned> Info
1232 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001233 // If the typedef has an aligned attribute on it, it overrides any computed
1234 // alignment we have. This violates the GCC documentation (which says that
1235 // attribute(aligned) can only round up) but matches its implementation.
1236 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1237 Align = AttrAlign;
1238 else
1239 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001240 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001241 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001242 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001243
1244 case Type::TypeOfExpr:
1245 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1246 .getTypePtr());
1247
1248 case Type::TypeOf:
1249 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1250
Anders Carlsson81df7b82009-06-24 19:06:50 +00001251 case Type::Decltype:
1252 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1253 .getTypePtr());
1254
Alexis Hunte852b102011-05-24 22:41:36 +00001255 case Type::UnaryTransform:
1256 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1257
Abramo Bagnara6150c882010-05-11 21:36:43 +00001258 case Type::Elaborated:
1259 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001260
John McCall81904512011-01-06 01:58:22 +00001261 case Type::Attributed:
1262 return getTypeInfo(
1263 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1264
Richard Smith3f1b5d02011-05-05 21:57:07 +00001265 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001266 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001267 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001268 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1269 // A type alias template specialization may refer to a typedef with the
1270 // aligned attribute on it.
1271 if (TST->isTypeAlias())
1272 return getTypeInfo(TST->getAliasedType().getTypePtr());
1273 else
1274 return getTypeInfo(getCanonicalType(T));
1275 }
1276
Eli Friedman0dfb8892011-10-06 23:00:33 +00001277 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001278 std::pair<uint64_t, unsigned> Info
1279 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1280 Width = Info.first;
1281 Align = Info.second;
1282 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1283 llvm::isPowerOf2_64(Width)) {
1284 // We can potentially perform lock-free atomic operations for this
1285 // type; promote the alignment appropriately.
1286 // FIXME: We could potentially promote the width here as well...
1287 // is that worthwhile? (Non-struct atomic types generally have
1288 // power-of-two size anyway, but structs might not. Requires a bit
1289 // of implementation work to make sure we zero out the extra bits.)
1290 Align = static_cast<unsigned>(Width);
1291 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001292 }
1293
Douglas Gregoref462e62009-04-30 17:32:17 +00001294 }
Mike Stump11289f42009-09-09 15:08:12 +00001295
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001296 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001297 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001298}
1299
Ken Dyckcc56c542011-01-15 18:38:59 +00001300/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1301CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1302 return CharUnits::fromQuantity(BitSize / getCharWidth());
1303}
1304
Ken Dyckb0fcc592011-02-11 01:54:29 +00001305/// toBits - Convert a size in characters to a size in characters.
1306int64_t ASTContext::toBits(CharUnits CharSize) const {
1307 return CharSize.getQuantity() * getCharWidth();
1308}
1309
Ken Dyck8c89d592009-12-22 14:23:30 +00001310/// getTypeSizeInChars - Return the size of the specified type, in characters.
1311/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001312CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001313 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001314}
Jay Foad39c79802011-01-12 09:06:06 +00001315CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001316 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001317}
1318
Ken Dycka6046ab2010-01-26 17:25:18 +00001319/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001320/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001321CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001322 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001323}
Jay Foad39c79802011-01-12 09:06:06 +00001324CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001325 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001326}
1327
Chris Lattnera3402cd2009-01-27 18:08:34 +00001328/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1329/// type for the current target in bits. This can be different than the ABI
1330/// alignment in cases where it is beneficial for performance to overalign
1331/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001332unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001333 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001334
1335 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001336 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001337 T = CT->getElementType().getTypePtr();
1338 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001339 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1340 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001341 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1342
Chris Lattnera3402cd2009-01-27 18:08:34 +00001343 return ABIAlign;
1344}
1345
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001346/// DeepCollectObjCIvars -
1347/// This routine first collects all declared, but not synthesized, ivars in
1348/// super class and then collects all ivars, including those synthesized for
1349/// current class. This routine is used for implementation of current class
1350/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001351///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001352void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1353 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001354 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001355 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1356 DeepCollectObjCIvars(SuperClass, false, Ivars);
1357 if (!leafClass) {
1358 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1359 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001360 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001361 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001362 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001363 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001364 Iv= Iv->getNextIvar())
1365 Ivars.push_back(Iv);
1366 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001367}
1368
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001369/// CollectInheritedProtocols - Collect all protocols in current class and
1370/// those inherited by it.
1371void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001372 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001373 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001374 // We can use protocol_iterator here instead of
1375 // all_referenced_protocol_iterator since we are walking all categories.
1376 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1377 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001378 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001379 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001380 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001381 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001382 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001383 CollectInheritedProtocols(*P, Protocols);
1384 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001385 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001386
1387 // Categories of this Interface.
1388 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1389 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1390 CollectInheritedProtocols(CDeclChain, Protocols);
1391 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1392 while (SD) {
1393 CollectInheritedProtocols(SD, Protocols);
1394 SD = SD->getSuperClass();
1395 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001396 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001397 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001398 PE = OC->protocol_end(); P != PE; ++P) {
1399 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001400 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001401 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1402 PE = Proto->protocol_end(); P != PE; ++P)
1403 CollectInheritedProtocols(*P, Protocols);
1404 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001405 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001406 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1407 PE = OP->protocol_end(); P != PE; ++P) {
1408 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001409 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001410 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1411 PE = Proto->protocol_end(); P != PE; ++P)
1412 CollectInheritedProtocols(*P, Protocols);
1413 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001414 }
1415}
1416
Jay Foad39c79802011-01-12 09:06:06 +00001417unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001418 unsigned count = 0;
1419 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001420 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1421 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001422 count += CDecl->ivar_size();
1423
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001424 // Count ivar defined in this class's implementation. This
1425 // includes synthesized ivars.
1426 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001427 count += ImplDecl->ivar_size();
1428
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001429 return count;
1430}
1431
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001432bool ASTContext::isSentinelNullExpr(const Expr *E) {
1433 if (!E)
1434 return false;
1435
1436 // nullptr_t is always treated as null.
1437 if (E->getType()->isNullPtrType()) return true;
1438
1439 if (E->getType()->isAnyPointerType() &&
1440 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1441 Expr::NPC_ValueDependentIsNull))
1442 return true;
1443
1444 // Unfortunately, __null has type 'int'.
1445 if (isa<GNUNullExpr>(E)) return true;
1446
1447 return false;
1448}
1449
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001450/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1451ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1452 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1453 I = ObjCImpls.find(D);
1454 if (I != ObjCImpls.end())
1455 return cast<ObjCImplementationDecl>(I->second);
1456 return 0;
1457}
1458/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1459ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1460 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1461 I = ObjCImpls.find(D);
1462 if (I != ObjCImpls.end())
1463 return cast<ObjCCategoryImplDecl>(I->second);
1464 return 0;
1465}
1466
1467/// \brief Set the implementation of ObjCInterfaceDecl.
1468void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1469 ObjCImplementationDecl *ImplD) {
1470 assert(IFaceD && ImplD && "Passed null params");
1471 ObjCImpls[IFaceD] = ImplD;
1472}
1473/// \brief Set the implementation of ObjCCategoryDecl.
1474void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1475 ObjCCategoryImplDecl *ImplD) {
1476 assert(CatD && ImplD && "Passed null params");
1477 ObjCImpls[CatD] = ImplD;
1478}
1479
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001480ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1481 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1482 return ID;
1483 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1484 return CD->getClassInterface();
1485 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1486 return IMD->getClassInterface();
1487
1488 return 0;
1489}
1490
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001491/// \brief Get the copy initialization expression of VarDecl,or NULL if
1492/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001493Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001494 assert(VD && "Passed null params");
1495 assert(VD->hasAttr<BlocksAttr>() &&
1496 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001497 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001498 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001499 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1500}
1501
1502/// \brief Set the copy inialization expression of a block var decl.
1503void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1504 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001505 assert(VD->hasAttr<BlocksAttr>() &&
1506 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001507 BlockVarCopyInits[VD] = Init;
1508}
1509
John McCallbcd03502009-12-07 02:54:59 +00001510TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001511 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001512 if (!DataSize)
1513 DataSize = TypeLoc::getFullDataSizeForType(T);
1514 else
1515 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001516 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001517
John McCallbcd03502009-12-07 02:54:59 +00001518 TypeSourceInfo *TInfo =
1519 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1520 new (TInfo) TypeSourceInfo(T);
1521 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001522}
1523
John McCallbcd03502009-12-07 02:54:59 +00001524TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001525 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001526 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001527 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001528 return DI;
1529}
1530
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001531const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001532ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001533 return getObjCLayout(D, 0);
1534}
1535
1536const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001537ASTContext::getASTObjCImplementationLayout(
1538 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001539 return getObjCLayout(D->getClassInterface(), D);
1540}
1541
Chris Lattner983a8bb2007-07-13 22:13:22 +00001542//===----------------------------------------------------------------------===//
1543// Type creation/memoization methods
1544//===----------------------------------------------------------------------===//
1545
Jay Foad39c79802011-01-12 09:06:06 +00001546QualType
John McCall33ddac02011-01-19 10:06:00 +00001547ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1548 unsigned fastQuals = quals.getFastQualifiers();
1549 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001550
1551 // Check if we've already instantiated this type.
1552 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001553 ExtQuals::Profile(ID, baseType, quals);
1554 void *insertPos = 0;
1555 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1556 assert(eq->getQualifiers() == quals);
1557 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001558 }
1559
John McCall33ddac02011-01-19 10:06:00 +00001560 // If the base type is not canonical, make the appropriate canonical type.
1561 QualType canon;
1562 if (!baseType->isCanonicalUnqualified()) {
1563 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001564 canonSplit.Quals.addConsistentQualifiers(quals);
1565 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001566
1567 // Re-find the insert position.
1568 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1569 }
1570
1571 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1572 ExtQualNodes.InsertNode(eq, insertPos);
1573 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001574}
1575
Jay Foad39c79802011-01-12 09:06:06 +00001576QualType
1577ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001578 QualType CanT = getCanonicalType(T);
1579 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001580 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001581
John McCall8ccfcb52009-09-24 19:53:00 +00001582 // If we are composing extended qualifiers together, merge together
1583 // into one ExtQuals node.
1584 QualifierCollector Quals;
1585 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001586
John McCall8ccfcb52009-09-24 19:53:00 +00001587 // If this type already has an address space specified, it cannot get
1588 // another one.
1589 assert(!Quals.hasAddressSpace() &&
1590 "Type cannot be in multiple addr spaces!");
1591 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001592
John McCall8ccfcb52009-09-24 19:53:00 +00001593 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001594}
1595
Chris Lattnerd60183d2009-02-18 22:53:11 +00001596QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001597 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001598 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001599 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001600 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001601
John McCall53fa7142010-12-24 02:08:15 +00001602 if (const PointerType *ptr = T->getAs<PointerType>()) {
1603 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001604 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001605 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1606 return getPointerType(ResultType);
1607 }
1608 }
Mike Stump11289f42009-09-09 15:08:12 +00001609
John McCall8ccfcb52009-09-24 19:53:00 +00001610 // If we are composing extended qualifiers together, merge together
1611 // into one ExtQuals node.
1612 QualifierCollector Quals;
1613 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001614
John McCall8ccfcb52009-09-24 19:53:00 +00001615 // If this type already has an ObjCGC specified, it cannot get
1616 // another one.
1617 assert(!Quals.hasObjCGCAttr() &&
1618 "Type cannot have multiple ObjCGCs!");
1619 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001620
John McCall8ccfcb52009-09-24 19:53:00 +00001621 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001622}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001623
John McCall4f5019e2010-12-19 02:44:49 +00001624const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1625 FunctionType::ExtInfo Info) {
1626 if (T->getExtInfo() == Info)
1627 return T;
1628
1629 QualType Result;
1630 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1631 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1632 } else {
1633 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1634 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1635 EPI.ExtInfo = Info;
1636 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1637 FPT->getNumArgs(), EPI);
1638 }
1639
1640 return cast<FunctionType>(Result.getTypePtr());
1641}
1642
Chris Lattnerc6395932007-06-22 20:56:16 +00001643/// getComplexType - Return the uniqued reference to the type for a complex
1644/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001645QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001646 // Unique pointers, to guarantee there is only one pointer of a particular
1647 // structure.
1648 llvm::FoldingSetNodeID ID;
1649 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001650
Chris Lattnerc6395932007-06-22 20:56:16 +00001651 void *InsertPos = 0;
1652 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1653 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001654
Chris Lattnerc6395932007-06-22 20:56:16 +00001655 // If the pointee type isn't canonical, this won't be a canonical type either,
1656 // so fill in the canonical type field.
1657 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001658 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001659 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001660
Chris Lattnerc6395932007-06-22 20:56:16 +00001661 // Get the new insert position for the node we care about.
1662 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001663 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001664 }
John McCall90d1c2d2009-09-24 23:30:46 +00001665 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001666 Types.push_back(New);
1667 ComplexTypes.InsertNode(New, InsertPos);
1668 return QualType(New, 0);
1669}
1670
Chris Lattner970e54e2006-11-12 00:37:36 +00001671/// getPointerType - Return the uniqued reference to the type for a pointer to
1672/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001673QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001674 // Unique pointers, to guarantee there is only one pointer of a particular
1675 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001676 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001677 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001678
Chris Lattner67521df2007-01-27 01:29:36 +00001679 void *InsertPos = 0;
1680 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001681 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001682
Chris Lattner7ccecb92006-11-12 08:50:50 +00001683 // If the pointee type isn't canonical, this won't be a canonical type either,
1684 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001685 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001686 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001687 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001688
Chris Lattner67521df2007-01-27 01:29:36 +00001689 // Get the new insert position for the node we care about.
1690 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001691 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001692 }
John McCall90d1c2d2009-09-24 23:30:46 +00001693 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001694 Types.push_back(New);
1695 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001696 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001697}
1698
Mike Stump11289f42009-09-09 15:08:12 +00001699/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001700/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001701QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001702 assert(T->isFunctionType() && "block of function types only");
1703 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001704 // structure.
1705 llvm::FoldingSetNodeID ID;
1706 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001707
Steve Naroffec33ed92008-08-27 16:04:49 +00001708 void *InsertPos = 0;
1709 if (BlockPointerType *PT =
1710 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1711 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001712
1713 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001714 // type either so fill in the canonical type field.
1715 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001716 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001717 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001718
Steve Naroffec33ed92008-08-27 16:04:49 +00001719 // Get the new insert position for the node we care about.
1720 BlockPointerType *NewIP =
1721 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001722 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001723 }
John McCall90d1c2d2009-09-24 23:30:46 +00001724 BlockPointerType *New
1725 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001726 Types.push_back(New);
1727 BlockPointerTypes.InsertNode(New, InsertPos);
1728 return QualType(New, 0);
1729}
1730
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001731/// getLValueReferenceType - Return the uniqued reference to the type for an
1732/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001733QualType
1734ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001735 assert(getCanonicalType(T) != OverloadTy &&
1736 "Unresolved overloaded function type");
1737
Bill Wendling3708c182007-05-27 10:15:43 +00001738 // Unique pointers, to guarantee there is only one pointer of a particular
1739 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001740 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001741 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001742
1743 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001744 if (LValueReferenceType *RT =
1745 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001746 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001747
John McCallfc93cf92009-10-22 22:37:11 +00001748 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1749
Bill Wendling3708c182007-05-27 10:15:43 +00001750 // If the referencee type isn't canonical, this won't be a canonical type
1751 // either, so fill in the canonical type field.
1752 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001753 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1754 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1755 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001756
Bill Wendling3708c182007-05-27 10:15:43 +00001757 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001758 LValueReferenceType *NewIP =
1759 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001760 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001761 }
1762
John McCall90d1c2d2009-09-24 23:30:46 +00001763 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001764 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1765 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001766 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001767 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001768
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001769 return QualType(New, 0);
1770}
1771
1772/// getRValueReferenceType - Return the uniqued reference to the type for an
1773/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001774QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001775 // Unique pointers, to guarantee there is only one pointer of a particular
1776 // structure.
1777 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001778 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001779
1780 void *InsertPos = 0;
1781 if (RValueReferenceType *RT =
1782 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1783 return QualType(RT, 0);
1784
John McCallfc93cf92009-10-22 22:37:11 +00001785 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1786
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001787 // If the referencee type isn't canonical, this won't be a canonical type
1788 // either, so fill in the canonical type field.
1789 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001790 if (InnerRef || !T.isCanonical()) {
1791 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1792 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001793
1794 // Get the new insert position for the node we care about.
1795 RValueReferenceType *NewIP =
1796 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001797 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001798 }
1799
John McCall90d1c2d2009-09-24 23:30:46 +00001800 RValueReferenceType *New
1801 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001802 Types.push_back(New);
1803 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001804 return QualType(New, 0);
1805}
1806
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001807/// getMemberPointerType - Return the uniqued reference to the type for a
1808/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001809QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001810 // Unique pointers, to guarantee there is only one pointer of a particular
1811 // structure.
1812 llvm::FoldingSetNodeID ID;
1813 MemberPointerType::Profile(ID, T, Cls);
1814
1815 void *InsertPos = 0;
1816 if (MemberPointerType *PT =
1817 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1818 return QualType(PT, 0);
1819
1820 // If the pointee or class type isn't canonical, this won't be a canonical
1821 // type either, so fill in the canonical type field.
1822 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001823 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001824 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1825
1826 // Get the new insert position for the node we care about.
1827 MemberPointerType *NewIP =
1828 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001829 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001830 }
John McCall90d1c2d2009-09-24 23:30:46 +00001831 MemberPointerType *New
1832 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001833 Types.push_back(New);
1834 MemberPointerTypes.InsertNode(New, InsertPos);
1835 return QualType(New, 0);
1836}
1837
Mike Stump11289f42009-09-09 15:08:12 +00001838/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001839/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001840QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001841 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001842 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001843 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001844 assert((EltTy->isDependentType() ||
1845 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001846 "Constant array of VLAs is illegal!");
1847
Chris Lattnere2df3f92009-05-13 04:12:56 +00001848 // Convert the array size into a canonical width matching the pointer size for
1849 // the target.
1850 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001851 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001852 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001853
Chris Lattner23b7eb62007-06-15 23:05:46 +00001854 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001855 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001856
Chris Lattner36f8e652007-01-27 08:31:04 +00001857 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001858 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001859 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001860 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001861
John McCall33ddac02011-01-19 10:06:00 +00001862 // If the element type isn't canonical or has qualifiers, this won't
1863 // be a canonical type either, so fill in the canonical type field.
1864 QualType Canon;
1865 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1866 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001867 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001868 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001869 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001870
Chris Lattner36f8e652007-01-27 08:31:04 +00001871 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001872 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001873 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001874 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001875 }
Mike Stump11289f42009-09-09 15:08:12 +00001876
John McCall90d1c2d2009-09-24 23:30:46 +00001877 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001878 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001879 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001880 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001881 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001882}
1883
John McCall06549462011-01-18 08:40:38 +00001884/// getVariableArrayDecayedType - Turns the given type, which may be
1885/// variably-modified, into the corresponding type with all the known
1886/// sizes replaced with [*].
1887QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1888 // Vastly most common case.
1889 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001890
John McCall06549462011-01-18 08:40:38 +00001891 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001892
John McCall06549462011-01-18 08:40:38 +00001893 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001894 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001895 switch (ty->getTypeClass()) {
1896#define TYPE(Class, Base)
1897#define ABSTRACT_TYPE(Class, Base)
1898#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1899#include "clang/AST/TypeNodes.def"
1900 llvm_unreachable("didn't desugar past all non-canonical types?");
1901
1902 // These types should never be variably-modified.
1903 case Type::Builtin:
1904 case Type::Complex:
1905 case Type::Vector:
1906 case Type::ExtVector:
1907 case Type::DependentSizedExtVector:
1908 case Type::ObjCObject:
1909 case Type::ObjCInterface:
1910 case Type::ObjCObjectPointer:
1911 case Type::Record:
1912 case Type::Enum:
1913 case Type::UnresolvedUsing:
1914 case Type::TypeOfExpr:
1915 case Type::TypeOf:
1916 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001917 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001918 case Type::DependentName:
1919 case Type::InjectedClassName:
1920 case Type::TemplateSpecialization:
1921 case Type::DependentTemplateSpecialization:
1922 case Type::TemplateTypeParm:
1923 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001924 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001925 case Type::PackExpansion:
1926 llvm_unreachable("type should never be variably-modified");
1927
1928 // These types can be variably-modified but should never need to
1929 // further decay.
1930 case Type::FunctionNoProto:
1931 case Type::FunctionProto:
1932 case Type::BlockPointer:
1933 case Type::MemberPointer:
1934 return type;
1935
1936 // These types can be variably-modified. All these modifications
1937 // preserve structure except as noted by comments.
1938 // TODO: if we ever care about optimizing VLAs, there are no-op
1939 // optimizations available here.
1940 case Type::Pointer:
1941 result = getPointerType(getVariableArrayDecayedType(
1942 cast<PointerType>(ty)->getPointeeType()));
1943 break;
1944
1945 case Type::LValueReference: {
1946 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1947 result = getLValueReferenceType(
1948 getVariableArrayDecayedType(lv->getPointeeType()),
1949 lv->isSpelledAsLValue());
1950 break;
1951 }
1952
1953 case Type::RValueReference: {
1954 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1955 result = getRValueReferenceType(
1956 getVariableArrayDecayedType(lv->getPointeeType()));
1957 break;
1958 }
1959
Eli Friedman0dfb8892011-10-06 23:00:33 +00001960 case Type::Atomic: {
1961 const AtomicType *at = cast<AtomicType>(ty);
1962 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1963 break;
1964 }
1965
John McCall06549462011-01-18 08:40:38 +00001966 case Type::ConstantArray: {
1967 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1968 result = getConstantArrayType(
1969 getVariableArrayDecayedType(cat->getElementType()),
1970 cat->getSize(),
1971 cat->getSizeModifier(),
1972 cat->getIndexTypeCVRQualifiers());
1973 break;
1974 }
1975
1976 case Type::DependentSizedArray: {
1977 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1978 result = getDependentSizedArrayType(
1979 getVariableArrayDecayedType(dat->getElementType()),
1980 dat->getSizeExpr(),
1981 dat->getSizeModifier(),
1982 dat->getIndexTypeCVRQualifiers(),
1983 dat->getBracketsRange());
1984 break;
1985 }
1986
1987 // Turn incomplete types into [*] types.
1988 case Type::IncompleteArray: {
1989 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1990 result = getVariableArrayType(
1991 getVariableArrayDecayedType(iat->getElementType()),
1992 /*size*/ 0,
1993 ArrayType::Normal,
1994 iat->getIndexTypeCVRQualifiers(),
1995 SourceRange());
1996 break;
1997 }
1998
1999 // Turn VLA types into [*] types.
2000 case Type::VariableArray: {
2001 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2002 result = getVariableArrayType(
2003 getVariableArrayDecayedType(vat->getElementType()),
2004 /*size*/ 0,
2005 ArrayType::Star,
2006 vat->getIndexTypeCVRQualifiers(),
2007 vat->getBracketsRange());
2008 break;
2009 }
2010 }
2011
2012 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002013 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002014}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002015
Steve Naroffcadebd02007-08-30 18:14:25 +00002016/// getVariableArrayType - Returns a non-unique reference to the type for a
2017/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002018QualType ASTContext::getVariableArrayType(QualType EltTy,
2019 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002020 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002021 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002022 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002023 // Since we don't unique expressions, it isn't possible to unique VLA's
2024 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002025 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002026
John McCall33ddac02011-01-19 10:06:00 +00002027 // Be sure to pull qualifiers off the element type.
2028 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2029 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002030 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002031 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002032 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002033 }
2034
John McCall90d1c2d2009-09-24 23:30:46 +00002035 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002036 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002037
2038 VariableArrayTypes.push_back(New);
2039 Types.push_back(New);
2040 return QualType(New, 0);
2041}
2042
Douglas Gregor4619e432008-12-05 23:32:09 +00002043/// getDependentSizedArrayType - Returns a non-unique reference to
2044/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002045/// type.
John McCall33ddac02011-01-19 10:06:00 +00002046QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2047 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002048 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002049 unsigned elementTypeQuals,
2050 SourceRange brackets) const {
2051 assert((!numElements || numElements->isTypeDependent() ||
2052 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002053 "Size must be type- or value-dependent!");
2054
John McCall33ddac02011-01-19 10:06:00 +00002055 // Dependently-sized array types that do not have a specified number
2056 // of elements will have their sizes deduced from a dependent
2057 // initializer. We do no canonicalization here at all, which is okay
2058 // because they can't be used in most locations.
2059 if (!numElements) {
2060 DependentSizedArrayType *newType
2061 = new (*this, TypeAlignment)
2062 DependentSizedArrayType(*this, elementType, QualType(),
2063 numElements, ASM, elementTypeQuals,
2064 brackets);
2065 Types.push_back(newType);
2066 return QualType(newType, 0);
2067 }
2068
2069 // Otherwise, we actually build a new type every time, but we
2070 // also build a canonical type.
2071
2072 SplitQualType canonElementType = getCanonicalType(elementType).split();
2073
2074 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002075 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002076 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002077 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002078 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002079
John McCall33ddac02011-01-19 10:06:00 +00002080 // Look for an existing type with these properties.
2081 DependentSizedArrayType *canonTy =
2082 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002083
John McCall33ddac02011-01-19 10:06:00 +00002084 // If we don't have one, build one.
2085 if (!canonTy) {
2086 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002087 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002088 QualType(), numElements, ASM, elementTypeQuals,
2089 brackets);
2090 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2091 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002092 }
2093
John McCall33ddac02011-01-19 10:06:00 +00002094 // Apply qualifiers from the element type to the array.
2095 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002096 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002097
John McCall33ddac02011-01-19 10:06:00 +00002098 // If we didn't need extra canonicalization for the element type,
2099 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002100 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002101 return canon;
2102
2103 // Otherwise, we need to build a type which follows the spelling
2104 // of the element type.
2105 DependentSizedArrayType *sugaredType
2106 = new (*this, TypeAlignment)
2107 DependentSizedArrayType(*this, elementType, canon, numElements,
2108 ASM, elementTypeQuals, brackets);
2109 Types.push_back(sugaredType);
2110 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002111}
2112
John McCall33ddac02011-01-19 10:06:00 +00002113QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002114 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002115 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002116 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002117 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002118
John McCall33ddac02011-01-19 10:06:00 +00002119 void *insertPos = 0;
2120 if (IncompleteArrayType *iat =
2121 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2122 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002123
2124 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002125 // either, so fill in the canonical type field. We also have to pull
2126 // qualifiers off the element type.
2127 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002128
John McCall33ddac02011-01-19 10:06:00 +00002129 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2130 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002131 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002132 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002133 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002134
2135 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002136 IncompleteArrayType *existing =
2137 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2138 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002139 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002140
John McCall33ddac02011-01-19 10:06:00 +00002141 IncompleteArrayType *newType = new (*this, TypeAlignment)
2142 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002143
John McCall33ddac02011-01-19 10:06:00 +00002144 IncompleteArrayTypes.InsertNode(newType, insertPos);
2145 Types.push_back(newType);
2146 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002147}
2148
Steve Naroff91fcddb2007-07-18 18:00:27 +00002149/// getVectorType - Return the unique reference to a vector type of
2150/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002151QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002152 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002153 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002154
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002155 // Check if we've already instantiated a vector of this type.
2156 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002157 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002158
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002159 void *InsertPos = 0;
2160 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2161 return QualType(VTP, 0);
2162
2163 // If the element type isn't canonical, this won't be a canonical type either,
2164 // so fill in the canonical type field.
2165 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002166 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002167 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002168
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002169 // Get the new insert position for the node we care about.
2170 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002171 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002172 }
John McCall90d1c2d2009-09-24 23:30:46 +00002173 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002174 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002175 VectorTypes.InsertNode(New, InsertPos);
2176 Types.push_back(New);
2177 return QualType(New, 0);
2178}
2179
Nate Begemance4d7fc2008-04-18 23:10:10 +00002180/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002181/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002182QualType
2183ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002184 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002185
Steve Naroff91fcddb2007-07-18 18:00:27 +00002186 // Check if we've already instantiated a vector of this type.
2187 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002188 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002189 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002190 void *InsertPos = 0;
2191 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2192 return QualType(VTP, 0);
2193
2194 // If the element type isn't canonical, this won't be a canonical type either,
2195 // so fill in the canonical type field.
2196 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002197 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002198 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002199
Steve Naroff91fcddb2007-07-18 18:00:27 +00002200 // Get the new insert position for the node we care about.
2201 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002202 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002203 }
John McCall90d1c2d2009-09-24 23:30:46 +00002204 ExtVectorType *New = new (*this, TypeAlignment)
2205 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002206 VectorTypes.InsertNode(New, InsertPos);
2207 Types.push_back(New);
2208 return QualType(New, 0);
2209}
2210
Jay Foad39c79802011-01-12 09:06:06 +00002211QualType
2212ASTContext::getDependentSizedExtVectorType(QualType vecType,
2213 Expr *SizeExpr,
2214 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002215 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002216 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002217 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002218
Douglas Gregor352169a2009-07-31 03:54:25 +00002219 void *InsertPos = 0;
2220 DependentSizedExtVectorType *Canon
2221 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2222 DependentSizedExtVectorType *New;
2223 if (Canon) {
2224 // We already have a canonical version of this array type; use it as
2225 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002226 New = new (*this, TypeAlignment)
2227 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2228 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002229 } else {
2230 QualType CanonVecTy = getCanonicalType(vecType);
2231 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002232 New = new (*this, TypeAlignment)
2233 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2234 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002235
2236 DependentSizedExtVectorType *CanonCheck
2237 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2238 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2239 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002240 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2241 } else {
2242 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2243 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002244 New = new (*this, TypeAlignment)
2245 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002246 }
2247 }
Mike Stump11289f42009-09-09 15:08:12 +00002248
Douglas Gregor758a8692009-06-17 21:51:59 +00002249 Types.push_back(New);
2250 return QualType(New, 0);
2251}
2252
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002253/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002254///
Jay Foad39c79802011-01-12 09:06:06 +00002255QualType
2256ASTContext::getFunctionNoProtoType(QualType ResultTy,
2257 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002258 const CallingConv DefaultCC = Info.getCC();
2259 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2260 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002261 // Unique functions, to guarantee there is only one function of a particular
2262 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002263 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002264 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002265
Chris Lattner47955de2007-01-27 08:37:20 +00002266 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002267 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002268 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002269 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002270
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002271 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002272 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002273 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002274 Canonical =
2275 getFunctionNoProtoType(getCanonicalType(ResultTy),
2276 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002277
Chris Lattner47955de2007-01-27 08:37:20 +00002278 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002279 FunctionNoProtoType *NewIP =
2280 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002281 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002282 }
Mike Stump11289f42009-09-09 15:08:12 +00002283
Roman Divacky65b88cd2011-03-01 17:40:53 +00002284 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002285 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002286 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002287 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002288 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002289 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002290}
2291
2292/// getFunctionType - Return a normal function type with a typed argument
2293/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002294QualType
2295ASTContext::getFunctionType(QualType ResultTy,
2296 const QualType *ArgArray, unsigned NumArgs,
2297 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002298 // Unique functions, to guarantee there is only one function of a particular
2299 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002300 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002301 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002302
2303 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002304 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002305 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002306 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002307
2308 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002309 bool isCanonical =
2310 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2311 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002312 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002313 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002314 isCanonical = false;
2315
Roman Divacky65b88cd2011-03-01 17:40:53 +00002316 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2317 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2318 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002319
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002320 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002321 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002322 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002323 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002324 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002325 CanonicalArgs.reserve(NumArgs);
2326 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002327 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002328
John McCalldb40c7f2010-12-14 08:05:40 +00002329 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002330 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002331 CanonicalEPI.ExceptionSpecType = EST_None;
2332 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002333 CanonicalEPI.ExtInfo
2334 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2335
Chris Lattner76a00cf2008-04-06 22:59:24 +00002336 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002337 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002338 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002339
Chris Lattnerfd4de792007-01-27 01:15:32 +00002340 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002341 FunctionProtoType *NewIP =
2342 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002343 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002344 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002345
John McCall31168b02011-06-15 23:02:42 +00002346 // FunctionProtoType objects are allocated with extra bytes after
2347 // them for three variable size arrays at the end:
2348 // - parameter types
2349 // - exception types
2350 // - consumed-arguments flags
2351 // Instead of the exception types, there could be a noexcept
2352 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002353 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002354 NumArgs * sizeof(QualType);
2355 if (EPI.ExceptionSpecType == EST_Dynamic)
2356 Size += EPI.NumExceptions * sizeof(QualType);
2357 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002358 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002359 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002360 Size += 2 * sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002361 }
John McCall31168b02011-06-15 23:02:42 +00002362 if (EPI.ConsumedArguments)
2363 Size += NumArgs * sizeof(bool);
2364
John McCalldb40c7f2010-12-14 08:05:40 +00002365 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002366 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2367 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002368 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002369 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002370 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002371 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002372}
Chris Lattneref51c202006-11-10 07:17:23 +00002373
John McCalle78aac42010-03-10 03:28:59 +00002374#ifndef NDEBUG
2375static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2376 if (!isa<CXXRecordDecl>(D)) return false;
2377 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2378 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2379 return true;
2380 if (RD->getDescribedClassTemplate() &&
2381 !isa<ClassTemplateSpecializationDecl>(RD))
2382 return true;
2383 return false;
2384}
2385#endif
2386
2387/// getInjectedClassNameType - Return the unique reference to the
2388/// injected class name type for the specified templated declaration.
2389QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002390 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002391 assert(NeedsInjectedClassNameType(Decl));
2392 if (Decl->TypeForDecl) {
2393 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002394 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002395 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2396 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2397 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2398 } else {
John McCall424cec92011-01-19 06:33:43 +00002399 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002400 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002401 Decl->TypeForDecl = newType;
2402 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002403 }
2404 return QualType(Decl->TypeForDecl, 0);
2405}
2406
Douglas Gregor83a586e2008-04-13 21:07:44 +00002407/// getTypeDeclType - Return the unique reference to the type for the
2408/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002409QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002410 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002411 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002412
Richard Smithdda56e42011-04-15 14:24:37 +00002413 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002414 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002415
John McCall96f0b5f2010-03-10 06:48:02 +00002416 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2417 "Template type parameter types are always available.");
2418
John McCall81e38502010-02-16 03:57:14 +00002419 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002420 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002421 "struct/union has previous declaration");
2422 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002423 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002424 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002425 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002426 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002427 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002428 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002429 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002430 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2431 Decl->TypeForDecl = newType;
2432 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002433 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002434 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002435
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002436 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002437}
2438
Chris Lattner32d920b2007-01-26 02:01:53 +00002439/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002440/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002441QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002442ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2443 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002444 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002445
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002446 if (Canonical.isNull())
2447 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002448 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002449 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002450 Decl->TypeForDecl = newType;
2451 Types.push_back(newType);
2452 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002453}
2454
Jay Foad39c79802011-01-12 09:06:06 +00002455QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002456 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2457
Douglas Gregorec9fd132012-01-14 16:38:05 +00002458 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002459 if (PrevDecl->TypeForDecl)
2460 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2461
John McCall424cec92011-01-19 06:33:43 +00002462 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2463 Decl->TypeForDecl = newType;
2464 Types.push_back(newType);
2465 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002466}
2467
Jay Foad39c79802011-01-12 09:06:06 +00002468QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002469 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2470
Douglas Gregorec9fd132012-01-14 16:38:05 +00002471 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002472 if (PrevDecl->TypeForDecl)
2473 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2474
John McCall424cec92011-01-19 06:33:43 +00002475 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2476 Decl->TypeForDecl = newType;
2477 Types.push_back(newType);
2478 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002479}
2480
John McCall81904512011-01-06 01:58:22 +00002481QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2482 QualType modifiedType,
2483 QualType equivalentType) {
2484 llvm::FoldingSetNodeID id;
2485 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2486
2487 void *insertPos = 0;
2488 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2489 if (type) return QualType(type, 0);
2490
2491 QualType canon = getCanonicalType(equivalentType);
2492 type = new (*this, TypeAlignment)
2493 AttributedType(canon, attrKind, modifiedType, equivalentType);
2494
2495 Types.push_back(type);
2496 AttributedTypes.InsertNode(type, insertPos);
2497
2498 return QualType(type, 0);
2499}
2500
2501
John McCallcebee162009-10-18 09:09:24 +00002502/// \brief Retrieve a substitution-result type.
2503QualType
2504ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002505 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002506 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002507 && "replacement types must always be canonical");
2508
2509 llvm::FoldingSetNodeID ID;
2510 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2511 void *InsertPos = 0;
2512 SubstTemplateTypeParmType *SubstParm
2513 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2514
2515 if (!SubstParm) {
2516 SubstParm = new (*this, TypeAlignment)
2517 SubstTemplateTypeParmType(Parm, Replacement);
2518 Types.push_back(SubstParm);
2519 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2520 }
2521
2522 return QualType(SubstParm, 0);
2523}
2524
Douglas Gregorada4b792011-01-14 02:55:32 +00002525/// \brief Retrieve a
2526QualType ASTContext::getSubstTemplateTypeParmPackType(
2527 const TemplateTypeParmType *Parm,
2528 const TemplateArgument &ArgPack) {
2529#ifndef NDEBUG
2530 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2531 PEnd = ArgPack.pack_end();
2532 P != PEnd; ++P) {
2533 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2534 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2535 }
2536#endif
2537
2538 llvm::FoldingSetNodeID ID;
2539 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2540 void *InsertPos = 0;
2541 if (SubstTemplateTypeParmPackType *SubstParm
2542 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2543 return QualType(SubstParm, 0);
2544
2545 QualType Canon;
2546 if (!Parm->isCanonicalUnqualified()) {
2547 Canon = getCanonicalType(QualType(Parm, 0));
2548 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2549 ArgPack);
2550 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2551 }
2552
2553 SubstTemplateTypeParmPackType *SubstParm
2554 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2555 ArgPack);
2556 Types.push_back(SubstParm);
2557 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2558 return QualType(SubstParm, 0);
2559}
2560
Douglas Gregoreff93e02009-02-05 23:33:38 +00002561/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002562/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002563/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002564QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002565 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002566 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002567 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002568 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002569 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002570 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002571 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2572
2573 if (TypeParm)
2574 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002575
Chandler Carruth08836322011-05-01 00:51:33 +00002576 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002577 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002578 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002579
2580 TemplateTypeParmType *TypeCheck
2581 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2582 assert(!TypeCheck && "Template type parameter canonical type broken");
2583 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002584 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002585 TypeParm = new (*this, TypeAlignment)
2586 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002587
2588 Types.push_back(TypeParm);
2589 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2590
2591 return QualType(TypeParm, 0);
2592}
2593
John McCalle78aac42010-03-10 03:28:59 +00002594TypeSourceInfo *
2595ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2596 SourceLocation NameLoc,
2597 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002598 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002599 assert(!Name.getAsDependentTemplateName() &&
2600 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002601 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002602
2603 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2604 TemplateSpecializationTypeLoc TL
2605 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002606 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002607 TL.setTemplateNameLoc(NameLoc);
2608 TL.setLAngleLoc(Args.getLAngleLoc());
2609 TL.setRAngleLoc(Args.getRAngleLoc());
2610 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2611 TL.setArgLocInfo(i, Args[i].getLocInfo());
2612 return DI;
2613}
2614
Mike Stump11289f42009-09-09 15:08:12 +00002615QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002616ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002617 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002618 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002619 assert(!Template.getAsDependentTemplateName() &&
2620 "No dependent template names here!");
2621
John McCall6b51f282009-11-23 01:53:49 +00002622 unsigned NumArgs = Args.size();
2623
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002624 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002625 ArgVec.reserve(NumArgs);
2626 for (unsigned i = 0; i != NumArgs; ++i)
2627 ArgVec.push_back(Args[i].getArgument());
2628
John McCall2408e322010-04-27 00:57:59 +00002629 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002630 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002631}
2632
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002633#ifndef NDEBUG
2634static bool hasAnyPackExpansions(const TemplateArgument *Args,
2635 unsigned NumArgs) {
2636 for (unsigned I = 0; I != NumArgs; ++I)
2637 if (Args[I].isPackExpansion())
2638 return true;
2639
2640 return true;
2641}
2642#endif
2643
John McCall0ad16662009-10-29 08:12:44 +00002644QualType
2645ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002646 const TemplateArgument *Args,
2647 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002648 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002649 assert(!Template.getAsDependentTemplateName() &&
2650 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002651 // Look through qualified template names.
2652 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2653 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002654
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002655 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002656 Template.getAsTemplateDecl() &&
2657 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002658 QualType CanonType;
2659 if (!Underlying.isNull())
2660 CanonType = getCanonicalType(Underlying);
2661 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002662 // We can get here with an alias template when the specialization contains
2663 // a pack expansion that does not match up with a parameter pack.
2664 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2665 "Caller must compute aliased type");
2666 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002667 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2668 NumArgs);
2669 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002670
Douglas Gregora8e02e72009-07-28 23:00:59 +00002671 // Allocate the (non-canonical) template specialization type, but don't
2672 // try to unique it: these types typically have location information that
2673 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002674 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2675 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002676 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002677 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002678 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002679 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2680 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002681
Douglas Gregor8bf42052009-02-09 18:46:07 +00002682 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002683 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002684}
2685
Mike Stump11289f42009-09-09 15:08:12 +00002686QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002687ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2688 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002689 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002690 assert(!Template.getAsDependentTemplateName() &&
2691 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002692
Douglas Gregore29139c2011-03-03 17:04:51 +00002693 // Look through qualified template names.
2694 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2695 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002696
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002697 // Build the canonical template specialization type.
2698 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002699 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002700 CanonArgs.reserve(NumArgs);
2701 for (unsigned I = 0; I != NumArgs; ++I)
2702 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2703
2704 // Determine whether this canonical template specialization type already
2705 // exists.
2706 llvm::FoldingSetNodeID ID;
2707 TemplateSpecializationType::Profile(ID, CanonTemplate,
2708 CanonArgs.data(), NumArgs, *this);
2709
2710 void *InsertPos = 0;
2711 TemplateSpecializationType *Spec
2712 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2713
2714 if (!Spec) {
2715 // Allocate a new canonical template specialization type.
2716 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2717 sizeof(TemplateArgument) * NumArgs),
2718 TypeAlignment);
2719 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2720 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002721 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002722 Types.push_back(Spec);
2723 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2724 }
2725
2726 assert(Spec->isDependentType() &&
2727 "Non-dependent template-id type must have a canonical type");
2728 return QualType(Spec, 0);
2729}
2730
2731QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002732ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2733 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002734 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002735 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002736 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002737
2738 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002739 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002740 if (T)
2741 return QualType(T, 0);
2742
Douglas Gregorc42075a2010-02-04 18:10:26 +00002743 QualType Canon = NamedType;
2744 if (!Canon.isCanonical()) {
2745 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002746 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2747 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002748 (void)CheckT;
2749 }
2750
Abramo Bagnara6150c882010-05-11 21:36:43 +00002751 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002752 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002753 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002754 return QualType(T, 0);
2755}
2756
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002757QualType
Jay Foad39c79802011-01-12 09:06:06 +00002758ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002759 llvm::FoldingSetNodeID ID;
2760 ParenType::Profile(ID, InnerType);
2761
2762 void *InsertPos = 0;
2763 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2764 if (T)
2765 return QualType(T, 0);
2766
2767 QualType Canon = InnerType;
2768 if (!Canon.isCanonical()) {
2769 Canon = getCanonicalType(InnerType);
2770 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2771 assert(!CheckT && "Paren canonical type broken");
2772 (void)CheckT;
2773 }
2774
2775 T = new (*this) ParenType(InnerType, Canon);
2776 Types.push_back(T);
2777 ParenTypes.InsertNode(T, InsertPos);
2778 return QualType(T, 0);
2779}
2780
Douglas Gregor02085352010-03-31 20:19:30 +00002781QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2782 NestedNameSpecifier *NNS,
2783 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002784 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002785 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2786
2787 if (Canon.isNull()) {
2788 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002789 ElaboratedTypeKeyword CanonKeyword = Keyword;
2790 if (Keyword == ETK_None)
2791 CanonKeyword = ETK_Typename;
2792
2793 if (CanonNNS != NNS || CanonKeyword != Keyword)
2794 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002795 }
2796
2797 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002798 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002799
2800 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002801 DependentNameType *T
2802 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002803 if (T)
2804 return QualType(T, 0);
2805
Douglas Gregor02085352010-03-31 20:19:30 +00002806 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002807 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002808 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002809 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002810}
2811
Mike Stump11289f42009-09-09 15:08:12 +00002812QualType
John McCallc392f372010-06-11 00:33:02 +00002813ASTContext::getDependentTemplateSpecializationType(
2814 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002815 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002816 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002817 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002818 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002819 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002820 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2821 ArgCopy.push_back(Args[I].getArgument());
2822 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2823 ArgCopy.size(),
2824 ArgCopy.data());
2825}
2826
2827QualType
2828ASTContext::getDependentTemplateSpecializationType(
2829 ElaboratedTypeKeyword Keyword,
2830 NestedNameSpecifier *NNS,
2831 const IdentifierInfo *Name,
2832 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002833 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002834 assert((!NNS || NNS->isDependent()) &&
2835 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002836
Douglas Gregorc42075a2010-02-04 18:10:26 +00002837 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002838 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2839 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002840
2841 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002842 DependentTemplateSpecializationType *T
2843 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002844 if (T)
2845 return QualType(T, 0);
2846
John McCallc392f372010-06-11 00:33:02 +00002847 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002848
John McCallc392f372010-06-11 00:33:02 +00002849 ElaboratedTypeKeyword CanonKeyword = Keyword;
2850 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2851
2852 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002853 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002854 for (unsigned I = 0; I != NumArgs; ++I) {
2855 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2856 if (!CanonArgs[I].structurallyEquals(Args[I]))
2857 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002858 }
2859
John McCallc392f372010-06-11 00:33:02 +00002860 QualType Canon;
2861 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2862 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2863 Name, NumArgs,
2864 CanonArgs.data());
2865
2866 // Find the insert position again.
2867 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2868 }
2869
2870 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2871 sizeof(TemplateArgument) * NumArgs),
2872 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002873 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002874 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002875 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002876 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002877 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002878}
2879
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002880QualType ASTContext::getPackExpansionType(QualType Pattern,
2881 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002882 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002883 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002884
2885 assert(Pattern->containsUnexpandedParameterPack() &&
2886 "Pack expansions must expand one or more parameter packs");
2887 void *InsertPos = 0;
2888 PackExpansionType *T
2889 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2890 if (T)
2891 return QualType(T, 0);
2892
2893 QualType Canon;
2894 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002895 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002896
2897 // Find the insert position again.
2898 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2899 }
2900
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002901 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002902 Types.push_back(T);
2903 PackExpansionTypes.InsertNode(T, InsertPos);
2904 return QualType(T, 0);
2905}
2906
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002907/// CmpProtocolNames - Comparison predicate for sorting protocols
2908/// alphabetically.
2909static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2910 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002911 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002912}
2913
John McCall8b07ec22010-05-15 11:32:37 +00002914static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002915 unsigned NumProtocols) {
2916 if (NumProtocols == 0) return true;
2917
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002918 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2919 return false;
2920
John McCallfc93cf92009-10-22 22:37:11 +00002921 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002922 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2923 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002924 return false;
2925 return true;
2926}
2927
2928static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002929 unsigned &NumProtocols) {
2930 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002931
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002932 // Sort protocols, keyed by name.
2933 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2934
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002935 // Canonicalize.
2936 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2937 Protocols[I] = Protocols[I]->getCanonicalDecl();
2938
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002939 // Remove duplicates.
2940 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2941 NumProtocols = ProtocolsEnd-Protocols;
2942}
2943
John McCall8b07ec22010-05-15 11:32:37 +00002944QualType ASTContext::getObjCObjectType(QualType BaseType,
2945 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002946 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002947 // If the base type is an interface and there aren't any protocols
2948 // to add, then the interface type will do just fine.
2949 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2950 return BaseType;
2951
2952 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002953 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002954 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002955 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002956 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2957 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002958
John McCall8b07ec22010-05-15 11:32:37 +00002959 // Build the canonical type, which has the canonical base type and
2960 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002961 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002962 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2963 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2964 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002965 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002966 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002967 unsigned UniqueCount = NumProtocols;
2968
John McCallfc93cf92009-10-22 22:37:11 +00002969 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002970 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2971 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002972 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002973 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2974 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002975 }
2976
2977 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002978 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2979 }
2980
2981 unsigned Size = sizeof(ObjCObjectTypeImpl);
2982 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2983 void *Mem = Allocate(Size, TypeAlignment);
2984 ObjCObjectTypeImpl *T =
2985 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2986
2987 Types.push_back(T);
2988 ObjCObjectTypes.InsertNode(T, InsertPos);
2989 return QualType(T, 0);
2990}
2991
2992/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2993/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002994QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002995 llvm::FoldingSetNodeID ID;
2996 ObjCObjectPointerType::Profile(ID, ObjectT);
2997
2998 void *InsertPos = 0;
2999 if (ObjCObjectPointerType *QT =
3000 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3001 return QualType(QT, 0);
3002
3003 // Find the canonical object type.
3004 QualType Canonical;
3005 if (!ObjectT.isCanonical()) {
3006 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3007
3008 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003009 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3010 }
3011
Douglas Gregorf85bee62010-02-08 22:59:26 +00003012 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003013 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3014 ObjCObjectPointerType *QType =
3015 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003016
Steve Narofffb4330f2009-06-17 22:40:22 +00003017 Types.push_back(QType);
3018 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003019 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003020}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003021
Douglas Gregor1c283312010-08-11 12:19:30 +00003022/// getObjCInterfaceType - Return the unique reference to the type for the
3023/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003024QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3025 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003026 if (Decl->TypeForDecl)
3027 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003028
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003029 if (PrevDecl) {
3030 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3031 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3032 return QualType(PrevDecl->TypeForDecl, 0);
3033 }
3034
Douglas Gregor7671e532011-12-16 16:34:57 +00003035 // Prefer the definition, if there is one.
3036 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3037 Decl = Def;
3038
Douglas Gregor1c283312010-08-11 12:19:30 +00003039 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3040 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3041 Decl->TypeForDecl = T;
3042 Types.push_back(T);
3043 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003044}
3045
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003046/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3047/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003048/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003049/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003050/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003051QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003052 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003053 if (tofExpr->isTypeDependent()) {
3054 llvm::FoldingSetNodeID ID;
3055 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003056
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003057 void *InsertPos = 0;
3058 DependentTypeOfExprType *Canon
3059 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3060 if (Canon) {
3061 // We already have a "canonical" version of an identical, dependent
3062 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003063 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003064 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003065 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003066 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003067 Canon
3068 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003069 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3070 toe = Canon;
3071 }
3072 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003073 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003074 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003075 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003076 Types.push_back(toe);
3077 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003078}
3079
Steve Naroffa773cd52007-08-01 18:02:17 +00003080/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3081/// TypeOfType AST's. The only motivation to unique these nodes would be
3082/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003083/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003084/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003085QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003086 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003087 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003088 Types.push_back(tot);
3089 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003090}
3091
Anders Carlssonad6bd352009-06-24 21:24:56 +00003092
Anders Carlsson81df7b82009-06-24 19:06:50 +00003093/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3094/// DecltypeType AST's. The only motivation to unique these nodes would be
3095/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003096/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003097/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003098QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003099 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003100
3101 // C++0x [temp.type]p2:
3102 // If an expression e involves a template parameter, decltype(e) denotes a
3103 // unique dependent type. Two such decltype-specifiers refer to the same
3104 // type only if their expressions are equivalent (14.5.6.1).
3105 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003106 llvm::FoldingSetNodeID ID;
3107 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003108
Douglas Gregora21f6c32009-07-30 23:36:40 +00003109 void *InsertPos = 0;
3110 DependentDecltypeType *Canon
3111 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3112 if (Canon) {
3113 // We already have a "canonical" version of an equivalent, dependent
3114 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003115 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003116 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003117 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003118 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003119 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003120 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3121 dt = Canon;
3122 }
3123 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003124 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3125 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003126 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003127 Types.push_back(dt);
3128 return QualType(dt, 0);
3129}
3130
Alexis Hunte852b102011-05-24 22:41:36 +00003131/// getUnaryTransformationType - We don't unique these, since the memory
3132/// savings are minimal and these are rare.
3133QualType ASTContext::getUnaryTransformType(QualType BaseType,
3134 QualType UnderlyingType,
3135 UnaryTransformType::UTTKind Kind)
3136 const {
3137 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003138 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3139 Kind,
3140 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003141 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003142 Types.push_back(Ty);
3143 return QualType(Ty, 0);
3144}
3145
Richard Smithb2bc2e62011-02-21 20:05:19 +00003146/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003147QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003148 void *InsertPos = 0;
3149 if (!DeducedType.isNull()) {
3150 // Look in the folding set for an existing type.
3151 llvm::FoldingSetNodeID ID;
3152 AutoType::Profile(ID, DeducedType);
3153 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3154 return QualType(AT, 0);
3155 }
3156
3157 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3158 Types.push_back(AT);
3159 if (InsertPos)
3160 AutoTypes.InsertNode(AT, InsertPos);
3161 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003162}
3163
Eli Friedman0dfb8892011-10-06 23:00:33 +00003164/// getAtomicType - Return the uniqued reference to the atomic type for
3165/// the given value type.
3166QualType ASTContext::getAtomicType(QualType T) const {
3167 // Unique pointers, to guarantee there is only one pointer of a particular
3168 // structure.
3169 llvm::FoldingSetNodeID ID;
3170 AtomicType::Profile(ID, T);
3171
3172 void *InsertPos = 0;
3173 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3174 return QualType(AT, 0);
3175
3176 // If the atomic value type isn't canonical, this won't be a canonical type
3177 // either, so fill in the canonical type field.
3178 QualType Canonical;
3179 if (!T.isCanonical()) {
3180 Canonical = getAtomicType(getCanonicalType(T));
3181
3182 // Get the new insert position for the node we care about.
3183 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3184 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3185 }
3186 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3187 Types.push_back(New);
3188 AtomicTypes.InsertNode(New, InsertPos);
3189 return QualType(New, 0);
3190}
3191
Richard Smith02e85f32011-04-14 22:09:26 +00003192/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3193QualType ASTContext::getAutoDeductType() const {
3194 if (AutoDeductTy.isNull())
3195 AutoDeductTy = getAutoType(QualType());
3196 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3197 return AutoDeductTy;
3198}
3199
3200/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3201QualType ASTContext::getAutoRRefDeductType() const {
3202 if (AutoRRefDeductTy.isNull())
3203 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3204 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3205 return AutoRRefDeductTy;
3206}
3207
Chris Lattnerfb072462007-01-23 05:45:31 +00003208/// getTagDeclType - Return the unique reference to the type for the
3209/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003210QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003211 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003212 // FIXME: What is the design on getTagDeclType when it requires casting
3213 // away const? mutable?
3214 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003215}
3216
Mike Stump11289f42009-09-09 15:08:12 +00003217/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3218/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3219/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003220CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003221 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003222}
Chris Lattnerfb072462007-01-23 05:45:31 +00003223
Hans Wennborg27541db2011-10-27 08:29:09 +00003224/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3225CanQualType ASTContext::getIntMaxType() const {
3226 return getFromTargetType(Target->getIntMaxType());
3227}
3228
3229/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3230CanQualType ASTContext::getUIntMaxType() const {
3231 return getFromTargetType(Target->getUIntMaxType());
3232}
3233
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003234/// getSignedWCharType - Return the type of "signed wchar_t".
3235/// Used when in C++, as a GCC extension.
3236QualType ASTContext::getSignedWCharType() const {
3237 // FIXME: derive from "Target" ?
3238 return WCharTy;
3239}
3240
3241/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3242/// Used when in C++, as a GCC extension.
3243QualType ASTContext::getUnsignedWCharType() const {
3244 // FIXME: derive from "Target" ?
3245 return UnsignedIntTy;
3246}
3247
Hans Wennborg27541db2011-10-27 08:29:09 +00003248/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003249/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3250QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003251 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003252}
3253
Chris Lattnera21ad802008-04-02 05:18:44 +00003254//===----------------------------------------------------------------------===//
3255// Type Operators
3256//===----------------------------------------------------------------------===//
3257
Jay Foad39c79802011-01-12 09:06:06 +00003258CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003259 // Push qualifiers into arrays, and then discard any remaining
3260 // qualifiers.
3261 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003262 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003263 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003264 QualType Result;
3265 if (isa<ArrayType>(Ty)) {
3266 Result = getArrayDecayedType(QualType(Ty,0));
3267 } else if (isa<FunctionType>(Ty)) {
3268 Result = getPointerType(QualType(Ty, 0));
3269 } else {
3270 Result = QualType(Ty, 0);
3271 }
3272
3273 return CanQualType::CreateUnsafe(Result);
3274}
3275
John McCall6c9dd522011-01-18 07:41:22 +00003276QualType ASTContext::getUnqualifiedArrayType(QualType type,
3277 Qualifiers &quals) {
3278 SplitQualType splitType = type.getSplitUnqualifiedType();
3279
3280 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3281 // the unqualified desugared type and then drops it on the floor.
3282 // We then have to strip that sugar back off with
3283 // getUnqualifiedDesugaredType(), which is silly.
3284 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003285 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003286
3287 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003288 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003289 quals = splitType.Quals;
3290 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003291 }
3292
John McCall6c9dd522011-01-18 07:41:22 +00003293 // Otherwise, recurse on the array's element type.
3294 QualType elementType = AT->getElementType();
3295 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3296
3297 // If that didn't change the element type, AT has no qualifiers, so we
3298 // can just use the results in splitType.
3299 if (elementType == unqualElementType) {
3300 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003301 quals = splitType.Quals;
3302 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003303 }
3304
3305 // Otherwise, add in the qualifiers from the outermost type, then
3306 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003307 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003308
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003309 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003310 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003311 CAT->getSizeModifier(), 0);
3312 }
3313
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003314 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003315 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003316 }
3317
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003318 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003319 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003320 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003321 VAT->getSizeModifier(),
3322 VAT->getIndexTypeCVRQualifiers(),
3323 VAT->getBracketsRange());
3324 }
3325
3326 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003327 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003328 DSAT->getSizeModifier(), 0,
3329 SourceRange());
3330}
3331
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003332/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3333/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3334/// they point to and return true. If T1 and T2 aren't pointer types
3335/// or pointer-to-member types, or if they are not similar at this
3336/// level, returns false and leaves T1 and T2 unchanged. Top-level
3337/// qualifiers on T1 and T2 are ignored. This function will typically
3338/// be called in a loop that successively "unwraps" pointer and
3339/// pointer-to-member types to compare them at each level.
3340bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3341 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3342 *T2PtrType = T2->getAs<PointerType>();
3343 if (T1PtrType && T2PtrType) {
3344 T1 = T1PtrType->getPointeeType();
3345 T2 = T2PtrType->getPointeeType();
3346 return true;
3347 }
3348
3349 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3350 *T2MPType = T2->getAs<MemberPointerType>();
3351 if (T1MPType && T2MPType &&
3352 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3353 QualType(T2MPType->getClass(), 0))) {
3354 T1 = T1MPType->getPointeeType();
3355 T2 = T2MPType->getPointeeType();
3356 return true;
3357 }
3358
David Blaikiebbafb8a2012-03-11 07:00:24 +00003359 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003360 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3361 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3362 if (T1OPType && T2OPType) {
3363 T1 = T1OPType->getPointeeType();
3364 T2 = T2OPType->getPointeeType();
3365 return true;
3366 }
3367 }
3368
3369 // FIXME: Block pointers, too?
3370
3371 return false;
3372}
3373
Jay Foad39c79802011-01-12 09:06:06 +00003374DeclarationNameInfo
3375ASTContext::getNameForTemplate(TemplateName Name,
3376 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003377 switch (Name.getKind()) {
3378 case TemplateName::QualifiedTemplate:
3379 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003380 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003381 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3382 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003383
John McCalld9dfe3a2011-06-30 08:33:18 +00003384 case TemplateName::OverloadedTemplate: {
3385 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3386 // DNInfo work in progress: CHECKME: what about DNLoc?
3387 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3388 }
3389
3390 case TemplateName::DependentTemplate: {
3391 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003392 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003393 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003394 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3395 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003396 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003397 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3398 // DNInfo work in progress: FIXME: source locations?
3399 DeclarationNameLoc DNLoc;
3400 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3401 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3402 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003403 }
3404 }
3405
John McCalld9dfe3a2011-06-30 08:33:18 +00003406 case TemplateName::SubstTemplateTemplateParm: {
3407 SubstTemplateTemplateParmStorage *subst
3408 = Name.getAsSubstTemplateTemplateParm();
3409 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3410 NameLoc);
3411 }
3412
3413 case TemplateName::SubstTemplateTemplateParmPack: {
3414 SubstTemplateTemplateParmPackStorage *subst
3415 = Name.getAsSubstTemplateTemplateParmPack();
3416 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3417 NameLoc);
3418 }
3419 }
3420
3421 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003422}
3423
Jay Foad39c79802011-01-12 09:06:06 +00003424TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003425 switch (Name.getKind()) {
3426 case TemplateName::QualifiedTemplate:
3427 case TemplateName::Template: {
3428 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003429 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003430 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003431 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3432
3433 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003434 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003435 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003436
John McCalld9dfe3a2011-06-30 08:33:18 +00003437 case TemplateName::OverloadedTemplate:
3438 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003439
John McCalld9dfe3a2011-06-30 08:33:18 +00003440 case TemplateName::DependentTemplate: {
3441 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3442 assert(DTN && "Non-dependent template names must refer to template decls.");
3443 return DTN->CanonicalTemplateName;
3444 }
3445
3446 case TemplateName::SubstTemplateTemplateParm: {
3447 SubstTemplateTemplateParmStorage *subst
3448 = Name.getAsSubstTemplateTemplateParm();
3449 return getCanonicalTemplateName(subst->getReplacement());
3450 }
3451
3452 case TemplateName::SubstTemplateTemplateParmPack: {
3453 SubstTemplateTemplateParmPackStorage *subst
3454 = Name.getAsSubstTemplateTemplateParmPack();
3455 TemplateTemplateParmDecl *canonParameter
3456 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3457 TemplateArgument canonArgPack
3458 = getCanonicalTemplateArgument(subst->getArgumentPack());
3459 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3460 }
3461 }
3462
3463 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003464}
3465
Douglas Gregoradee3e32009-11-11 23:06:43 +00003466bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3467 X = getCanonicalTemplateName(X);
3468 Y = getCanonicalTemplateName(Y);
3469 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3470}
3471
Mike Stump11289f42009-09-09 15:08:12 +00003472TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003473ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003474 switch (Arg.getKind()) {
3475 case TemplateArgument::Null:
3476 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003477
Douglas Gregora8e02e72009-07-28 23:00:59 +00003478 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003479 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003480
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003481 case TemplateArgument::Declaration: {
3482 if (Decl *D = Arg.getAsDecl())
3483 return TemplateArgument(D->getCanonicalDecl());
3484 return TemplateArgument((Decl*)0);
3485 }
Mike Stump11289f42009-09-09 15:08:12 +00003486
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003487 case TemplateArgument::Template:
3488 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003489
3490 case TemplateArgument::TemplateExpansion:
3491 return TemplateArgument(getCanonicalTemplateName(
3492 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003493 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003494
Douglas Gregora8e02e72009-07-28 23:00:59 +00003495 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003496 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003497
Douglas Gregora8e02e72009-07-28 23:00:59 +00003498 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003499 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003500
Douglas Gregora8e02e72009-07-28 23:00:59 +00003501 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003502 if (Arg.pack_size() == 0)
3503 return Arg;
3504
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003505 TemplateArgument *CanonArgs
3506 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003507 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003508 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003509 AEnd = Arg.pack_end();
3510 A != AEnd; (void)++A, ++Idx)
3511 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003512
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003513 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003514 }
3515 }
3516
3517 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003518 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003519}
3520
Douglas Gregor333489b2009-03-27 23:10:48 +00003521NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003522ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003523 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003524 return 0;
3525
3526 switch (NNS->getKind()) {
3527 case NestedNameSpecifier::Identifier:
3528 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003529 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003530 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3531 NNS->getAsIdentifier());
3532
3533 case NestedNameSpecifier::Namespace:
3534 // A namespace is canonical; build a nested-name-specifier with
3535 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003536 return NestedNameSpecifier::Create(*this, 0,
3537 NNS->getAsNamespace()->getOriginalNamespace());
3538
3539 case NestedNameSpecifier::NamespaceAlias:
3540 // A namespace is canonical; build a nested-name-specifier with
3541 // this namespace and no prefix.
3542 return NestedNameSpecifier::Create(*this, 0,
3543 NNS->getAsNamespaceAlias()->getNamespace()
3544 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003545
3546 case NestedNameSpecifier::TypeSpec:
3547 case NestedNameSpecifier::TypeSpecWithTemplate: {
3548 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003549
3550 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3551 // break it apart into its prefix and identifier, then reconsititute those
3552 // as the canonical nested-name-specifier. This is required to canonicalize
3553 // a dependent nested-name-specifier involving typedefs of dependent-name
3554 // types, e.g.,
3555 // typedef typename T::type T1;
3556 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003557 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3558 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003559 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003560
Eli Friedman5358a0a2012-03-03 04:09:56 +00003561 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3562 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3563 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003564 return NestedNameSpecifier::Create(*this, 0, false,
3565 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003566 }
3567
3568 case NestedNameSpecifier::Global:
3569 // The global specifier is canonical and unique.
3570 return NNS;
3571 }
3572
David Blaikie8a40f702012-01-17 06:56:22 +00003573 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003574}
3575
Chris Lattner7adf0762008-08-04 07:31:14 +00003576
Jay Foad39c79802011-01-12 09:06:06 +00003577const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003578 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003579 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003580 // Handle the common positive case fast.
3581 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3582 return AT;
3583 }
Mike Stump11289f42009-09-09 15:08:12 +00003584
John McCall8ccfcb52009-09-24 19:53:00 +00003585 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003586 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003587 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003588
John McCall8ccfcb52009-09-24 19:53:00 +00003589 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003590 // implements C99 6.7.3p8: "If the specification of an array type includes
3591 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003592
Chris Lattner7adf0762008-08-04 07:31:14 +00003593 // If we get here, we either have type qualifiers on the type, or we have
3594 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003595 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003596
John McCall33ddac02011-01-19 10:06:00 +00003597 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003598 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003599
Chris Lattner7adf0762008-08-04 07:31:14 +00003600 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003601 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003602 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003603 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003604
Chris Lattner7adf0762008-08-04 07:31:14 +00003605 // Otherwise, we have an array and we have qualifiers on it. Push the
3606 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003607 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003608
Chris Lattner7adf0762008-08-04 07:31:14 +00003609 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3610 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3611 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003612 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003613 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3614 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3615 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003616 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003617
Mike Stump11289f42009-09-09 15:08:12 +00003618 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003619 = dyn_cast<DependentSizedArrayType>(ATy))
3620 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003621 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003622 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003623 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003624 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003625 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003626
Chris Lattner7adf0762008-08-04 07:31:14 +00003627 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003628 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003629 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003630 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003631 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003632 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003633}
3634
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003635QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003636 // C99 6.7.5.3p7:
3637 // A declaration of a parameter as "array of type" shall be
3638 // adjusted to "qualified pointer to type", where the type
3639 // qualifiers (if any) are those specified within the [ and ] of
3640 // the array type derivation.
3641 if (T->isArrayType())
3642 return getArrayDecayedType(T);
3643
3644 // C99 6.7.5.3p8:
3645 // A declaration of a parameter as "function returning type"
3646 // shall be adjusted to "pointer to function returning type", as
3647 // in 6.3.2.1.
3648 if (T->isFunctionType())
3649 return getPointerType(T);
3650
3651 return T;
3652}
3653
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003654QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003655 T = getVariableArrayDecayedType(T);
3656 T = getAdjustedParameterType(T);
3657 return T.getUnqualifiedType();
3658}
3659
Chris Lattnera21ad802008-04-02 05:18:44 +00003660/// getArrayDecayedType - Return the properly qualified result of decaying the
3661/// specified array type to a pointer. This operation is non-trivial when
3662/// handling typedefs etc. The canonical type of "T" must be an array type,
3663/// this returns a pointer to a properly qualified element of the array.
3664///
3665/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003666QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003667 // Get the element type with 'getAsArrayType' so that we don't lose any
3668 // typedefs in the element type of the array. This also handles propagation
3669 // of type qualifiers from the array type into the element type if present
3670 // (C99 6.7.3p8).
3671 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3672 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003673
Chris Lattner7adf0762008-08-04 07:31:14 +00003674 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003675
3676 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003677 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003678}
3679
John McCall33ddac02011-01-19 10:06:00 +00003680QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3681 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003682}
3683
John McCall33ddac02011-01-19 10:06:00 +00003684QualType ASTContext::getBaseElementType(QualType type) const {
3685 Qualifiers qs;
3686 while (true) {
3687 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003688 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003689 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003690
John McCall33ddac02011-01-19 10:06:00 +00003691 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003692 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003693 }
Mike Stump11289f42009-09-09 15:08:12 +00003694
John McCall33ddac02011-01-19 10:06:00 +00003695 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003696}
3697
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003698/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003699uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003700ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3701 uint64_t ElementCount = 1;
3702 do {
3703 ElementCount *= CA->getSize().getZExtValue();
3704 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3705 } while (CA);
3706 return ElementCount;
3707}
3708
Steve Naroff0af91202007-04-27 21:51:21 +00003709/// getFloatingRank - Return a relative rank for floating point types.
3710/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003711static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003712 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003713 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003714
John McCall9dd450b2009-09-21 23:43:11 +00003715 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3716 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003717 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003718 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003719 case BuiltinType::Float: return FloatRank;
3720 case BuiltinType::Double: return DoubleRank;
3721 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003722 }
3723}
3724
Mike Stump11289f42009-09-09 15:08:12 +00003725/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3726/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003727/// 'typeDomain' is a real floating point or complex type.
3728/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003729QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3730 QualType Domain) const {
3731 FloatingRank EltRank = getFloatingRank(Size);
3732 if (Domain->isComplexType()) {
3733 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003734 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003735 case FloatRank: return FloatComplexTy;
3736 case DoubleRank: return DoubleComplexTy;
3737 case LongDoubleRank: return LongDoubleComplexTy;
3738 }
Steve Naroff0af91202007-04-27 21:51:21 +00003739 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003740
3741 assert(Domain->isRealFloatingType() && "Unknown domain!");
3742 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003743 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003744 case FloatRank: return FloatTy;
3745 case DoubleRank: return DoubleTy;
3746 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003747 }
David Blaikief47fa302012-01-17 02:30:50 +00003748 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003749}
3750
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003751/// getFloatingTypeOrder - Compare the rank of the two specified floating
3752/// point types, ignoring the domain of the type (i.e. 'double' ==
3753/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003754/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003755int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003756 FloatingRank LHSR = getFloatingRank(LHS);
3757 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003758
Chris Lattnerb90739d2008-04-06 23:38:49 +00003759 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003760 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003761 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003762 return 1;
3763 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003764}
3765
Chris Lattner76a00cf2008-04-06 22:59:24 +00003766/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3767/// routine will assert if passed a built-in type that isn't an integer or enum,
3768/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003769unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003770 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003771
Chris Lattner76a00cf2008-04-06 22:59:24 +00003772 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003773 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003774 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003775 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003776 case BuiltinType::Char_S:
3777 case BuiltinType::Char_U:
3778 case BuiltinType::SChar:
3779 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003780 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003781 case BuiltinType::Short:
3782 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003783 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003784 case BuiltinType::Int:
3785 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003786 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003787 case BuiltinType::Long:
3788 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003789 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003790 case BuiltinType::LongLong:
3791 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003792 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003793 case BuiltinType::Int128:
3794 case BuiltinType::UInt128:
3795 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003796 }
3797}
3798
Eli Friedman629ffb92009-08-20 04:21:42 +00003799/// \brief Whether this is a promotable bitfield reference according
3800/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3801///
3802/// \returns the type this bit-field will promote to, or NULL if no
3803/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003804QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003805 if (E->isTypeDependent() || E->isValueDependent())
3806 return QualType();
3807
Eli Friedman629ffb92009-08-20 04:21:42 +00003808 FieldDecl *Field = E->getBitField();
3809 if (!Field)
3810 return QualType();
3811
3812 QualType FT = Field->getType();
3813
Richard Smithcaf33902011-10-10 18:28:20 +00003814 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003815 uint64_t IntSize = getTypeSize(IntTy);
3816 // GCC extension compatibility: if the bit-field size is less than or equal
3817 // to the size of int, it gets promoted no matter what its type is.
3818 // For instance, unsigned long bf : 4 gets promoted to signed int.
3819 if (BitWidth < IntSize)
3820 return IntTy;
3821
3822 if (BitWidth == IntSize)
3823 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3824
3825 // Types bigger than int are not subject to promotions, and therefore act
3826 // like the base type.
3827 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3828 // is ridiculous.
3829 return QualType();
3830}
3831
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003832/// getPromotedIntegerType - Returns the type that Promotable will
3833/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3834/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003835QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003836 assert(!Promotable.isNull());
3837 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003838 if (const EnumType *ET = Promotable->getAs<EnumType>())
3839 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003840
3841 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3842 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3843 // (3.9.1) can be converted to a prvalue of the first of the following
3844 // types that can represent all the values of its underlying type:
3845 // int, unsigned int, long int, unsigned long int, long long int, or
3846 // unsigned long long int [...]
3847 // FIXME: Is there some better way to compute this?
3848 if (BT->getKind() == BuiltinType::WChar_S ||
3849 BT->getKind() == BuiltinType::WChar_U ||
3850 BT->getKind() == BuiltinType::Char16 ||
3851 BT->getKind() == BuiltinType::Char32) {
3852 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3853 uint64_t FromSize = getTypeSize(BT);
3854 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3855 LongLongTy, UnsignedLongLongTy };
3856 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3857 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3858 if (FromSize < ToSize ||
3859 (FromSize == ToSize &&
3860 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3861 return PromoteTypes[Idx];
3862 }
3863 llvm_unreachable("char type should fit into long long");
3864 }
3865 }
3866
3867 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003868 if (Promotable->isSignedIntegerType())
3869 return IntTy;
3870 uint64_t PromotableSize = getTypeSize(Promotable);
3871 uint64_t IntSize = getTypeSize(IntTy);
3872 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3873 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3874}
3875
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003876/// \brief Recurses in pointer/array types until it finds an objc retainable
3877/// type and returns its ownership.
3878Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3879 while (!T.isNull()) {
3880 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3881 return T.getObjCLifetime();
3882 if (T->isArrayType())
3883 T = getBaseElementType(T);
3884 else if (const PointerType *PT = T->getAs<PointerType>())
3885 T = PT->getPointeeType();
3886 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003887 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003888 else
3889 break;
3890 }
3891
3892 return Qualifiers::OCL_None;
3893}
3894
Mike Stump11289f42009-09-09 15:08:12 +00003895/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003896/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003897/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003898int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003899 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3900 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003901 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003902
Chris Lattner76a00cf2008-04-06 22:59:24 +00003903 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3904 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003905
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003906 unsigned LHSRank = getIntegerRank(LHSC);
3907 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003908
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003909 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3910 if (LHSRank == RHSRank) return 0;
3911 return LHSRank > RHSRank ? 1 : -1;
3912 }
Mike Stump11289f42009-09-09 15:08:12 +00003913
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003914 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3915 if (LHSUnsigned) {
3916 // If the unsigned [LHS] type is larger, return it.
3917 if (LHSRank >= RHSRank)
3918 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003919
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003920 // If the signed type can represent all values of the unsigned type, it
3921 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003922 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003923 return -1;
3924 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003925
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003926 // If the unsigned [RHS] type is larger, return it.
3927 if (RHSRank >= LHSRank)
3928 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003929
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003930 // If the signed type can represent all values of the unsigned type, it
3931 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003932 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003933 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003934}
Anders Carlsson98f07902007-08-17 05:31:46 +00003935
Anders Carlsson6d417272009-11-14 21:45:58 +00003936static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003937CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3938 DeclContext *DC, IdentifierInfo *Id) {
3939 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003940 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003941 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003942 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003943 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003944}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003945
Mike Stump11289f42009-09-09 15:08:12 +00003946// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003947QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003948 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003949 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003950 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003951 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003952 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003953
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003954 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003955
Anders Carlsson98f07902007-08-17 05:31:46 +00003956 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003957 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003958 // int flags;
3959 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003960 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003961 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003962 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003963 FieldTypes[3] = LongTy;
3964
Anders Carlsson98f07902007-08-17 05:31:46 +00003965 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003966 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003967 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003968 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003969 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003970 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003971 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003972 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003973 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003974 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003975 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003976 }
3977
Douglas Gregord5058122010-02-11 01:19:42 +00003978 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003979 }
Mike Stump11289f42009-09-09 15:08:12 +00003980
Anders Carlsson98f07902007-08-17 05:31:46 +00003981 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003982}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003983
Douglas Gregor512b0772009-04-23 22:29:11 +00003984void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003985 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003986 assert(Rec && "Invalid CFConstantStringType");
3987 CFConstantStringTypeDecl = Rec->getDecl();
3988}
3989
Jay Foad39c79802011-01-12 09:06:06 +00003990QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003991 if (BlockDescriptorType)
3992 return getTagDeclType(BlockDescriptorType);
3993
3994 RecordDecl *T;
3995 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003996 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003997 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003998 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003999
4000 QualType FieldTypes[] = {
4001 UnsignedLongTy,
4002 UnsignedLongTy,
4003 };
4004
4005 const char *FieldNames[] = {
4006 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004007 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004008 };
4009
4010 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004011 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004012 SourceLocation(),
4013 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004014 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004015 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004016 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004017 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004018 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004019 T->addDecl(Field);
4020 }
4021
Douglas Gregord5058122010-02-11 01:19:42 +00004022 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004023
4024 BlockDescriptorType = T;
4025
4026 return getTagDeclType(BlockDescriptorType);
4027}
4028
Jay Foad39c79802011-01-12 09:06:06 +00004029QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004030 if (BlockDescriptorExtendedType)
4031 return getTagDeclType(BlockDescriptorExtendedType);
4032
4033 RecordDecl *T;
4034 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004035 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004036 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004037 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004038
4039 QualType FieldTypes[] = {
4040 UnsignedLongTy,
4041 UnsignedLongTy,
4042 getPointerType(VoidPtrTy),
4043 getPointerType(VoidPtrTy)
4044 };
4045
4046 const char *FieldNames[] = {
4047 "reserved",
4048 "Size",
4049 "CopyFuncPtr",
4050 "DestroyFuncPtr"
4051 };
4052
4053 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004054 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004055 SourceLocation(),
4056 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004057 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004058 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004059 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004060 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004061 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004062 T->addDecl(Field);
4063 }
4064
Douglas Gregord5058122010-02-11 01:19:42 +00004065 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004066
4067 BlockDescriptorExtendedType = T;
4068
4069 return getTagDeclType(BlockDescriptorExtendedType);
4070}
4071
Jay Foad39c79802011-01-12 09:06:06 +00004072bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004073 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004074 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004075 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004076 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4077 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004078 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004079
4080 }
4081 }
Mike Stump94967902009-10-21 18:16:27 +00004082 return false;
4083}
4084
Jay Foad39c79802011-01-12 09:06:06 +00004085QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004086ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004087 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004088 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004089 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004090 // unsigned int __flags;
4091 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004092 // void *__copy_helper; // as needed
4093 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004094 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004095 // } *
4096
Mike Stump94967902009-10-21 18:16:27 +00004097 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4098
4099 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004100 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004101 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4102 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004103 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004104 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004105 T->startDefinition();
4106 QualType Int32Ty = IntTy;
4107 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4108 QualType FieldTypes[] = {
4109 getPointerType(VoidPtrTy),
4110 getPointerType(getTagDeclType(T)),
4111 Int32Ty,
4112 Int32Ty,
4113 getPointerType(VoidPtrTy),
4114 getPointerType(VoidPtrTy),
4115 Ty
4116 };
4117
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004118 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004119 "__isa",
4120 "__forwarding",
4121 "__flags",
4122 "__size",
4123 "__copy_helper",
4124 "__destroy_helper",
4125 DeclName,
4126 };
4127
4128 for (size_t i = 0; i < 7; ++i) {
4129 if (!HasCopyAndDispose && i >=4 && i <= 5)
4130 continue;
4131 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004132 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004133 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004134 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004135 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004136 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004137 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004138 T->addDecl(Field);
4139 }
4140
Douglas Gregord5058122010-02-11 01:19:42 +00004141 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004142
4143 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004144}
4145
Douglas Gregorbab8a962011-09-08 01:46:34 +00004146TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4147 if (!ObjCInstanceTypeDecl)
4148 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4149 getTranslationUnitDecl(),
4150 SourceLocation(),
4151 SourceLocation(),
4152 &Idents.get("instancetype"),
4153 getTrivialTypeSourceInfo(getObjCIdType()));
4154 return ObjCInstanceTypeDecl;
4155}
4156
Anders Carlsson18acd442007-10-29 06:33:42 +00004157// This returns true if a type has been typedefed to BOOL:
4158// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004159static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004160 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004161 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4162 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004163
Anders Carlssond8499822007-10-29 05:01:08 +00004164 return false;
4165}
4166
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004167/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004168/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004169CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004170 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4171 return CharUnits::Zero();
4172
Ken Dyck40775002010-01-11 17:06:35 +00004173 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004174
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004175 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004176 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004177 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004178 // Treat arrays as pointers, since that's how they're passed in.
4179 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004180 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004181 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004182}
4183
4184static inline
4185std::string charUnitsToString(const CharUnits &CU) {
4186 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004187}
4188
John McCall351762c2011-02-07 10:33:21 +00004189/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004190/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004191std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4192 std::string S;
4193
David Chisnall950a9512009-11-17 19:33:30 +00004194 const BlockDecl *Decl = Expr->getBlockDecl();
4195 QualType BlockTy =
4196 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4197 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004198 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004199 // Compute size of all parameters.
4200 // Start with computing size of a pointer in number of bytes.
4201 // FIXME: There might(should) be a better way of doing this computation!
4202 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004203 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4204 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004205 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004206 E = Decl->param_end(); PI != E; ++PI) {
4207 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004208 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004209 if (sz.isZero())
4210 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004211 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004212 ParmOffset += sz;
4213 }
4214 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004215 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004216 // Block pointer and offset.
4217 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004218
4219 // Argument types.
4220 ParmOffset = PtrSize;
4221 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4222 Decl->param_end(); PI != E; ++PI) {
4223 ParmVarDecl *PVDecl = *PI;
4224 QualType PType = PVDecl->getOriginalType();
4225 if (const ArrayType *AT =
4226 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4227 // Use array's original type only if it has known number of
4228 // elements.
4229 if (!isa<ConstantArrayType>(AT))
4230 PType = PVDecl->getType();
4231 } else if (PType->isFunctionType())
4232 PType = PVDecl->getType();
4233 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004234 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004235 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004236 }
John McCall351762c2011-02-07 10:33:21 +00004237
4238 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004239}
4240
Douglas Gregora9d84932011-05-27 01:19:52 +00004241bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004242 std::string& S) {
4243 // Encode result type.
4244 getObjCEncodingForType(Decl->getResultType(), S);
4245 CharUnits ParmOffset;
4246 // Compute size of all parameters.
4247 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4248 E = Decl->param_end(); PI != E; ++PI) {
4249 QualType PType = (*PI)->getType();
4250 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004251 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004252 continue;
4253
David Chisnall50e4eba2010-12-30 14:05:53 +00004254 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004255 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004256 ParmOffset += sz;
4257 }
4258 S += charUnitsToString(ParmOffset);
4259 ParmOffset = CharUnits::Zero();
4260
4261 // Argument types.
4262 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4263 E = Decl->param_end(); PI != E; ++PI) {
4264 ParmVarDecl *PVDecl = *PI;
4265 QualType PType = PVDecl->getOriginalType();
4266 if (const ArrayType *AT =
4267 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4268 // Use array's original type only if it has known number of
4269 // elements.
4270 if (!isa<ConstantArrayType>(AT))
4271 PType = PVDecl->getType();
4272 } else if (PType->isFunctionType())
4273 PType = PVDecl->getType();
4274 getObjCEncodingForType(PType, S);
4275 S += charUnitsToString(ParmOffset);
4276 ParmOffset += getObjCEncodingTypeSize(PType);
4277 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004278
4279 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004280}
4281
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004282/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4283/// method parameter or return type. If Extended, include class names and
4284/// block object types.
4285void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4286 QualType T, std::string& S,
4287 bool Extended) const {
4288 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4289 getObjCEncodingForTypeQualifier(QT, S);
4290 // Encode parameter type.
4291 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4292 true /*OutermostType*/,
4293 false /*EncodingProperty*/,
4294 false /*StructField*/,
4295 Extended /*EncodeBlockParameters*/,
4296 Extended /*EncodeClassNames*/);
4297}
4298
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004299/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004300/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004301bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004302 std::string& S,
4303 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004304 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004305 // Encode return type.
4306 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4307 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004308 // Compute size of all parameters.
4309 // Start with computing size of a pointer in number of bytes.
4310 // FIXME: There might(should) be a better way of doing this computation!
4311 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004312 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004313 // The first two arguments (self and _cmd) are pointers; account for
4314 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004315 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004316 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004317 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004318 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004319 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004320 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004321 continue;
4322
Ken Dyck40775002010-01-11 17:06:35 +00004323 assert (sz.isPositive() &&
4324 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004325 ParmOffset += sz;
4326 }
Ken Dyck40775002010-01-11 17:06:35 +00004327 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004328 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004329 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004330
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004331 // Argument types.
4332 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004333 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004334 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004335 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004336 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004337 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004338 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4339 // Use array's original type only if it has known number of
4340 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004341 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004342 PType = PVDecl->getType();
4343 } else if (PType->isFunctionType())
4344 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004345 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4346 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004347 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004348 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004349 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004350
4351 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004352}
4353
Daniel Dunbar4932b362008-08-28 04:38:10 +00004354/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004355/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004356/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4357/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004358/// Property attributes are stored as a comma-delimited C string. The simple
4359/// attributes readonly and bycopy are encoded as single characters. The
4360/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4361/// encoded as single characters, followed by an identifier. Property types
4362/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004363/// these attributes are defined by the following enumeration:
4364/// @code
4365/// enum PropertyAttributes {
4366/// kPropertyReadOnly = 'R', // property is read-only.
4367/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4368/// kPropertyByref = '&', // property is a reference to the value last assigned
4369/// kPropertyDynamic = 'D', // property is dynamic
4370/// kPropertyGetter = 'G', // followed by getter selector name
4371/// kPropertySetter = 'S', // followed by setter selector name
4372/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004373/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004374/// kPropertyWeak = 'W' // 'weak' property
4375/// kPropertyStrong = 'P' // property GC'able
4376/// kPropertyNonAtomic = 'N' // property non-atomic
4377/// };
4378/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004379void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004380 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004381 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004382 // Collect information from the property implementation decl(s).
4383 bool Dynamic = false;
4384 ObjCPropertyImplDecl *SynthesizePID = 0;
4385
4386 // FIXME: Duplicated code due to poor abstraction.
4387 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004388 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004389 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4390 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004391 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004392 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004393 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004394 if (PID->getPropertyDecl() == PD) {
4395 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4396 Dynamic = true;
4397 } else {
4398 SynthesizePID = PID;
4399 }
4400 }
4401 }
4402 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004403 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004404 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004405 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004406 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004407 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004408 if (PID->getPropertyDecl() == PD) {
4409 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4410 Dynamic = true;
4411 } else {
4412 SynthesizePID = PID;
4413 }
4414 }
Mike Stump11289f42009-09-09 15:08:12 +00004415 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004416 }
4417 }
4418
4419 // FIXME: This is not very efficient.
4420 S = "T";
4421
4422 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004423 // GCC has some special rules regarding encoding of properties which
4424 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004425 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004426 true /* outermost type */,
4427 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004428
4429 if (PD->isReadOnly()) {
4430 S += ",R";
4431 } else {
4432 switch (PD->getSetterKind()) {
4433 case ObjCPropertyDecl::Assign: break;
4434 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004435 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004436 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004437 }
4438 }
4439
4440 // It really isn't clear at all what this means, since properties
4441 // are "dynamic by default".
4442 if (Dynamic)
4443 S += ",D";
4444
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004445 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4446 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004447
Daniel Dunbar4932b362008-08-28 04:38:10 +00004448 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4449 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004450 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004451 }
4452
4453 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4454 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004455 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004456 }
4457
4458 if (SynthesizePID) {
4459 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4460 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004461 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004462 }
4463
4464 // FIXME: OBJCGC: weak & strong
4465}
4466
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004467/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004468/// Another legacy compatibility encoding: 32-bit longs are encoded as
4469/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004470/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4471///
4472void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004473 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004474 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004475 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004476 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004477 else
Jay Foad39c79802011-01-12 09:06:06 +00004478 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004479 PointeeTy = IntTy;
4480 }
4481 }
4482}
4483
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004484void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004485 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004486 // We follow the behavior of gcc, expanding structures which are
4487 // directly pointed to, and expanding embedded structures. Note that
4488 // these rules are sufficient to prevent recursive encoding of the
4489 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004490 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004491 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004492}
4493
David Chisnallb190a2c2010-06-04 01:10:52 +00004494static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4495 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004496 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004497 case BuiltinType::Void: return 'v';
4498 case BuiltinType::Bool: return 'B';
4499 case BuiltinType::Char_U:
4500 case BuiltinType::UChar: return 'C';
4501 case BuiltinType::UShort: return 'S';
4502 case BuiltinType::UInt: return 'I';
4503 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004504 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004505 case BuiltinType::UInt128: return 'T';
4506 case BuiltinType::ULongLong: return 'Q';
4507 case BuiltinType::Char_S:
4508 case BuiltinType::SChar: return 'c';
4509 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004510 case BuiltinType::WChar_S:
4511 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004512 case BuiltinType::Int: return 'i';
4513 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004514 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004515 case BuiltinType::LongLong: return 'q';
4516 case BuiltinType::Int128: return 't';
4517 case BuiltinType::Float: return 'f';
4518 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004519 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004520 }
4521}
4522
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004523static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4524 EnumDecl *Enum = ET->getDecl();
4525
4526 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4527 if (!Enum->isFixed())
4528 return 'i';
4529
4530 // The encoding of a fixed enum type matches its fixed underlying type.
4531 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4532}
4533
Jay Foad39c79802011-01-12 09:06:06 +00004534static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004535 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004536 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004537 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004538 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4539 // The GNU runtime requires more information; bitfields are encoded as b,
4540 // then the offset (in bits) of the first element, then the type of the
4541 // bitfield, then the size in bits. For example, in this structure:
4542 //
4543 // struct
4544 // {
4545 // int integer;
4546 // int flags:2;
4547 // };
4548 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4549 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4550 // information is not especially sensible, but we're stuck with it for
4551 // compatibility with GCC, although providing it breaks anything that
4552 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004553 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004554 const RecordDecl *RD = FD->getParent();
4555 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004556 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004557 if (const EnumType *ET = T->getAs<EnumType>())
4558 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004559 else
Jay Foad39c79802011-01-12 09:06:06 +00004560 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004561 }
Richard Smithcaf33902011-10-10 18:28:20 +00004562 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004563}
4564
Daniel Dunbar07d07852009-10-18 21:17:35 +00004565// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004566void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4567 bool ExpandPointedToStructures,
4568 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004569 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004570 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004571 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004572 bool StructField,
4573 bool EncodeBlockParameters,
4574 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004575 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004576 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004577 return EncodeBitField(this, S, T, FD);
4578 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004579 return;
4580 }
Mike Stump11289f42009-09-09 15:08:12 +00004581
John McCall9dd450b2009-09-21 23:43:11 +00004582 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004583 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004584 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004585 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004586 return;
4587 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004588
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004589 // encoding for pointer or r3eference types.
4590 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004591 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004592 if (PT->isObjCSelType()) {
4593 S += ':';
4594 return;
4595 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004596 PointeeTy = PT->getPointeeType();
4597 }
4598 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4599 PointeeTy = RT->getPointeeType();
4600 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004601 bool isReadOnly = false;
4602 // For historical/compatibility reasons, the read-only qualifier of the
4603 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4604 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004605 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004606 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004607 if (OutermostType && T.isConstQualified()) {
4608 isReadOnly = true;
4609 S += 'r';
4610 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004611 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004612 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004613 while (P->getAs<PointerType>())
4614 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004615 if (P.isConstQualified()) {
4616 isReadOnly = true;
4617 S += 'r';
4618 }
4619 }
4620 if (isReadOnly) {
4621 // Another legacy compatibility encoding. Some ObjC qualifier and type
4622 // combinations need to be rearranged.
4623 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004624 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004625 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004626 }
Mike Stump11289f42009-09-09 15:08:12 +00004627
Anders Carlssond8499822007-10-29 05:01:08 +00004628 if (PointeeTy->isCharType()) {
4629 // char pointer types should be encoded as '*' unless it is a
4630 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004631 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004632 S += '*';
4633 return;
4634 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004635 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004636 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4637 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4638 S += '#';
4639 return;
4640 }
4641 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4642 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4643 S += '@';
4644 return;
4645 }
4646 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004647 }
Anders Carlssond8499822007-10-29 05:01:08 +00004648 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004649 getLegacyIntegralTypeEncoding(PointeeTy);
4650
Mike Stump11289f42009-09-09 15:08:12 +00004651 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004652 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004653 return;
4654 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004655
Chris Lattnere7cabb92009-07-13 00:10:46 +00004656 if (const ArrayType *AT =
4657 // Ignore type qualifiers etc.
4658 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004659 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004660 // Incomplete arrays are encoded as a pointer to the array element.
4661 S += '^';
4662
Mike Stump11289f42009-09-09 15:08:12 +00004663 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004664 false, ExpandStructures, FD);
4665 } else {
4666 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004667
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004668 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4669 if (getTypeSize(CAT->getElementType()) == 0)
4670 S += '0';
4671 else
4672 S += llvm::utostr(CAT->getSize().getZExtValue());
4673 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004674 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004675 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4676 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004677 S += '0';
4678 }
Mike Stump11289f42009-09-09 15:08:12 +00004679
4680 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004681 false, ExpandStructures, FD);
4682 S += ']';
4683 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004684 return;
4685 }
Mike Stump11289f42009-09-09 15:08:12 +00004686
John McCall9dd450b2009-09-21 23:43:11 +00004687 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004688 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004689 return;
4690 }
Mike Stump11289f42009-09-09 15:08:12 +00004691
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004692 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004693 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004694 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004695 // Anonymous structures print as '?'
4696 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4697 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004698 if (ClassTemplateSpecializationDecl *Spec
4699 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4700 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4701 std::string TemplateArgsStr
4702 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004703 TemplateArgs.data(),
4704 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004705 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004706
4707 S += TemplateArgsStr;
4708 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004709 } else {
4710 S += '?';
4711 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004712 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004713 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004714 if (!RDecl->isUnion()) {
4715 getObjCEncodingForStructureImpl(RDecl, S, FD);
4716 } else {
4717 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4718 FieldEnd = RDecl->field_end();
4719 Field != FieldEnd; ++Field) {
4720 if (FD) {
4721 S += '"';
4722 S += Field->getNameAsString();
4723 S += '"';
4724 }
Mike Stump11289f42009-09-09 15:08:12 +00004725
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004726 // Special case bit-fields.
4727 if (Field->isBitField()) {
4728 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004729 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004730 } else {
4731 QualType qt = Field->getType();
4732 getLegacyIntegralTypeEncoding(qt);
4733 getObjCEncodingForTypeImpl(qt, S, false, true,
4734 FD, /*OutermostType*/false,
4735 /*EncodingProperty*/false,
4736 /*StructField*/true);
4737 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004738 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004739 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004740 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004741 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004742 return;
4743 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004744
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004745 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004746 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004747 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004748 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004749 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004750 return;
4751 }
Mike Stump11289f42009-09-09 15:08:12 +00004752
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004753 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004754 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004755 if (EncodeBlockParameters) {
4756 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4757
4758 S += '<';
4759 // Block return type
4760 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4761 ExpandPointedToStructures, ExpandStructures,
4762 FD,
4763 false /* OutermostType */,
4764 EncodingProperty,
4765 false /* StructField */,
4766 EncodeBlockParameters,
4767 EncodeClassNames);
4768 // Block self
4769 S += "@?";
4770 // Block parameters
4771 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4772 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4773 E = FPT->arg_type_end(); I && (I != E); ++I) {
4774 getObjCEncodingForTypeImpl(*I, S,
4775 ExpandPointedToStructures,
4776 ExpandStructures,
4777 FD,
4778 false /* OutermostType */,
4779 EncodingProperty,
4780 false /* StructField */,
4781 EncodeBlockParameters,
4782 EncodeClassNames);
4783 }
4784 }
4785 S += '>';
4786 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004787 return;
4788 }
Mike Stump11289f42009-09-09 15:08:12 +00004789
John McCall8b07ec22010-05-15 11:32:37 +00004790 // Ignore protocol qualifiers when mangling at this level.
4791 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4792 T = OT->getBaseType();
4793
John McCall8ccfcb52009-09-24 19:53:00 +00004794 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004795 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004796 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004797 S += '{';
4798 const IdentifierInfo *II = OI->getIdentifier();
4799 S += II->getName();
4800 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004801 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004802 DeepCollectObjCIvars(OI, true, Ivars);
4803 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004804 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004805 if (Field->isBitField())
4806 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004807 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004808 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004809 }
4810 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004811 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004812 }
Mike Stump11289f42009-09-09 15:08:12 +00004813
John McCall9dd450b2009-09-21 23:43:11 +00004814 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004815 if (OPT->isObjCIdType()) {
4816 S += '@';
4817 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004818 }
Mike Stump11289f42009-09-09 15:08:12 +00004819
Steve Narofff0c86112009-10-28 22:03:49 +00004820 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4821 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4822 // Since this is a binary compatibility issue, need to consult with runtime
4823 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004824 S += '#';
4825 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004826 }
Mike Stump11289f42009-09-09 15:08:12 +00004827
Chris Lattnere7cabb92009-07-13 00:10:46 +00004828 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004829 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004830 ExpandPointedToStructures,
4831 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004832 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004833 // Note that we do extended encoding of protocol qualifer list
4834 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004835 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004836 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4837 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004838 S += '<';
4839 S += (*I)->getNameAsString();
4840 S += '>';
4841 }
4842 S += '"';
4843 }
4844 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004845 }
Mike Stump11289f42009-09-09 15:08:12 +00004846
Chris Lattnere7cabb92009-07-13 00:10:46 +00004847 QualType PointeeTy = OPT->getPointeeType();
4848 if (!EncodingProperty &&
4849 isa<TypedefType>(PointeeTy.getTypePtr())) {
4850 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004851 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004852 // {...};
4853 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004854 getObjCEncodingForTypeImpl(PointeeTy, S,
4855 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004856 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004857 return;
4858 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004859
4860 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004861 if (OPT->getInterfaceDecl() &&
4862 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004863 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004864 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004865 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4866 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004867 S += '<';
4868 S += (*I)->getNameAsString();
4869 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004870 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004871 S += '"';
4872 }
4873 return;
4874 }
Mike Stump11289f42009-09-09 15:08:12 +00004875
John McCalla9e6e8d2010-05-17 23:56:34 +00004876 // gcc just blithely ignores member pointers.
4877 // TODO: maybe there should be a mangling for these
4878 if (T->getAs<MemberPointerType>())
4879 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004880
4881 if (T->isVectorType()) {
4882 // This matches gcc's encoding, even though technically it is
4883 // insufficient.
4884 // FIXME. We should do a better job than gcc.
4885 return;
4886 }
4887
David Blaikie83d382b2011-09-23 05:06:16 +00004888 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004889}
4890
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004891void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4892 std::string &S,
4893 const FieldDecl *FD,
4894 bool includeVBases) const {
4895 assert(RDecl && "Expected non-null RecordDecl");
4896 assert(!RDecl->isUnion() && "Should not be called for unions");
4897 if (!RDecl->getDefinition())
4898 return;
4899
4900 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4901 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4902 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4903
4904 if (CXXRec) {
4905 for (CXXRecordDecl::base_class_iterator
4906 BI = CXXRec->bases_begin(),
4907 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4908 if (!BI->isVirtual()) {
4909 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004910 if (base->isEmpty())
4911 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00004912 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004913 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4914 std::make_pair(offs, base));
4915 }
4916 }
4917 }
4918
4919 unsigned i = 0;
4920 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4921 FieldEnd = RDecl->field_end();
4922 Field != FieldEnd; ++Field, ++i) {
4923 uint64_t offs = layout.getFieldOffset(i);
4924 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00004925 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004926 }
4927
4928 if (CXXRec && includeVBases) {
4929 for (CXXRecordDecl::base_class_iterator
4930 BI = CXXRec->vbases_begin(),
4931 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4932 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004933 if (base->isEmpty())
4934 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00004935 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004936 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4937 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4938 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004939 }
4940 }
4941
4942 CharUnits size;
4943 if (CXXRec) {
4944 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4945 } else {
4946 size = layout.getSize();
4947 }
4948
4949 uint64_t CurOffs = 0;
4950 std::multimap<uint64_t, NamedDecl *>::iterator
4951 CurLayObj = FieldOrBaseOffsets.begin();
4952
Douglas Gregorf5d6c742012-04-27 22:30:01 +00004953 if (CXXRec && CXXRec->isDynamicClass() &&
4954 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004955 if (FD) {
4956 S += "\"_vptr$";
4957 std::string recname = CXXRec->getNameAsString();
4958 if (recname.empty()) recname = "?";
4959 S += recname;
4960 S += '"';
4961 }
4962 S += "^^?";
4963 CurOffs += getTypeSize(VoidPtrTy);
4964 }
4965
4966 if (!RDecl->hasFlexibleArrayMember()) {
4967 // Mark the end of the structure.
4968 uint64_t offs = toBits(size);
4969 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4970 std::make_pair(offs, (NamedDecl*)0));
4971 }
4972
4973 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4974 assert(CurOffs <= CurLayObj->first);
4975
4976 if (CurOffs < CurLayObj->first) {
4977 uint64_t padding = CurLayObj->first - CurOffs;
4978 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4979 // packing/alignment of members is different that normal, in which case
4980 // the encoding will be out-of-sync with the real layout.
4981 // If the runtime switches to just consider the size of types without
4982 // taking into account alignment, we could make padding explicit in the
4983 // encoding (e.g. using arrays of chars). The encoding strings would be
4984 // longer then though.
4985 CurOffs += padding;
4986 }
4987
4988 NamedDecl *dcl = CurLayObj->second;
4989 if (dcl == 0)
4990 break; // reached end of structure.
4991
4992 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4993 // We expand the bases without their virtual bases since those are going
4994 // in the initial structure. Note that this differs from gcc which
4995 // expands virtual bases each time one is encountered in the hierarchy,
4996 // making the encoding type bigger than it really is.
4997 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004998 assert(!base->isEmpty());
4999 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005000 } else {
5001 FieldDecl *field = cast<FieldDecl>(dcl);
5002 if (FD) {
5003 S += '"';
5004 S += field->getNameAsString();
5005 S += '"';
5006 }
5007
5008 if (field->isBitField()) {
5009 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005010 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005011 } else {
5012 QualType qt = field->getType();
5013 getLegacyIntegralTypeEncoding(qt);
5014 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5015 /*OutermostType*/false,
5016 /*EncodingProperty*/false,
5017 /*StructField*/true);
5018 CurOffs += getTypeSize(field->getType());
5019 }
5020 }
5021 }
5022}
5023
Mike Stump11289f42009-09-09 15:08:12 +00005024void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005025 std::string& S) const {
5026 if (QT & Decl::OBJC_TQ_In)
5027 S += 'n';
5028 if (QT & Decl::OBJC_TQ_Inout)
5029 S += 'N';
5030 if (QT & Decl::OBJC_TQ_Out)
5031 S += 'o';
5032 if (QT & Decl::OBJC_TQ_Bycopy)
5033 S += 'O';
5034 if (QT & Decl::OBJC_TQ_Byref)
5035 S += 'R';
5036 if (QT & Decl::OBJC_TQ_Oneway)
5037 S += 'V';
5038}
5039
Douglas Gregor3ea72692011-08-12 05:46:01 +00005040TypedefDecl *ASTContext::getObjCIdDecl() const {
5041 if (!ObjCIdDecl) {
5042 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5043 T = getObjCObjectPointerType(T);
5044 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5045 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5046 getTranslationUnitDecl(),
5047 SourceLocation(), SourceLocation(),
5048 &Idents.get("id"), IdInfo);
5049 }
5050
5051 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005052}
5053
Douglas Gregor52e02802011-08-12 06:17:30 +00005054TypedefDecl *ASTContext::getObjCSelDecl() const {
5055 if (!ObjCSelDecl) {
5056 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5057 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5058 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5059 getTranslationUnitDecl(),
5060 SourceLocation(), SourceLocation(),
5061 &Idents.get("SEL"), SelInfo);
5062 }
5063 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005064}
5065
Douglas Gregor0a586182011-08-12 05:59:41 +00005066TypedefDecl *ASTContext::getObjCClassDecl() const {
5067 if (!ObjCClassDecl) {
5068 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5069 T = getObjCObjectPointerType(T);
5070 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5071 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5072 getTranslationUnitDecl(),
5073 SourceLocation(), SourceLocation(),
5074 &Idents.get("Class"), ClassInfo);
5075 }
5076
5077 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005078}
5079
Douglas Gregord53ae832012-01-17 18:09:05 +00005080ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5081 if (!ObjCProtocolClassDecl) {
5082 ObjCProtocolClassDecl
5083 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5084 SourceLocation(),
5085 &Idents.get("Protocol"),
5086 /*PrevDecl=*/0,
5087 SourceLocation(), true);
5088 }
5089
5090 return ObjCProtocolClassDecl;
5091}
5092
Meador Inge5d3fb222012-06-16 03:34:49 +00005093//===----------------------------------------------------------------------===//
5094// __builtin_va_list Construction Functions
5095//===----------------------------------------------------------------------===//
5096
5097static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5098 // typedef char* __builtin_va_list;
5099 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5100 TypeSourceInfo *TInfo
5101 = Context->getTrivialTypeSourceInfo(CharPtrType);
5102
5103 TypedefDecl *VaListTypeDecl
5104 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5105 Context->getTranslationUnitDecl(),
5106 SourceLocation(), SourceLocation(),
5107 &Context->Idents.get("__builtin_va_list"),
5108 TInfo);
5109 return VaListTypeDecl;
5110}
5111
5112static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5113 // typedef void* __builtin_va_list;
5114 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5115 TypeSourceInfo *TInfo
5116 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5117
5118 TypedefDecl *VaListTypeDecl
5119 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5120 Context->getTranslationUnitDecl(),
5121 SourceLocation(), SourceLocation(),
5122 &Context->Idents.get("__builtin_va_list"),
5123 TInfo);
5124 return VaListTypeDecl;
5125}
5126
5127static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5128 // typedef struct __va_list_tag {
5129 RecordDecl *VaListTagDecl;
5130
5131 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5132 Context->getTranslationUnitDecl(),
5133 &Context->Idents.get("__va_list_tag"));
5134 VaListTagDecl->startDefinition();
5135
5136 const size_t NumFields = 5;
5137 QualType FieldTypes[NumFields];
5138 const char *FieldNames[NumFields];
5139
5140 // unsigned char gpr;
5141 FieldTypes[0] = Context->UnsignedCharTy;
5142 FieldNames[0] = "gpr";
5143
5144 // unsigned char fpr;
5145 FieldTypes[1] = Context->UnsignedCharTy;
5146 FieldNames[1] = "fpr";
5147
5148 // unsigned short reserved;
5149 FieldTypes[2] = Context->UnsignedShortTy;
5150 FieldNames[2] = "reserved";
5151
5152 // void* overflow_arg_area;
5153 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5154 FieldNames[3] = "overflow_arg_area";
5155
5156 // void* reg_save_area;
5157 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5158 FieldNames[4] = "reg_save_area";
5159
5160 // Create fields
5161 for (unsigned i = 0; i < NumFields; ++i) {
5162 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5163 SourceLocation(),
5164 SourceLocation(),
5165 &Context->Idents.get(FieldNames[i]),
5166 FieldTypes[i], /*TInfo=*/0,
5167 /*BitWidth=*/0,
5168 /*Mutable=*/false,
5169 ICIS_NoInit);
5170 Field->setAccess(AS_public);
5171 VaListTagDecl->addDecl(Field);
5172 }
5173 VaListTagDecl->completeDefinition();
5174 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005175 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005176
5177 // } __va_list_tag;
5178 TypedefDecl *VaListTagTypedefDecl
5179 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5180 Context->getTranslationUnitDecl(),
5181 SourceLocation(), SourceLocation(),
5182 &Context->Idents.get("__va_list_tag"),
5183 Context->getTrivialTypeSourceInfo(VaListTagType));
5184 QualType VaListTagTypedefType =
5185 Context->getTypedefType(VaListTagTypedefDecl);
5186
5187 // typedef __va_list_tag __builtin_va_list[1];
5188 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5189 QualType VaListTagArrayType
5190 = Context->getConstantArrayType(VaListTagTypedefType,
5191 Size, ArrayType::Normal, 0);
5192 TypeSourceInfo *TInfo
5193 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5194 TypedefDecl *VaListTypedefDecl
5195 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5196 Context->getTranslationUnitDecl(),
5197 SourceLocation(), SourceLocation(),
5198 &Context->Idents.get("__builtin_va_list"),
5199 TInfo);
5200
5201 return VaListTypedefDecl;
5202}
5203
5204static TypedefDecl *
5205CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5206 // typedef struct __va_list_tag {
5207 RecordDecl *VaListTagDecl;
5208 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5209 Context->getTranslationUnitDecl(),
5210 &Context->Idents.get("__va_list_tag"));
5211 VaListTagDecl->startDefinition();
5212
5213 const size_t NumFields = 4;
5214 QualType FieldTypes[NumFields];
5215 const char *FieldNames[NumFields];
5216
5217 // unsigned gp_offset;
5218 FieldTypes[0] = Context->UnsignedIntTy;
5219 FieldNames[0] = "gp_offset";
5220
5221 // unsigned fp_offset;
5222 FieldTypes[1] = Context->UnsignedIntTy;
5223 FieldNames[1] = "fp_offset";
5224
5225 // void* overflow_arg_area;
5226 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5227 FieldNames[2] = "overflow_arg_area";
5228
5229 // void* reg_save_area;
5230 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5231 FieldNames[3] = "reg_save_area";
5232
5233 // Create fields
5234 for (unsigned i = 0; i < NumFields; ++i) {
5235 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5236 VaListTagDecl,
5237 SourceLocation(),
5238 SourceLocation(),
5239 &Context->Idents.get(FieldNames[i]),
5240 FieldTypes[i], /*TInfo=*/0,
5241 /*BitWidth=*/0,
5242 /*Mutable=*/false,
5243 ICIS_NoInit);
5244 Field->setAccess(AS_public);
5245 VaListTagDecl->addDecl(Field);
5246 }
5247 VaListTagDecl->completeDefinition();
5248 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005249 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005250
5251 // } __va_list_tag;
5252 TypedefDecl *VaListTagTypedefDecl
5253 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5254 Context->getTranslationUnitDecl(),
5255 SourceLocation(), SourceLocation(),
5256 &Context->Idents.get("__va_list_tag"),
5257 Context->getTrivialTypeSourceInfo(VaListTagType));
5258 QualType VaListTagTypedefType =
5259 Context->getTypedefType(VaListTagTypedefDecl);
5260
5261 // typedef __va_list_tag __builtin_va_list[1];
5262 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5263 QualType VaListTagArrayType
5264 = Context->getConstantArrayType(VaListTagTypedefType,
5265 Size, ArrayType::Normal,0);
5266 TypeSourceInfo *TInfo
5267 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5268 TypedefDecl *VaListTypedefDecl
5269 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5270 Context->getTranslationUnitDecl(),
5271 SourceLocation(), SourceLocation(),
5272 &Context->Idents.get("__builtin_va_list"),
5273 TInfo);
5274
5275 return VaListTypedefDecl;
5276}
5277
5278static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5279 // typedef int __builtin_va_list[4];
5280 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5281 QualType IntArrayType
5282 = Context->getConstantArrayType(Context->IntTy,
5283 Size, ArrayType::Normal, 0);
5284 TypedefDecl *VaListTypedefDecl
5285 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5286 Context->getTranslationUnitDecl(),
5287 SourceLocation(), SourceLocation(),
5288 &Context->Idents.get("__builtin_va_list"),
5289 Context->getTrivialTypeSourceInfo(IntArrayType));
5290
5291 return VaListTypedefDecl;
5292}
5293
5294static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5295 TargetInfo::BuiltinVaListKind Kind) {
5296 switch (Kind) {
5297 case TargetInfo::CharPtrBuiltinVaList:
5298 return CreateCharPtrBuiltinVaListDecl(Context);
5299 case TargetInfo::VoidPtrBuiltinVaList:
5300 return CreateVoidPtrBuiltinVaListDecl(Context);
5301 case TargetInfo::PowerABIBuiltinVaList:
5302 return CreatePowerABIBuiltinVaListDecl(Context);
5303 case TargetInfo::X86_64ABIBuiltinVaList:
5304 return CreateX86_64ABIBuiltinVaListDecl(Context);
5305 case TargetInfo::PNaClABIBuiltinVaList:
5306 return CreatePNaClABIBuiltinVaListDecl(Context);
5307 }
5308
5309 llvm_unreachable("Unhandled __builtin_va_list type kind");
5310}
5311
5312TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5313 if (!BuiltinVaListDecl)
5314 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5315
5316 return BuiltinVaListDecl;
5317}
5318
Meador Ingecfb60902012-07-01 15:57:25 +00005319QualType ASTContext::getVaListTagType() const {
5320 // Force the creation of VaListTagTy by building the __builtin_va_list
5321 // declaration.
5322 if (VaListTagTy.isNull())
5323 (void) getBuiltinVaListDecl();
5324
5325 return VaListTagTy;
5326}
5327
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005328void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005329 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005330 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005331
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005332 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005333}
5334
John McCalld28ae272009-12-02 08:04:21 +00005335/// \brief Retrieve the template name that corresponds to a non-empty
5336/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005337TemplateName
5338ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5339 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005340 unsigned size = End - Begin;
5341 assert(size > 1 && "set is not overloaded!");
5342
5343 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5344 size * sizeof(FunctionTemplateDecl*));
5345 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5346
5347 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005348 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005349 NamedDecl *D = *I;
5350 assert(isa<FunctionTemplateDecl>(D) ||
5351 (isa<UsingShadowDecl>(D) &&
5352 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5353 *Storage++ = D;
5354 }
5355
5356 return TemplateName(OT);
5357}
5358
Douglas Gregordc572a32009-03-30 22:58:21 +00005359/// \brief Retrieve the template name that represents a qualified
5360/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005361TemplateName
5362ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5363 bool TemplateKeyword,
5364 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005365 assert(NNS && "Missing nested-name-specifier in qualified template name");
5366
Douglas Gregorc42075a2010-02-04 18:10:26 +00005367 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005368 llvm::FoldingSetNodeID ID;
5369 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5370
5371 void *InsertPos = 0;
5372 QualifiedTemplateName *QTN =
5373 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5374 if (!QTN) {
5375 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5376 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5377 }
5378
5379 return TemplateName(QTN);
5380}
5381
5382/// \brief Retrieve the template name that represents a dependent
5383/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005384TemplateName
5385ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5386 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005387 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005388 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005389
5390 llvm::FoldingSetNodeID ID;
5391 DependentTemplateName::Profile(ID, NNS, Name);
5392
5393 void *InsertPos = 0;
5394 DependentTemplateName *QTN =
5395 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5396
5397 if (QTN)
5398 return TemplateName(QTN);
5399
5400 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5401 if (CanonNNS == NNS) {
5402 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5403 } else {
5404 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5405 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005406 DependentTemplateName *CheckQTN =
5407 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5408 assert(!CheckQTN && "Dependent type name canonicalization broken");
5409 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005410 }
5411
5412 DependentTemplateNames.InsertNode(QTN, InsertPos);
5413 return TemplateName(QTN);
5414}
5415
Douglas Gregor71395fa2009-11-04 00:56:37 +00005416/// \brief Retrieve the template name that represents a dependent
5417/// template name such as \c MetaFun::template operator+.
5418TemplateName
5419ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005420 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005421 assert((!NNS || NNS->isDependent()) &&
5422 "Nested name specifier must be dependent");
5423
5424 llvm::FoldingSetNodeID ID;
5425 DependentTemplateName::Profile(ID, NNS, Operator);
5426
5427 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005428 DependentTemplateName *QTN
5429 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005430
5431 if (QTN)
5432 return TemplateName(QTN);
5433
5434 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5435 if (CanonNNS == NNS) {
5436 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5437 } else {
5438 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5439 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005440
5441 DependentTemplateName *CheckQTN
5442 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5443 assert(!CheckQTN && "Dependent template name canonicalization broken");
5444 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005445 }
5446
5447 DependentTemplateNames.InsertNode(QTN, InsertPos);
5448 return TemplateName(QTN);
5449}
5450
Douglas Gregor5590be02011-01-15 06:45:20 +00005451TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005452ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5453 TemplateName replacement) const {
5454 llvm::FoldingSetNodeID ID;
5455 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5456
5457 void *insertPos = 0;
5458 SubstTemplateTemplateParmStorage *subst
5459 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5460
5461 if (!subst) {
5462 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5463 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5464 }
5465
5466 return TemplateName(subst);
5467}
5468
5469TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005470ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5471 const TemplateArgument &ArgPack) const {
5472 ASTContext &Self = const_cast<ASTContext &>(*this);
5473 llvm::FoldingSetNodeID ID;
5474 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5475
5476 void *InsertPos = 0;
5477 SubstTemplateTemplateParmPackStorage *Subst
5478 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5479
5480 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005481 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005482 ArgPack.pack_size(),
5483 ArgPack.pack_begin());
5484 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5485 }
5486
5487 return TemplateName(Subst);
5488}
5489
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005490/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005491/// TargetInfo, produce the corresponding type. The unsigned @p Type
5492/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005493CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005494 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005495 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005496 case TargetInfo::SignedShort: return ShortTy;
5497 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5498 case TargetInfo::SignedInt: return IntTy;
5499 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5500 case TargetInfo::SignedLong: return LongTy;
5501 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5502 case TargetInfo::SignedLongLong: return LongLongTy;
5503 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5504 }
5505
David Blaikie83d382b2011-09-23 05:06:16 +00005506 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005507}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005508
5509//===----------------------------------------------------------------------===//
5510// Type Predicates.
5511//===----------------------------------------------------------------------===//
5512
Fariborz Jahanian96207692009-02-18 21:49:28 +00005513/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5514/// garbage collection attribute.
5515///
John McCall553d45a2011-01-12 00:34:59 +00005516Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005517 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005518 return Qualifiers::GCNone;
5519
David Blaikiebbafb8a2012-03-11 07:00:24 +00005520 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005521 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5522
5523 // Default behaviour under objective-C's gc is for ObjC pointers
5524 // (or pointers to them) be treated as though they were declared
5525 // as __strong.
5526 if (GCAttrs == Qualifiers::GCNone) {
5527 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5528 return Qualifiers::Strong;
5529 else if (Ty->isPointerType())
5530 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5531 } else {
5532 // It's not valid to set GC attributes on anything that isn't a
5533 // pointer.
5534#ifndef NDEBUG
5535 QualType CT = Ty->getCanonicalTypeInternal();
5536 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5537 CT = AT->getElementType();
5538 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5539#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005540 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005541 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005542}
5543
Chris Lattner49af6a42008-04-07 06:51:04 +00005544//===----------------------------------------------------------------------===//
5545// Type Compatibility Testing
5546//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005547
Mike Stump11289f42009-09-09 15:08:12 +00005548/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005549/// compatible.
5550static bool areCompatVectorTypes(const VectorType *LHS,
5551 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005552 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005553 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005554 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005555}
5556
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005557bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5558 QualType SecondVec) {
5559 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5560 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5561
5562 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5563 return true;
5564
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005565 // Treat Neon vector types and most AltiVec vector types as if they are the
5566 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005567 const VectorType *First = FirstVec->getAs<VectorType>();
5568 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005569 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005570 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005571 First->getVectorKind() != VectorType::AltiVecPixel &&
5572 First->getVectorKind() != VectorType::AltiVecBool &&
5573 Second->getVectorKind() != VectorType::AltiVecPixel &&
5574 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005575 return true;
5576
5577 return false;
5578}
5579
Steve Naroff8e6aee52009-07-23 01:01:38 +00005580//===----------------------------------------------------------------------===//
5581// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5582//===----------------------------------------------------------------------===//
5583
5584/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5585/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005586bool
5587ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5588 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005589 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005590 return true;
5591 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5592 E = rProto->protocol_end(); PI != E; ++PI)
5593 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5594 return true;
5595 return false;
5596}
5597
Steve Naroff8e6aee52009-07-23 01:01:38 +00005598/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5599/// return true if lhs's protocols conform to rhs's protocol; false
5600/// otherwise.
5601bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5602 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5603 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5604 return false;
5605}
5606
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005607/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5608/// Class<p1, ...>.
5609bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5610 QualType rhs) {
5611 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5612 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5613 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5614
5615 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5616 E = lhsQID->qual_end(); I != E; ++I) {
5617 bool match = false;
5618 ObjCProtocolDecl *lhsProto = *I;
5619 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5620 E = rhsOPT->qual_end(); J != E; ++J) {
5621 ObjCProtocolDecl *rhsProto = *J;
5622 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5623 match = true;
5624 break;
5625 }
5626 }
5627 if (!match)
5628 return false;
5629 }
5630 return true;
5631}
5632
Steve Naroff8e6aee52009-07-23 01:01:38 +00005633/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5634/// ObjCQualifiedIDType.
5635bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5636 bool compare) {
5637 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005638 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005639 lhs->isObjCIdType() || lhs->isObjCClassType())
5640 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005641 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005642 rhs->isObjCIdType() || rhs->isObjCClassType())
5643 return true;
5644
5645 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005646 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005647
Steve Naroff8e6aee52009-07-23 01:01:38 +00005648 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005649
Steve Naroff8e6aee52009-07-23 01:01:38 +00005650 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005651 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005652 // make sure we check the class hierarchy.
5653 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5654 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5655 E = lhsQID->qual_end(); I != E; ++I) {
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.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005659 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005660 return false;
5661 }
5662 }
5663 // If there are no qualifiers and no interface, we have an 'id'.
5664 return true;
5665 }
Mike Stump11289f42009-09-09 15:08:12 +00005666 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005667 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5668 E = lhsQID->qual_end(); I != E; ++I) {
5669 ObjCProtocolDecl *lhsProto = *I;
5670 bool match = false;
5671
5672 // when comparing an id<P> on lhs with a static type on rhs,
5673 // see if static class implements all of id's protocols, directly or
5674 // through its super class and categories.
5675 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5676 E = rhsOPT->qual_end(); J != E; ++J) {
5677 ObjCProtocolDecl *rhsProto = *J;
5678 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5679 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5680 match = true;
5681 break;
5682 }
5683 }
Mike Stump11289f42009-09-09 15:08:12 +00005684 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005685 // make sure we check the class hierarchy.
5686 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5687 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5688 E = lhsQID->qual_end(); I != E; ++I) {
5689 // when comparing an id<P> on lhs with a static type on rhs,
5690 // see if static class implements all of id's protocols, directly or
5691 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005692 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005693 match = true;
5694 break;
5695 }
5696 }
5697 }
5698 if (!match)
5699 return false;
5700 }
Mike Stump11289f42009-09-09 15:08:12 +00005701
Steve Naroff8e6aee52009-07-23 01:01:38 +00005702 return true;
5703 }
Mike Stump11289f42009-09-09 15:08:12 +00005704
Steve Naroff8e6aee52009-07-23 01:01:38 +00005705 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5706 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5707
Mike Stump11289f42009-09-09 15:08:12 +00005708 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005709 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005710 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005711 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5712 E = lhsOPT->qual_end(); I != E; ++I) {
5713 ObjCProtocolDecl *lhsProto = *I;
5714 bool match = false;
5715
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005716 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005717 // see if static class implements all of id's protocols, directly or
5718 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005719 // First, lhs protocols in the qualifier list must be found, direct
5720 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005721 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5722 E = rhsQID->qual_end(); J != E; ++J) {
5723 ObjCProtocolDecl *rhsProto = *J;
5724 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5725 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5726 match = true;
5727 break;
5728 }
5729 }
5730 if (!match)
5731 return false;
5732 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005733
5734 // Static class's protocols, or its super class or category protocols
5735 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5736 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5737 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5738 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5739 // This is rather dubious but matches gcc's behavior. If lhs has
5740 // no type qualifier and its class has no static protocol(s)
5741 // assume that it is mismatch.
5742 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5743 return false;
5744 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5745 LHSInheritedProtocols.begin(),
5746 E = LHSInheritedProtocols.end(); I != E; ++I) {
5747 bool match = false;
5748 ObjCProtocolDecl *lhsProto = (*I);
5749 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5750 E = rhsQID->qual_end(); J != E; ++J) {
5751 ObjCProtocolDecl *rhsProto = *J;
5752 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5753 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5754 match = true;
5755 break;
5756 }
5757 }
5758 if (!match)
5759 return false;
5760 }
5761 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005762 return true;
5763 }
5764 return false;
5765}
5766
Eli Friedman47f77112008-08-22 00:56:42 +00005767/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005768/// compatible for assignment from RHS to LHS. This handles validation of any
5769/// protocol qualifiers on the LHS or RHS.
5770///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005771bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5772 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005773 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5774 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5775
Steve Naroff1329fa02009-07-15 18:40:39 +00005776 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005777 if (LHS->isObjCUnqualifiedIdOrClass() ||
5778 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005779 return true;
5780
John McCall8b07ec22010-05-15 11:32:37 +00005781 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005782 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5783 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005784 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005785
5786 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5787 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5788 QualType(RHSOPT,0));
5789
John McCall8b07ec22010-05-15 11:32:37 +00005790 // If we have 2 user-defined types, fall into that path.
5791 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005792 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005793
Steve Naroff8e6aee52009-07-23 01:01:38 +00005794 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005795}
5796
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005797/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005798/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005799/// arguments in block literals. When passed as arguments, passing 'A*' where
5800/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5801/// not OK. For the return type, the opposite is not OK.
5802bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5803 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005804 const ObjCObjectPointerType *RHSOPT,
5805 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005806 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005807 return true;
5808
5809 if (LHSOPT->isObjCBuiltinType()) {
5810 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5811 }
5812
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005813 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005814 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5815 QualType(RHSOPT,0),
5816 false);
5817
5818 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5819 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5820 if (LHS && RHS) { // We have 2 user-defined types.
5821 if (LHS != RHS) {
5822 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005823 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005824 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005825 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005826 }
5827 else
5828 return true;
5829 }
5830 return false;
5831}
5832
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005833/// getIntersectionOfProtocols - This routine finds the intersection of set
5834/// of protocols inherited from two distinct objective-c pointer objects.
5835/// It is used to build composite qualifier list of the composite type of
5836/// the conditional expression involving two objective-c pointer objects.
5837static
5838void getIntersectionOfProtocols(ASTContext &Context,
5839 const ObjCObjectPointerType *LHSOPT,
5840 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005841 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005842
John McCall8b07ec22010-05-15 11:32:37 +00005843 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5844 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5845 assert(LHS->getInterface() && "LHS must have an interface base");
5846 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005847
5848 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5849 unsigned LHSNumProtocols = LHS->getNumProtocols();
5850 if (LHSNumProtocols > 0)
5851 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5852 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005853 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005854 Context.CollectInheritedProtocols(LHS->getInterface(),
5855 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005856 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5857 LHSInheritedProtocols.end());
5858 }
5859
5860 unsigned RHSNumProtocols = RHS->getNumProtocols();
5861 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005862 ObjCProtocolDecl **RHSProtocols =
5863 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005864 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5865 if (InheritedProtocolSet.count(RHSProtocols[i]))
5866 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005867 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005868 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005869 Context.CollectInheritedProtocols(RHS->getInterface(),
5870 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005871 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5872 RHSInheritedProtocols.begin(),
5873 E = RHSInheritedProtocols.end(); I != E; ++I)
5874 if (InheritedProtocolSet.count((*I)))
5875 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005876 }
5877}
5878
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005879/// areCommonBaseCompatible - Returns common base class of the two classes if
5880/// one found. Note that this is O'2 algorithm. But it will be called as the
5881/// last type comparison in a ?-exp of ObjC pointer types before a
5882/// warning is issued. So, its invokation is extremely rare.
5883QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005884 const ObjCObjectPointerType *Lptr,
5885 const ObjCObjectPointerType *Rptr) {
5886 const ObjCObjectType *LHS = Lptr->getObjectType();
5887 const ObjCObjectType *RHS = Rptr->getObjectType();
5888 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5889 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005890 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005891 return QualType();
5892
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005893 do {
John McCall8b07ec22010-05-15 11:32:37 +00005894 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005895 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005896 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005897 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5898
5899 QualType Result = QualType(LHS, 0);
5900 if (!Protocols.empty())
5901 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5902 Result = getObjCObjectPointerType(Result);
5903 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005904 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005905 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005906
5907 return QualType();
5908}
5909
John McCall8b07ec22010-05-15 11:32:37 +00005910bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5911 const ObjCObjectType *RHS) {
5912 assert(LHS->getInterface() && "LHS is not an interface type");
5913 assert(RHS->getInterface() && "RHS is not an interface type");
5914
Chris Lattner49af6a42008-04-07 06:51:04 +00005915 // Verify that the base decls are compatible: the RHS must be a subclass of
5916 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005917 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005918 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005919
Chris Lattner49af6a42008-04-07 06:51:04 +00005920 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5921 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005922 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005923 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005924
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005925 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5926 // more detailed analysis is required.
5927 if (RHS->getNumProtocols() == 0) {
5928 // OK, if LHS is a superclass of RHS *and*
5929 // this superclass is assignment compatible with LHS.
5930 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005931 bool IsSuperClass =
5932 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5933 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005934 // OK if conversion of LHS to SuperClass results in narrowing of types
5935 // ; i.e., SuperClass may implement at least one of the protocols
5936 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5937 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5938 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005939 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005940 // If super class has no protocols, it is not a match.
5941 if (SuperClassInheritedProtocols.empty())
5942 return false;
5943
5944 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5945 LHSPE = LHS->qual_end();
5946 LHSPI != LHSPE; LHSPI++) {
5947 bool SuperImplementsProtocol = false;
5948 ObjCProtocolDecl *LHSProto = (*LHSPI);
5949
5950 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5951 SuperClassInheritedProtocols.begin(),
5952 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5953 ObjCProtocolDecl *SuperClassProto = (*I);
5954 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5955 SuperImplementsProtocol = true;
5956 break;
5957 }
5958 }
5959 if (!SuperImplementsProtocol)
5960 return false;
5961 }
5962 return true;
5963 }
5964 return false;
5965 }
Mike Stump11289f42009-09-09 15:08:12 +00005966
John McCall8b07ec22010-05-15 11:32:37 +00005967 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5968 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005969 LHSPI != LHSPE; LHSPI++) {
5970 bool RHSImplementsProtocol = false;
5971
5972 // If the RHS doesn't implement the protocol on the left, the types
5973 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005974 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5975 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005976 RHSPI != RHSPE; RHSPI++) {
5977 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005978 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005979 break;
5980 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005981 }
5982 // FIXME: For better diagnostics, consider passing back the protocol name.
5983 if (!RHSImplementsProtocol)
5984 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005985 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005986 // The RHS implements all protocols listed on the LHS.
5987 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005988}
5989
Steve Naroffb7605152009-02-12 17:52:19 +00005990bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5991 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005992 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5993 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005994
Steve Naroff7cae42b2009-07-10 23:34:53 +00005995 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005996 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005997
5998 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5999 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006000}
6001
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006002bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6003 return canAssignObjCInterfaces(
6004 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6005 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6006}
6007
Mike Stump11289f42009-09-09 15:08:12 +00006008/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006009/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006010/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006011/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006012bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6013 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006014 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006015 return hasSameType(LHS, RHS);
6016
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006017 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006018}
6019
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006020bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006021 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006022}
6023
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006024bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6025 return !mergeTypes(LHS, RHS, true).isNull();
6026}
6027
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006028/// mergeTransparentUnionType - if T is a transparent union type and a member
6029/// of T is compatible with SubType, return the merged type, else return
6030/// QualType()
6031QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6032 bool OfBlockPointer,
6033 bool Unqualified) {
6034 if (const RecordType *UT = T->getAsUnionType()) {
6035 RecordDecl *UD = UT->getDecl();
6036 if (UD->hasAttr<TransparentUnionAttr>()) {
6037 for (RecordDecl::field_iterator it = UD->field_begin(),
6038 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006039 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006040 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6041 if (!MT.isNull())
6042 return MT;
6043 }
6044 }
6045 }
6046
6047 return QualType();
6048}
6049
6050/// mergeFunctionArgumentTypes - merge two types which appear as function
6051/// argument types
6052QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6053 bool OfBlockPointer,
6054 bool Unqualified) {
6055 // GNU extension: two types are compatible if they appear as a function
6056 // argument, one of the types is a transparent union type and the other
6057 // type is compatible with a union member
6058 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6059 Unqualified);
6060 if (!lmerge.isNull())
6061 return lmerge;
6062
6063 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6064 Unqualified);
6065 if (!rmerge.isNull())
6066 return rmerge;
6067
6068 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6069}
6070
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006071QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006072 bool OfBlockPointer,
6073 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006074 const FunctionType *lbase = lhs->getAs<FunctionType>();
6075 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006076 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6077 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006078 bool allLTypes = true;
6079 bool allRTypes = true;
6080
6081 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006082 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006083 if (OfBlockPointer) {
6084 QualType RHS = rbase->getResultType();
6085 QualType LHS = lbase->getResultType();
6086 bool UnqualifiedResult = Unqualified;
6087 if (!UnqualifiedResult)
6088 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006089 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006090 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006091 else
John McCall8c6b56f2010-12-15 01:06:38 +00006092 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6093 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006094 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006095
6096 if (Unqualified)
6097 retType = retType.getUnqualifiedType();
6098
6099 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6100 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6101 if (Unqualified) {
6102 LRetType = LRetType.getUnqualifiedType();
6103 RRetType = RRetType.getUnqualifiedType();
6104 }
6105
6106 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006107 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006108 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006109 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006110
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006111 // FIXME: double check this
6112 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6113 // rbase->getRegParmAttr() != 0 &&
6114 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006115 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6116 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006117
Douglas Gregor8c940862010-01-18 17:14:39 +00006118 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006119 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006120 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006121
John McCall8c6b56f2010-12-15 01:06:38 +00006122 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006123 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6124 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006125 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6126 return QualType();
6127
John McCall31168b02011-06-15 23:02:42 +00006128 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6129 return QualType();
6130
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006131 // functypes which return are preferred over those that do not.
6132 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6133 allLTypes = false;
6134 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6135 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006136 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6137 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006138
John McCall31168b02011-06-15 23:02:42 +00006139 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006140
Eli Friedman47f77112008-08-22 00:56:42 +00006141 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006142 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6143 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006144 unsigned lproto_nargs = lproto->getNumArgs();
6145 unsigned rproto_nargs = rproto->getNumArgs();
6146
6147 // Compatible functions must have the same number of arguments
6148 if (lproto_nargs != rproto_nargs)
6149 return QualType();
6150
6151 // Variadic and non-variadic functions aren't compatible
6152 if (lproto->isVariadic() != rproto->isVariadic())
6153 return QualType();
6154
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006155 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6156 return QualType();
6157
Fariborz Jahanian97676972011-09-28 21:52:05 +00006158 if (LangOpts.ObjCAutoRefCount &&
6159 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6160 return QualType();
6161
Eli Friedman47f77112008-08-22 00:56:42 +00006162 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006163 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006164 for (unsigned i = 0; i < lproto_nargs; i++) {
6165 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6166 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006167 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6168 OfBlockPointer,
6169 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006170 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006171
6172 if (Unqualified)
6173 argtype = argtype.getUnqualifiedType();
6174
Eli Friedman47f77112008-08-22 00:56:42 +00006175 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006176 if (Unqualified) {
6177 largtype = largtype.getUnqualifiedType();
6178 rargtype = rargtype.getUnqualifiedType();
6179 }
6180
Chris Lattner465fa322008-10-05 17:34:18 +00006181 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6182 allLTypes = false;
6183 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6184 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006185 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006186
Eli Friedman47f77112008-08-22 00:56:42 +00006187 if (allLTypes) return lhs;
6188 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006189
6190 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6191 EPI.ExtInfo = einfo;
6192 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006193 }
6194
6195 if (lproto) allRTypes = false;
6196 if (rproto) allLTypes = false;
6197
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006198 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006199 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006200 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006201 if (proto->isVariadic()) return QualType();
6202 // Check that the types are compatible with the types that
6203 // would result from default argument promotions (C99 6.7.5.3p15).
6204 // The only types actually affected are promotable integer
6205 // types and floats, which would be passed as a different
6206 // type depending on whether the prototype is visible.
6207 unsigned proto_nargs = proto->getNumArgs();
6208 for (unsigned i = 0; i < proto_nargs; ++i) {
6209 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006210
6211 // Look at the promotion type of enum types, since that is the type used
6212 // to pass enum values.
6213 if (const EnumType *Enum = argTy->getAs<EnumType>())
6214 argTy = Enum->getDecl()->getPromotionType();
6215
Eli Friedman47f77112008-08-22 00:56:42 +00006216 if (argTy->isPromotableIntegerType() ||
6217 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6218 return QualType();
6219 }
6220
6221 if (allLTypes) return lhs;
6222 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006223
6224 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6225 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006226 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006227 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006228 }
6229
6230 if (allLTypes) return lhs;
6231 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006232 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006233}
6234
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006235QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006236 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006237 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006238 // C++ [expr]: If an expression initially has the type "reference to T", the
6239 // type is adjusted to "T" prior to any further analysis, the expression
6240 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006241 // expression is an lvalue unless the reference is an rvalue reference and
6242 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006243 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6244 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006245
6246 if (Unqualified) {
6247 LHS = LHS.getUnqualifiedType();
6248 RHS = RHS.getUnqualifiedType();
6249 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006250
Eli Friedman47f77112008-08-22 00:56:42 +00006251 QualType LHSCan = getCanonicalType(LHS),
6252 RHSCan = getCanonicalType(RHS);
6253
6254 // If two types are identical, they are compatible.
6255 if (LHSCan == RHSCan)
6256 return LHS;
6257
John McCall8ccfcb52009-09-24 19:53:00 +00006258 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006259 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6260 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006261 if (LQuals != RQuals) {
6262 // If any of these qualifiers are different, we have a type
6263 // mismatch.
6264 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006265 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6266 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006267 return QualType();
6268
6269 // Exactly one GC qualifier difference is allowed: __strong is
6270 // okay if the other type has no GC qualifier but is an Objective
6271 // C object pointer (i.e. implicitly strong by default). We fix
6272 // this by pretending that the unqualified type was actually
6273 // qualified __strong.
6274 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6275 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6276 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6277
6278 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6279 return QualType();
6280
6281 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6282 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6283 }
6284 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6285 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6286 }
Eli Friedman47f77112008-08-22 00:56:42 +00006287 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006288 }
6289
6290 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006291
Eli Friedmandcca6332009-06-01 01:22:52 +00006292 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6293 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006294
Chris Lattnerfd652912008-01-14 05:45:46 +00006295 // We want to consider the two function types to be the same for these
6296 // comparisons, just force one to the other.
6297 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6298 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006299
6300 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006301 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6302 LHSClass = Type::ConstantArray;
6303 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6304 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006305
John McCall8b07ec22010-05-15 11:32:37 +00006306 // ObjCInterfaces are just specialized ObjCObjects.
6307 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6308 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6309
Nate Begemance4d7fc2008-04-18 23:10:10 +00006310 // Canonicalize ExtVector -> Vector.
6311 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6312 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006313
Chris Lattner95554662008-04-07 05:43:21 +00006314 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006315 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006316 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006317 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006318 // Compatibility is based on the underlying type, not the promotion
6319 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006320 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006321 QualType TINT = ETy->getDecl()->getIntegerType();
6322 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006323 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006324 }
John McCall9dd450b2009-09-21 23:43:11 +00006325 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006326 QualType TINT = ETy->getDecl()->getIntegerType();
6327 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006328 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006329 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006330 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006331 if (OfBlockPointer && !BlockReturnType) {
6332 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6333 return LHS;
6334 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6335 return RHS;
6336 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006337
Eli Friedman47f77112008-08-22 00:56:42 +00006338 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006339 }
Eli Friedman47f77112008-08-22 00:56:42 +00006340
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006341 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006342 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006343#define TYPE(Class, Base)
6344#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006345#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006346#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6347#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6348#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006349 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006350
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006351 case Type::LValueReference:
6352 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006353 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006354 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006355
John McCall8b07ec22010-05-15 11:32:37 +00006356 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006357 case Type::IncompleteArray:
6358 case Type::VariableArray:
6359 case Type::FunctionProto:
6360 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006361 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006362
Chris Lattnerfd652912008-01-14 05:45:46 +00006363 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006364 {
6365 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006366 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6367 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006368 if (Unqualified) {
6369 LHSPointee = LHSPointee.getUnqualifiedType();
6370 RHSPointee = RHSPointee.getUnqualifiedType();
6371 }
6372 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6373 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006374 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006375 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006376 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006377 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006378 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006379 return getPointerType(ResultType);
6380 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006381 case Type::BlockPointer:
6382 {
6383 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006384 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6385 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006386 if (Unqualified) {
6387 LHSPointee = LHSPointee.getUnqualifiedType();
6388 RHSPointee = RHSPointee.getUnqualifiedType();
6389 }
6390 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6391 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006392 if (ResultType.isNull()) return QualType();
6393 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6394 return LHS;
6395 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6396 return RHS;
6397 return getBlockPointerType(ResultType);
6398 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006399 case Type::Atomic:
6400 {
6401 // Merge two pointer types, while trying to preserve typedef info
6402 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6403 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6404 if (Unqualified) {
6405 LHSValue = LHSValue.getUnqualifiedType();
6406 RHSValue = RHSValue.getUnqualifiedType();
6407 }
6408 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6409 Unqualified);
6410 if (ResultType.isNull()) return QualType();
6411 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6412 return LHS;
6413 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6414 return RHS;
6415 return getAtomicType(ResultType);
6416 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006417 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006418 {
6419 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6420 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6421 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6422 return QualType();
6423
6424 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6425 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006426 if (Unqualified) {
6427 LHSElem = LHSElem.getUnqualifiedType();
6428 RHSElem = RHSElem.getUnqualifiedType();
6429 }
6430
6431 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006432 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006433 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6434 return LHS;
6435 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6436 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006437 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6438 ArrayType::ArraySizeModifier(), 0);
6439 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6440 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006441 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6442 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006443 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6444 return LHS;
6445 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6446 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006447 if (LVAT) {
6448 // FIXME: This isn't correct! But tricky to implement because
6449 // the array's size has to be the size of LHS, but the type
6450 // has to be different.
6451 return LHS;
6452 }
6453 if (RVAT) {
6454 // FIXME: This isn't correct! But tricky to implement because
6455 // the array's size has to be the size of RHS, but the type
6456 // has to be different.
6457 return RHS;
6458 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006459 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6460 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006461 return getIncompleteArrayType(ResultType,
6462 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006463 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006464 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006465 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006466 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006467 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006468 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006469 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006470 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006471 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006472 case Type::Complex:
6473 // Distinct complex types are incompatible.
6474 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006475 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006476 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006477 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6478 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006479 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006480 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006481 case Type::ObjCObject: {
6482 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006483 // FIXME: This should be type compatibility, e.g. whether
6484 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006485 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6486 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6487 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006488 return LHS;
6489
Eli Friedman47f77112008-08-22 00:56:42 +00006490 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006491 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006492 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006493 if (OfBlockPointer) {
6494 if (canAssignObjCInterfacesInBlockPointer(
6495 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006496 RHS->getAs<ObjCObjectPointerType>(),
6497 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006498 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006499 return QualType();
6500 }
John McCall9dd450b2009-09-21 23:43:11 +00006501 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6502 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006503 return LHS;
6504
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006505 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006506 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006507 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006508
David Blaikie8a40f702012-01-17 06:56:22 +00006509 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006510}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006511
Fariborz Jahanian97676972011-09-28 21:52:05 +00006512bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6513 const FunctionProtoType *FromFunctionType,
6514 const FunctionProtoType *ToFunctionType) {
6515 if (FromFunctionType->hasAnyConsumedArgs() !=
6516 ToFunctionType->hasAnyConsumedArgs())
6517 return false;
6518 FunctionProtoType::ExtProtoInfo FromEPI =
6519 FromFunctionType->getExtProtoInfo();
6520 FunctionProtoType::ExtProtoInfo ToEPI =
6521 ToFunctionType->getExtProtoInfo();
6522 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6523 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6524 ArgIdx != NumArgs; ++ArgIdx) {
6525 if (FromEPI.ConsumedArguments[ArgIdx] !=
6526 ToEPI.ConsumedArguments[ArgIdx])
6527 return false;
6528 }
6529 return true;
6530}
6531
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006532/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6533/// 'RHS' attributes and returns the merged version; including for function
6534/// return types.
6535QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6536 QualType LHSCan = getCanonicalType(LHS),
6537 RHSCan = getCanonicalType(RHS);
6538 // If two types are identical, they are compatible.
6539 if (LHSCan == RHSCan)
6540 return LHS;
6541 if (RHSCan->isFunctionType()) {
6542 if (!LHSCan->isFunctionType())
6543 return QualType();
6544 QualType OldReturnType =
6545 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6546 QualType NewReturnType =
6547 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6548 QualType ResReturnType =
6549 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6550 if (ResReturnType.isNull())
6551 return QualType();
6552 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6553 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6554 // In either case, use OldReturnType to build the new function type.
6555 const FunctionType *F = LHS->getAs<FunctionType>();
6556 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006557 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6558 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006559 QualType ResultType
6560 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006561 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006562 return ResultType;
6563 }
6564 }
6565 return QualType();
6566 }
6567
6568 // If the qualifiers are different, the types can still be merged.
6569 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6570 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6571 if (LQuals != RQuals) {
6572 // If any of these qualifiers are different, we have a type mismatch.
6573 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6574 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6575 return QualType();
6576
6577 // Exactly one GC qualifier difference is allowed: __strong is
6578 // okay if the other type has no GC qualifier but is an Objective
6579 // C object pointer (i.e. implicitly strong by default). We fix
6580 // this by pretending that the unqualified type was actually
6581 // qualified __strong.
6582 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6583 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6584 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6585
6586 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6587 return QualType();
6588
6589 if (GC_L == Qualifiers::Strong)
6590 return LHS;
6591 if (GC_R == Qualifiers::Strong)
6592 return RHS;
6593 return QualType();
6594 }
6595
6596 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6597 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6598 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6599 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6600 if (ResQT == LHSBaseQT)
6601 return LHS;
6602 if (ResQT == RHSBaseQT)
6603 return RHS;
6604 }
6605 return QualType();
6606}
6607
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006608//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006609// Integer Predicates
6610//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006611
Jay Foad39c79802011-01-12 09:06:06 +00006612unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006613 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006614 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006615 if (T->isBooleanType())
6616 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006617 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006618 return (unsigned)getTypeSize(T);
6619}
6620
6621QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006622 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006623
6624 // Turn <4 x signed int> -> <4 x unsigned int>
6625 if (const VectorType *VTy = T->getAs<VectorType>())
6626 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006627 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006628
6629 // For enums, we return the unsigned version of the base type.
6630 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006631 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006632
6633 const BuiltinType *BTy = T->getAs<BuiltinType>();
6634 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006635 switch (BTy->getKind()) {
6636 case BuiltinType::Char_S:
6637 case BuiltinType::SChar:
6638 return UnsignedCharTy;
6639 case BuiltinType::Short:
6640 return UnsignedShortTy;
6641 case BuiltinType::Int:
6642 return UnsignedIntTy;
6643 case BuiltinType::Long:
6644 return UnsignedLongTy;
6645 case BuiltinType::LongLong:
6646 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006647 case BuiltinType::Int128:
6648 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006649 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006650 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006651 }
6652}
6653
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006654ASTMutationListener::~ASTMutationListener() { }
6655
Chris Lattnerecd79c62009-06-14 00:45:47 +00006656
6657//===----------------------------------------------------------------------===//
6658// Builtin Type Computation
6659//===----------------------------------------------------------------------===//
6660
6661/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006662/// pointer over the consumed characters. This returns the resultant type. If
6663/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6664/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6665/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006666///
6667/// RequiresICE is filled in on return to indicate whether the value is required
6668/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006669static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006670 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006671 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006672 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006673 // Modifiers.
6674 int HowLong = 0;
6675 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006676 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006677
Chris Lattnerdc226c22010-10-01 22:42:38 +00006678 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006679 bool Done = false;
6680 while (!Done) {
6681 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006682 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006683 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006684 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006685 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006686 case 'S':
6687 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6688 assert(!Signed && "Can't use 'S' modifier multiple times!");
6689 Signed = true;
6690 break;
6691 case 'U':
6692 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6693 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6694 Unsigned = true;
6695 break;
6696 case 'L':
6697 assert(HowLong <= 2 && "Can't have LLLL modifier");
6698 ++HowLong;
6699 break;
6700 }
6701 }
6702
6703 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006704
Chris Lattnerecd79c62009-06-14 00:45:47 +00006705 // Read the base type.
6706 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006707 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006708 case 'v':
6709 assert(HowLong == 0 && !Signed && !Unsigned &&
6710 "Bad modifiers used with 'v'!");
6711 Type = Context.VoidTy;
6712 break;
6713 case 'f':
6714 assert(HowLong == 0 && !Signed && !Unsigned &&
6715 "Bad modifiers used with 'f'!");
6716 Type = Context.FloatTy;
6717 break;
6718 case 'd':
6719 assert(HowLong < 2 && !Signed && !Unsigned &&
6720 "Bad modifiers used with 'd'!");
6721 if (HowLong)
6722 Type = Context.LongDoubleTy;
6723 else
6724 Type = Context.DoubleTy;
6725 break;
6726 case 's':
6727 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6728 if (Unsigned)
6729 Type = Context.UnsignedShortTy;
6730 else
6731 Type = Context.ShortTy;
6732 break;
6733 case 'i':
6734 if (HowLong == 3)
6735 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6736 else if (HowLong == 2)
6737 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6738 else if (HowLong == 1)
6739 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6740 else
6741 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6742 break;
6743 case 'c':
6744 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6745 if (Signed)
6746 Type = Context.SignedCharTy;
6747 else if (Unsigned)
6748 Type = Context.UnsignedCharTy;
6749 else
6750 Type = Context.CharTy;
6751 break;
6752 case 'b': // boolean
6753 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6754 Type = Context.BoolTy;
6755 break;
6756 case 'z': // size_t.
6757 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6758 Type = Context.getSizeType();
6759 break;
6760 case 'F':
6761 Type = Context.getCFConstantStringType();
6762 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006763 case 'G':
6764 Type = Context.getObjCIdType();
6765 break;
6766 case 'H':
6767 Type = Context.getObjCSelType();
6768 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006769 case 'a':
6770 Type = Context.getBuiltinVaListType();
6771 assert(!Type.isNull() && "builtin va list type not initialized!");
6772 break;
6773 case 'A':
6774 // This is a "reference" to a va_list; however, what exactly
6775 // this means depends on how va_list is defined. There are two
6776 // different kinds of va_list: ones passed by value, and ones
6777 // passed by reference. An example of a by-value va_list is
6778 // x86, where va_list is a char*. An example of by-ref va_list
6779 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6780 // we want this argument to be a char*&; for x86-64, we want
6781 // it to be a __va_list_tag*.
6782 Type = Context.getBuiltinVaListType();
6783 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006784 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006785 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006786 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006787 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006788 break;
6789 case 'V': {
6790 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006791 unsigned NumElements = strtoul(Str, &End, 10);
6792 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006793 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006794
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006795 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6796 RequiresICE, false);
6797 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006798
6799 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006800 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006801 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006802 break;
6803 }
Douglas Gregorfed66992012-06-07 18:08:25 +00006804 case 'E': {
6805 char *End;
6806
6807 unsigned NumElements = strtoul(Str, &End, 10);
6808 assert(End != Str && "Missing vector size");
6809
6810 Str = End;
6811
6812 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6813 false);
6814 Type = Context.getExtVectorType(ElementType, NumElements);
6815 break;
6816 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006817 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006818 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6819 false);
6820 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006821 Type = Context.getComplexType(ElementType);
6822 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006823 }
6824 case 'Y' : {
6825 Type = Context.getPointerDiffType();
6826 break;
6827 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006828 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006829 Type = Context.getFILEType();
6830 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006831 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006832 return QualType();
6833 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006834 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006835 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006836 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006837 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006838 else
6839 Type = Context.getjmp_bufType();
6840
Mike Stump2adb4da2009-07-28 23:47:15 +00006841 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006842 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006843 return QualType();
6844 }
6845 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006846 case 'K':
6847 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6848 Type = Context.getucontext_tType();
6849
6850 if (Type.isNull()) {
6851 Error = ASTContext::GE_Missing_ucontext;
6852 return QualType();
6853 }
6854 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006855 }
Mike Stump11289f42009-09-09 15:08:12 +00006856
Chris Lattnerdc226c22010-10-01 22:42:38 +00006857 // If there are modifiers and if we're allowed to parse them, go for it.
6858 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006859 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006860 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006861 default: Done = true; --Str; break;
6862 case '*':
6863 case '&': {
6864 // Both pointers and references can have their pointee types
6865 // qualified with an address space.
6866 char *End;
6867 unsigned AddrSpace = strtoul(Str, &End, 10);
6868 if (End != Str && AddrSpace != 0) {
6869 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6870 Str = End;
6871 }
6872 if (c == '*')
6873 Type = Context.getPointerType(Type);
6874 else
6875 Type = Context.getLValueReferenceType(Type);
6876 break;
6877 }
6878 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6879 case 'C':
6880 Type = Type.withConst();
6881 break;
6882 case 'D':
6883 Type = Context.getVolatileType(Type);
6884 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006885 case 'R':
6886 Type = Type.withRestrict();
6887 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006888 }
6889 }
Chris Lattner84733392010-10-01 07:13:18 +00006890
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006891 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006892 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006893
Chris Lattnerecd79c62009-06-14 00:45:47 +00006894 return Type;
6895}
6896
6897/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006898QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006899 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006900 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006901 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006902
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006903 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006904
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006905 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006906 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006907 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6908 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006909 if (Error != GE_None)
6910 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006911
6912 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6913
Chris Lattnerecd79c62009-06-14 00:45:47 +00006914 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006915 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006916 if (Error != GE_None)
6917 return QualType();
6918
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006919 // If this argument is required to be an IntegerConstantExpression and the
6920 // caller cares, fill in the bitmask we return.
6921 if (RequiresICE && IntegerConstantArgs)
6922 *IntegerConstantArgs |= 1 << ArgTypes.size();
6923
Chris Lattnerecd79c62009-06-14 00:45:47 +00006924 // Do array -> pointer decay. The builtin should use the decayed type.
6925 if (Ty->isArrayType())
6926 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006927
Chris Lattnerecd79c62009-06-14 00:45:47 +00006928 ArgTypes.push_back(Ty);
6929 }
6930
6931 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6932 "'.' should only occur at end of builtin type list!");
6933
John McCall991eb4b2010-12-21 00:44:39 +00006934 FunctionType::ExtInfo EI;
6935 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6936
6937 bool Variadic = (TypeStr[0] == '.');
6938
6939 // We really shouldn't be making a no-proto type here, especially in C++.
6940 if (ArgTypes.empty() && Variadic)
6941 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006942
John McCalldb40c7f2010-12-14 08:05:40 +00006943 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006944 EPI.ExtInfo = EI;
6945 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006946
6947 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006948}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006949
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006950GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6951 GVALinkage External = GVA_StrongExternal;
6952
6953 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006954 switch (L) {
6955 case NoLinkage:
6956 case InternalLinkage:
6957 case UniqueExternalLinkage:
6958 return GVA_Internal;
6959
6960 case ExternalLinkage:
6961 switch (FD->getTemplateSpecializationKind()) {
6962 case TSK_Undeclared:
6963 case TSK_ExplicitSpecialization:
6964 External = GVA_StrongExternal;
6965 break;
6966
6967 case TSK_ExplicitInstantiationDefinition:
6968 return GVA_ExplicitTemplateInstantiation;
6969
6970 case TSK_ExplicitInstantiationDeclaration:
6971 case TSK_ImplicitInstantiation:
6972 External = GVA_TemplateInstantiation;
6973 break;
6974 }
6975 }
6976
6977 if (!FD->isInlined())
6978 return External;
6979
David Blaikiebbafb8a2012-03-11 07:00:24 +00006980 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006981 // GNU or C99 inline semantics. Determine whether this symbol should be
6982 // externally visible.
6983 if (FD->isInlineDefinitionExternallyVisible())
6984 return External;
6985
6986 // C99 inline semantics, where the symbol is not externally visible.
6987 return GVA_C99Inline;
6988 }
6989
6990 // C++0x [temp.explicit]p9:
6991 // [ Note: The intent is that an inline function that is the subject of
6992 // an explicit instantiation declaration will still be implicitly
6993 // instantiated when used so that the body can be considered for
6994 // inlining, but that no out-of-line copy of the inline function would be
6995 // generated in the translation unit. -- end note ]
6996 if (FD->getTemplateSpecializationKind()
6997 == TSK_ExplicitInstantiationDeclaration)
6998 return GVA_C99Inline;
6999
7000 return GVA_CXXInline;
7001}
7002
7003GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7004 // If this is a static data member, compute the kind of template
7005 // specialization. Otherwise, this variable is not part of a
7006 // template.
7007 TemplateSpecializationKind TSK = TSK_Undeclared;
7008 if (VD->isStaticDataMember())
7009 TSK = VD->getTemplateSpecializationKind();
7010
7011 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007012 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007013 VD->getType()->getLinkage() == UniqueExternalLinkage)
7014 L = UniqueExternalLinkage;
7015
7016 switch (L) {
7017 case NoLinkage:
7018 case InternalLinkage:
7019 case UniqueExternalLinkage:
7020 return GVA_Internal;
7021
7022 case ExternalLinkage:
7023 switch (TSK) {
7024 case TSK_Undeclared:
7025 case TSK_ExplicitSpecialization:
7026 return GVA_StrongExternal;
7027
7028 case TSK_ExplicitInstantiationDeclaration:
7029 llvm_unreachable("Variable should not be instantiated");
7030 // Fall through to treat this like any other instantiation.
7031
7032 case TSK_ExplicitInstantiationDefinition:
7033 return GVA_ExplicitTemplateInstantiation;
7034
7035 case TSK_ImplicitInstantiation:
7036 return GVA_TemplateInstantiation;
7037 }
7038 }
7039
David Blaikie8a40f702012-01-17 06:56:22 +00007040 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007041}
7042
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007043bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007044 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7045 if (!VD->isFileVarDecl())
7046 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007047 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007048 return false;
7049
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007050 // Weak references don't produce any output by themselves.
7051 if (D->hasAttr<WeakRefAttr>())
7052 return false;
7053
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007054 // Aliases and used decls are required.
7055 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7056 return true;
7057
7058 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7059 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007060 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007061 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007062
7063 // Constructors and destructors are required.
7064 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7065 return true;
7066
7067 // The key function for a class is required.
7068 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7069 const CXXRecordDecl *RD = MD->getParent();
7070 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7071 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7072 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7073 return true;
7074 }
7075 }
7076
7077 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7078
7079 // static, static inline, always_inline, and extern inline functions can
7080 // always be deferred. Normal inline functions can be deferred in C99/C++.
7081 // Implicit template instantiations can also be deferred in C++.
7082 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007083 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007084 return false;
7085 return true;
7086 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007087
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007088 const VarDecl *VD = cast<VarDecl>(D);
7089 assert(VD->isFileVarDecl() && "Expected file scoped var");
7090
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007091 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7092 return false;
7093
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007094 // Structs that have non-trivial constructors or destructors are required.
7095
7096 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007097 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007098 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7099 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007100 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7101 RD->hasTrivialCopyConstructor() &&
7102 RD->hasTrivialMoveConstructor() &&
7103 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007104 return true;
7105 }
7106 }
7107
7108 GVALinkage L = GetGVALinkageForVariable(VD);
7109 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7110 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7111 return false;
7112 }
7113
7114 return true;
7115}
Charles Davis53c59df2010-08-16 03:33:14 +00007116
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007117CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007118 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007119 return ABI->getDefaultMethodCallConv(isVariadic);
7120}
7121
7122CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7123 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7124 return CC_Default;
7125 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007126}
7127
Jay Foad39c79802011-01-12 09:06:06 +00007128bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007129 // Pass through to the C++ ABI object
7130 return ABI->isNearlyEmpty(RD);
7131}
7132
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007133MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007134 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007135 case CXXABI_ARM:
7136 case CXXABI_Itanium:
7137 return createItaniumMangleContext(*this, getDiagnostics());
7138 case CXXABI_Microsoft:
7139 return createMicrosoftMangleContext(*this, getDiagnostics());
7140 }
David Blaikie83d382b2011-09-23 05:06:16 +00007141 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007142}
7143
Charles Davis53c59df2010-08-16 03:33:14 +00007144CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007145
7146size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007147 return ASTRecordLayouts.getMemorySize()
7148 + llvm::capacity_in_bytes(ObjCLayouts)
7149 + llvm::capacity_in_bytes(KeyFunctions)
7150 + llvm::capacity_in_bytes(ObjCImpls)
7151 + llvm::capacity_in_bytes(BlockVarCopyInits)
7152 + llvm::capacity_in_bytes(DeclAttrs)
7153 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7154 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7155 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7156 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7157 + llvm::capacity_in_bytes(OverriddenMethods)
7158 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007159 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007160 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007161}
Ted Kremenek540017e2011-10-06 05:00:56 +00007162
Douglas Gregor63798542012-02-20 19:44:39 +00007163unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7164 CXXRecordDecl *Lambda = CallOperator->getParent();
7165 return LambdaMangleContexts[Lambda->getDeclContext()]
7166 .getManglingNumber(CallOperator);
7167}
7168
7169
Ted Kremenek540017e2011-10-06 05:00:56 +00007170void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7171 ParamIndices[D] = index;
7172}
7173
7174unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7175 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7176 assert(I != ParamIndices.end() &&
7177 "ParmIndices lacks entry set by ParmVarDecl");
7178 return I->second;
7179}