blob: 46a4d87f9a9b89a3ee5c41dc84ba4bf21d827834 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +000016#include "clang/AST/CommentLexer.h"
17#include "clang/AST/CommentSema.h"
18#include "clang/AST/CommentParser.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000019#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000021#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000022#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000023#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000024#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000025#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +000026#include "clang/AST/ASTMutationListener.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000027#include "clang/AST/RecordLayout.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000029#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000030#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000032#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000033#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000034#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000035#include "llvm/Support/raw_ostream.h"
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +000036#include "llvm/Support/Capacity.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000037#include "CXXABI.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000038#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000039
Reid Spencer5f016e22007-07-11 17:01:13 +000040using namespace clang;
41
Douglas Gregor18274032010-07-03 00:47:00 +000042unsigned ASTContext::NumImplicitDefaultConstructors;
43unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000044unsigned ASTContext::NumImplicitCopyConstructors;
45unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveConstructors;
47unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000048unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000052unsigned ASTContext::NumImplicitDestructors;
53unsigned ASTContext::NumImplicitDestructorsDeclared;
54
Reid Spencer5f016e22007-07-11 17:01:13 +000055enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000056 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000057};
58
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000059RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000060 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
63 }
64
65 assert(D);
66
Dmitri Gribenkoc3fee352012-06-28 16:19:39 +000067 // User can not attach documentation to implicit declarations.
68 if (D->isImplicit())
69 return NULL;
70
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000071 // TODO: handle comments for function parameters properly.
72 if (isa<ParmVarDecl>(D))
73 return NULL;
74
Dmitri Gribenko811c8202012-07-06 18:19:34 +000075 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaa0cd852012-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 Gribenkoabd56c82012-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 Gribenkoaa0cd852012-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 Gribenkoaa0cd852012-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 Gribenkoa444f182012-07-17 22:01:09 +0000100 ArrayRef<RawComment *>::iterator Comment;
101 {
102 // When searching for comments during parsing, the comment we are looking
103 // for is usually among the last two comments we parsed -- check them
104 // first.
105 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
106 BeforeThanCompare<RawComment> Compare(SourceMgr);
107 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
108 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
109 if (!Found && RawComments.size() >= 2) {
110 MaybeBeforeDecl--;
111 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
112 }
113
114 if (Found) {
115 Comment = MaybeBeforeDecl + 1;
116 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
117 &CommentAtDeclLoc, Compare));
118 } else {
119 // Slow path.
120 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
121 &CommentAtDeclLoc, Compare);
122 }
123 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000124
125 // Decompose the location for the declaration and find the beginning of the
126 // file buffer.
127 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
128
129 // First check whether we have a trailing comment.
130 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000131 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko9c006762012-07-06 23:27:33 +0000132 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000133 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000134 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000135 // Check that Doxygen trailing comment comes after the declaration, starts
136 // on the same line and in the same file as the declaration.
137 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
138 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
139 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
140 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000141 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000142 }
143 }
144
145 // The comment just after the declaration was not a trailing comment.
146 // Let's look at the previous comment.
147 if (Comment == RawComments.begin())
148 return NULL;
149 --Comment;
150
151 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000152 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000153 return NULL;
154
155 // Decompose the end of the comment.
156 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000157 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000158
159 // If the comment and the declaration aren't in the same file, then they
160 // aren't related.
161 if (DeclLocDecomp.first != CommentEndDecomp.first)
162 return NULL;
163
164 // Get the corresponding buffer.
165 bool Invalid = false;
166 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
167 &Invalid).data();
168 if (Invalid)
169 return NULL;
170
171 // Extract text between the comment and declaration.
172 StringRef Text(Buffer + CommentEndDecomp.second,
173 DeclLocDecomp.second - CommentEndDecomp.second);
174
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000175 // There should be no other declarations or preprocessor directives between
176 // comment and declaration.
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000177 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000178 return NULL;
179
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000180 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000181}
182
183const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const {
184 // Check whether we have cached a comment string for this declaration
185 // already.
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000186 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000187 = DeclComments.find(D);
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000188 if (Pos != DeclComments.end()) {
189 RawAndParsedComment C = Pos->second;
190 return C.first;
191 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000192
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +0000193 RawComment *RC = getRawCommentForDeclNoCache(D);
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000194 // If we found a comment, it should be a documentation comment.
195 assert(!RC || RC->isDocumentation());
Dmitri Gribenko9bf997e2012-07-06 15:40:08 +0000196 DeclComments[D] =
197 RawAndParsedComment(RC, static_cast<comments::FullComment *>(NULL));
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +0000198 if (RC)
199 RC->setAttached();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000200 return RC;
201}
202
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000203comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const {
204 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
205 = DeclComments.find(D);
206 const RawComment *RC;
207 if (Pos != DeclComments.end()) {
208 RawAndParsedComment C = Pos->second;
209 if (comments::FullComment *FC = C.second)
210 return FC;
211 RC = C.first;
212 } else
213 RC = getRawCommentForDecl(D);
214
215 if (!RC)
216 return NULL;
217
218 const StringRef RawText = RC->getRawText(SourceMgr);
Dmitri Gribenko477a9f52012-07-27 20:37:06 +0000219 comments::Lexer L(getAllocator(),
220 RC->getSourceRange().getBegin(), comments::CommentOptions(),
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000221 RawText.begin(), RawText.end());
222
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +0000223 comments::Sema S(getAllocator(), getSourceManager(), getDiagnostics());
224 S.setDecl(D);
225 comments::Parser P(L, S, getAllocator(), getSourceManager(),
226 getDiagnostics());
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000227
228 comments::FullComment *FC = P.parseFullComment();
229 DeclComments[D].second = FC;
230 return FC;
231}
232
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000233void
234ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
235 TemplateTemplateParmDecl *Parm) {
236 ID.AddInteger(Parm->getDepth());
237 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000238 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000239
240 TemplateParameterList *Params = Parm->getTemplateParameters();
241 ID.AddInteger(Params->size());
242 for (TemplateParameterList::const_iterator P = Params->begin(),
243 PEnd = Params->end();
244 P != PEnd; ++P) {
245 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
246 ID.AddInteger(0);
247 ID.AddBoolean(TTP->isParameterPack());
248 continue;
249 }
250
251 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
252 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000253 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000254 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000255 if (NTTP->isExpandedParameterPack()) {
256 ID.AddBoolean(true);
257 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000258 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
259 QualType T = NTTP->getExpansionType(I);
260 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
261 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000262 } else
263 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000264 continue;
265 }
266
267 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
268 ID.AddInteger(2);
269 Profile(ID, TTP);
270 }
271}
272
273TemplateTemplateParmDecl *
274ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000275 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000276 // Check if we already have a canonical template template parameter.
277 llvm::FoldingSetNodeID ID;
278 CanonicalTemplateTemplateParm::Profile(ID, TTP);
279 void *InsertPos = 0;
280 CanonicalTemplateTemplateParm *Canonical
281 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
282 if (Canonical)
283 return Canonical->getParam();
284
285 // Build a canonical template parameter list.
286 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000287 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000288 CanonParams.reserve(Params->size());
289 for (TemplateParameterList::const_iterator P = Params->begin(),
290 PEnd = Params->end();
291 P != PEnd; ++P) {
292 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
293 CanonParams.push_back(
294 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000295 SourceLocation(),
296 SourceLocation(),
297 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000298 TTP->getIndex(), 0, false,
299 TTP->isParameterPack()));
300 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000301 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
302 QualType T = getCanonicalType(NTTP->getType());
303 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
304 NonTypeTemplateParmDecl *Param;
305 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000306 SmallVector<QualType, 2> ExpandedTypes;
307 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000308 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
309 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
310 ExpandedTInfos.push_back(
311 getTrivialTypeSourceInfo(ExpandedTypes.back()));
312 }
313
314 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000315 SourceLocation(),
316 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000317 NTTP->getDepth(),
318 NTTP->getPosition(), 0,
319 T,
320 TInfo,
321 ExpandedTypes.data(),
322 ExpandedTypes.size(),
323 ExpandedTInfos.data());
324 } else {
325 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000326 SourceLocation(),
327 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000328 NTTP->getDepth(),
329 NTTP->getPosition(), 0,
330 T,
331 NTTP->isParameterPack(),
332 TInfo);
333 }
334 CanonParams.push_back(Param);
335
336 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000337 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
338 cast<TemplateTemplateParmDecl>(*P)));
339 }
340
341 TemplateTemplateParmDecl *CanonTTP
342 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
343 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000344 TTP->getPosition(),
345 TTP->isParameterPack(),
346 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000347 TemplateParameterList::Create(*this, SourceLocation(),
348 SourceLocation(),
349 CanonParams.data(),
350 CanonParams.size(),
351 SourceLocation()));
352
353 // Get the new insert position for the node we care about.
354 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
355 assert(Canonical == 0 && "Shouldn't be in the map!");
356 (void)Canonical;
357
358 // Create the canonical template template parameter entry.
359 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
360 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
361 return CanonTTP;
362}
363
Charles Davis071cc7d2010-08-16 03:33:14 +0000364CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000365 if (!LangOpts.CPlusPlus) return 0;
366
Charles Davis20cf7172010-08-19 02:18:14 +0000367 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000368 case CXXABI_ARM:
369 return CreateARMCXXABI(*this);
370 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000371 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000372 case CXXABI_Microsoft:
373 return CreateMicrosoftCXXABI(*this);
374 }
David Blaikie7530c032012-01-17 06:56:22 +0000375 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000376}
377
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000378static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000379 const LangOptions &LOpts) {
380 if (LOpts.FakeAddressSpaceMap) {
381 // The fake address space map must have a distinct entry for each
382 // language-specific address space.
383 static const unsigned FakeAddrSpaceMap[] = {
384 1, // opencl_global
385 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000386 3, // opencl_constant
387 4, // cuda_device
388 5, // cuda_constant
389 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000390 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000391 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000392 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000393 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000394 }
395}
396
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000397ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000398 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000399 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000400 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000401 unsigned size_reserve,
402 bool DelayInitialization)
403 : FunctionProtoTypes(this_()),
404 TemplateSpecializationTypes(this_()),
405 DependentTemplateSpecializationTypes(this_()),
406 SubstTemplateTemplateParmPacks(this_()),
407 GlobalNestedNameSpecifier(0),
408 Int128Decl(0), UInt128Decl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000409 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000410 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000411 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000412 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000413 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
414 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
415 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000416 NullTypeSourceInfo(QualType()),
417 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000418 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000419 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000420 Idents(idents), Selectors(sels),
421 BuiltinInfo(builtins),
422 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000423 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000424 Comments(SM), CommentsLoaded(false),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000425 LastSDM(0, 0),
426 UniqueBlockByRefTypeID(0)
427{
Mike Stump1eb44332009-09-09 15:08:12 +0000428 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000429 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000430
431 if (!DelayInitialization) {
432 assert(t && "No target supplied for ASTContext initialization");
433 InitBuiltinTypes(*t);
434 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000435}
436
Reid Spencer5f016e22007-07-11 17:01:13 +0000437ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000438 // Release the DenseMaps associated with DeclContext objects.
439 // FIXME: Is this the ideal solution?
440 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000441
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000442 // Call all of the deallocation functions.
443 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
444 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000445
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000446 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000447 // because they can contain DenseMaps.
448 for (llvm::DenseMap<const ObjCContainerDecl*,
449 const ASTRecordLayout*>::iterator
450 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
451 // Increment in loop to prevent using deallocated memory.
452 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
453 R->Destroy(*this);
454
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000455 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
456 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
457 // Increment in loop to prevent using deallocated memory.
458 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
459 R->Destroy(*this);
460 }
Douglas Gregor63200642010-08-30 16:49:28 +0000461
462 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
463 AEnd = DeclAttrs.end();
464 A != AEnd; ++A)
465 A->second->~AttrVec();
466}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000467
Douglas Gregor00545312010-05-23 18:26:36 +0000468void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
469 Deallocations.push_back(std::make_pair(Callback, Data));
470}
471
Mike Stump1eb44332009-09-09 15:08:12 +0000472void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000473ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000474 ExternalSource.reset(Source.take());
475}
476
Reid Spencer5f016e22007-07-11 17:01:13 +0000477void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000478 llvm::errs() << "\n*** AST Context Stats:\n";
479 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000480
Douglas Gregordbe833d2009-05-26 14:40:08 +0000481 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000482#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000483#define ABSTRACT_TYPE(Name, Parent)
484#include "clang/AST/TypeNodes.def"
485 0 // Extra
486 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000487
Reid Spencer5f016e22007-07-11 17:01:13 +0000488 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
489 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000490 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000491 }
492
Douglas Gregordbe833d2009-05-26 14:40:08 +0000493 unsigned Idx = 0;
494 unsigned TotalBytes = 0;
495#define TYPE(Name, Parent) \
496 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000497 llvm::errs() << " " << counts[Idx] << " " << #Name \
498 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000499 TotalBytes += counts[Idx] * sizeof(Name##Type); \
500 ++Idx;
501#define ABSTRACT_TYPE(Name, Parent)
502#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Chandler Carruthcd92a652011-07-04 05:32:14 +0000504 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
505
Douglas Gregor4923aa22010-07-02 20:37:36 +0000506 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000507 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
508 << NumImplicitDefaultConstructors
509 << " implicit default constructors created\n";
510 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
511 << NumImplicitCopyConstructors
512 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000513 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000514 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
515 << NumImplicitMoveConstructors
516 << " implicit move constructors created\n";
517 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
518 << NumImplicitCopyAssignmentOperators
519 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000520 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000521 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
522 << NumImplicitMoveAssignmentOperators
523 << " implicit move assignment operators created\n";
524 llvm::errs() << NumImplicitDestructorsDeclared << "/"
525 << NumImplicitDestructors
526 << " implicit destructors created\n";
527
Douglas Gregor2cf26342009-04-09 22:27:44 +0000528 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000529 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000530 ExternalSource->PrintStats();
531 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000532
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000533 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000534}
535
Douglas Gregor772eeae2011-08-12 06:49:56 +0000536TypedefDecl *ASTContext::getInt128Decl() const {
537 if (!Int128Decl) {
538 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
539 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
540 getTranslationUnitDecl(),
541 SourceLocation(),
542 SourceLocation(),
543 &Idents.get("__int128_t"),
544 TInfo);
545 }
546
547 return Int128Decl;
548}
549
550TypedefDecl *ASTContext::getUInt128Decl() const {
551 if (!UInt128Decl) {
552 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
553 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
554 getTranslationUnitDecl(),
555 SourceLocation(),
556 SourceLocation(),
557 &Idents.get("__uint128_t"),
558 TInfo);
559 }
560
561 return UInt128Decl;
562}
Reid Spencer5f016e22007-07-11 17:01:13 +0000563
John McCalle27ec8a2009-10-23 23:03:21 +0000564void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000565 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000566 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000567 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000568}
569
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000570void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
571 assert((!this->Target || this->Target == &Target) &&
572 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000573 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000575 this->Target = &Target;
576
577 ABI.reset(createCXXABI(Target));
578 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
579
Reid Spencer5f016e22007-07-11 17:01:13 +0000580 // C99 6.2.5p19.
581 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000582
Reid Spencer5f016e22007-07-11 17:01:13 +0000583 // C99 6.2.5p2.
584 InitBuiltinType(BoolTy, BuiltinType::Bool);
585 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000586 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000587 InitBuiltinType(CharTy, BuiltinType::Char_S);
588 else
589 InitBuiltinType(CharTy, BuiltinType::Char_U);
590 // C99 6.2.5p4.
591 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
592 InitBuiltinType(ShortTy, BuiltinType::Short);
593 InitBuiltinType(IntTy, BuiltinType::Int);
594 InitBuiltinType(LongTy, BuiltinType::Long);
595 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Reid Spencer5f016e22007-07-11 17:01:13 +0000597 // C99 6.2.5p6.
598 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
599 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
600 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
601 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
602 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Reid Spencer5f016e22007-07-11 17:01:13 +0000604 // C99 6.2.5p10.
605 InitBuiltinType(FloatTy, BuiltinType::Float);
606 InitBuiltinType(DoubleTy, BuiltinType::Double);
607 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000608
Chris Lattner2df9ced2009-04-30 02:43:43 +0000609 // GNU extension, 128-bit integers.
610 InitBuiltinType(Int128Ty, BuiltinType::Int128);
611 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
612
Chris Lattner3f59c972010-12-25 23:25:43 +0000613 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000614 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000615 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
616 else // -fshort-wchar makes wchar_t be unsigned.
617 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
618 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000619 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000620
James Molloy392da482012-05-04 10:55:22 +0000621 WIntTy = getFromTargetType(Target.getWIntType());
622
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000623 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
624 InitBuiltinType(Char16Ty, BuiltinType::Char16);
625 else // C99
626 Char16Ty = getFromTargetType(Target.getChar16Type());
627
628 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
629 InitBuiltinType(Char32Ty, BuiltinType::Char32);
630 else // C99
631 Char32Ty = getFromTargetType(Target.getChar32Type());
632
Douglas Gregor898574e2008-12-05 23:32:09 +0000633 // Placeholder type for type-dependent expressions whose type is
634 // completely unknown. No code should ever check a type against
635 // DependentTy and users should never see it; however, it is here to
636 // help diagnose failures to properly check for type-dependent
637 // expressions.
638 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000639
John McCall2a984ca2010-10-12 00:20:44 +0000640 // Placeholder type for functions.
641 InitBuiltinType(OverloadTy, BuiltinType::Overload);
642
John McCall864c0412011-04-26 20:42:42 +0000643 // Placeholder type for bound members.
644 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
645
John McCall3c3b7f92011-10-25 17:37:35 +0000646 // Placeholder type for pseudo-objects.
647 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
648
John McCall1de4d4e2011-04-07 08:22:57 +0000649 // "any" type; useful for debugger-like clients.
650 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
651
John McCall0ddaeb92011-10-17 18:09:15 +0000652 // Placeholder type for unbridged ARC casts.
653 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
654
Reid Spencer5f016e22007-07-11 17:01:13 +0000655 // C99 6.2.5p11.
656 FloatComplexTy = getComplexType(FloatTy);
657 DoubleComplexTy = getComplexType(DoubleTy);
658 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000659
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000660 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000661 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
662 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000663 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000664
665 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000666 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
667 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000668
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000669 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000670
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000671 // void * type
672 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000673
674 // nullptr type (C++0x 2.14.7)
675 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000676
677 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
678 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +0000679
680 // Builtin type used to help define __builtin_va_list.
681 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000682}
683
David Blaikied6471f72011-09-25 23:23:43 +0000684DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000685 return SourceMgr.getDiagnostics();
686}
687
Douglas Gregor63200642010-08-30 16:49:28 +0000688AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
689 AttrVec *&Result = DeclAttrs[D];
690 if (!Result) {
691 void *Mem = Allocate(sizeof(AttrVec));
692 Result = new (Mem) AttrVec;
693 }
694
695 return *Result;
696}
697
698/// \brief Erase the attributes corresponding to the given declaration.
699void ASTContext::eraseDeclAttrs(const Decl *D) {
700 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
701 if (Pos != DeclAttrs.end()) {
702 Pos->second->~AttrVec();
703 DeclAttrs.erase(Pos);
704 }
705}
706
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000707MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000708ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000709 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000710 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000711 = InstantiatedFromStaticDataMember.find(Var);
712 if (Pos == InstantiatedFromStaticDataMember.end())
713 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Douglas Gregor7caa6822009-07-24 20:34:43 +0000715 return Pos->second;
716}
717
Mike Stump1eb44332009-09-09 15:08:12 +0000718void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000719ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000720 TemplateSpecializationKind TSK,
721 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000722 assert(Inst->isStaticDataMember() && "Not a static data member");
723 assert(Tmpl->isStaticDataMember() && "Not a static data member");
724 assert(!InstantiatedFromStaticDataMember[Inst] &&
725 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000726 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000727 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000728}
729
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000730FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
731 const FunctionDecl *FD){
732 assert(FD && "Specialization is 0");
733 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000734 = ClassScopeSpecializationPattern.find(FD);
735 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000736 return 0;
737
738 return Pos->second;
739}
740
741void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
742 FunctionDecl *Pattern) {
743 assert(FD && "Specialization is 0");
744 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000745 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000746}
747
John McCall7ba107a2009-11-18 02:36:19 +0000748NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000749ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000750 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000751 = InstantiatedFromUsingDecl.find(UUD);
752 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000753 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Anders Carlsson0d8df782009-08-29 19:37:28 +0000755 return Pos->second;
756}
757
758void
John McCalled976492009-12-04 22:46:56 +0000759ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
760 assert((isa<UsingDecl>(Pattern) ||
761 isa<UnresolvedUsingValueDecl>(Pattern) ||
762 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
763 "pattern decl is not a using decl");
764 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
765 InstantiatedFromUsingDecl[Inst] = Pattern;
766}
767
768UsingShadowDecl *
769ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
770 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
771 = InstantiatedFromUsingShadowDecl.find(Inst);
772 if (Pos == InstantiatedFromUsingShadowDecl.end())
773 return 0;
774
775 return Pos->second;
776}
777
778void
779ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
780 UsingShadowDecl *Pattern) {
781 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
782 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000783}
784
Anders Carlssond8b285f2009-09-01 04:26:58 +0000785FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
786 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
787 = InstantiatedFromUnnamedFieldDecl.find(Field);
788 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
789 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Anders Carlssond8b285f2009-09-01 04:26:58 +0000791 return Pos->second;
792}
793
794void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
795 FieldDecl *Tmpl) {
796 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
797 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
798 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
799 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Anders Carlssond8b285f2009-09-01 04:26:58 +0000801 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
802}
803
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000804bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
805 const FieldDecl *LastFD) const {
806 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000807 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000808}
809
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000810bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
811 const FieldDecl *LastFD) const {
812 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000813 FD->getBitWidthValue(*this) == 0 &&
814 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000815}
816
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000817bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
818 const FieldDecl *LastFD) const {
819 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000820 FD->getBitWidthValue(*this) &&
821 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000822}
823
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000824bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000825 const FieldDecl *LastFD) const {
826 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000827 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000828}
829
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000830bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000831 const FieldDecl *LastFD) const {
832 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000833 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000834}
835
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000836ASTContext::overridden_cxx_method_iterator
837ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
838 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
839 = OverriddenMethods.find(Method);
840 if (Pos == OverriddenMethods.end())
841 return 0;
842
843 return Pos->second.begin();
844}
845
846ASTContext::overridden_cxx_method_iterator
847ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
848 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
849 = OverriddenMethods.find(Method);
850 if (Pos == OverriddenMethods.end())
851 return 0;
852
853 return Pos->second.end();
854}
855
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000856unsigned
857ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
858 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
859 = OverriddenMethods.find(Method);
860 if (Pos == OverriddenMethods.end())
861 return 0;
862
863 return Pos->second.size();
864}
865
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000866void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
867 const CXXMethodDecl *Overridden) {
868 OverriddenMethods[Method].push_back(Overridden);
869}
870
Douglas Gregore6649772011-12-03 00:30:27 +0000871void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
872 assert(!Import->NextLocalImport && "Import declaration already in the chain");
873 assert(!Import->isFromASTFile() && "Non-local import declaration");
874 if (!FirstLocalImport) {
875 FirstLocalImport = Import;
876 LastLocalImport = Import;
877 return;
878 }
879
880 LastLocalImport->NextLocalImport = Import;
881 LastLocalImport = Import;
882}
883
Chris Lattner464175b2007-07-18 17:52:12 +0000884//===----------------------------------------------------------------------===//
885// Type Sizing and Analysis
886//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000887
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000888/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
889/// scalar floating point type.
890const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000891 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000892 assert(BT && "Not a floating point type!");
893 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000894 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000895 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000896 case BuiltinType::Float: return Target->getFloatFormat();
897 case BuiltinType::Double: return Target->getDoubleFormat();
898 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000899 }
900}
901
Ken Dyck8b752f12010-01-27 17:10:57 +0000902/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000903/// specified decl. Note that bitfields do not have a valid alignment, so
904/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000905/// If @p RefAsPointee, references are treated like their underlying type
906/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000907CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000908 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +0000909
John McCall4081a5c2010-10-08 18:24:19 +0000910 bool UseAlignAttrOnly = false;
911 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
912 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000913
John McCall4081a5c2010-10-08 18:24:19 +0000914 // __attribute__((aligned)) can increase or decrease alignment
915 // *except* on a struct or struct member, where it only increases
916 // alignment unless 'packed' is also specified.
917 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +0000918 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +0000919 // ignore that possibility; Sema should diagnose it.
920 if (isa<FieldDecl>(D)) {
921 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
922 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
923 } else {
924 UseAlignAttrOnly = true;
925 }
926 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000927 else if (isa<FieldDecl>(D))
928 UseAlignAttrOnly =
929 D->hasAttr<PackedAttr>() ||
930 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000931
John McCallba4f5d52011-01-20 07:57:12 +0000932 // If we're using the align attribute only, just ignore everything
933 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000934 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000935 // do nothing
936
John McCall4081a5c2010-10-08 18:24:19 +0000937 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000938 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000939 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000940 if (RefAsPointee)
941 T = RT->getPointeeType();
942 else
943 T = getPointerType(RT->getPointeeType());
944 }
945 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000946 // Adjust alignments of declarations with array type by the
947 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000948 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000949 const ArrayType *arrayType;
950 if (MinWidth && (arrayType = getAsArrayType(T))) {
951 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000952 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +0000953 else if (isa<ConstantArrayType>(arrayType) &&
954 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000955 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000956
John McCall3b657512011-01-19 10:06:00 +0000957 // Walk through any array types while we're at it.
958 T = getBaseElementType(arrayType);
959 }
Chad Rosier9f1210c2011-07-26 07:03:04 +0000960 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +0000961 }
John McCallba4f5d52011-01-20 07:57:12 +0000962
963 // Fields can be subject to extra alignment constraints, like if
964 // the field is packed, the struct is packed, or the struct has a
965 // a max-field-alignment constraint (#pragma pack). So calculate
966 // the actual alignment of the field within the struct, and then
967 // (as we're expected to) constrain that by the alignment of the type.
968 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
969 // So calculate the alignment of the field.
970 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
971
972 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000973 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000974
975 // Use the GCD of that and the offset within the record.
976 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
977 if (offset > 0) {
978 // Alignment is always a power of 2, so the GCD will be a power of 2,
979 // which means we get to do this crazy thing instead of Euclid's.
980 uint64_t lowBitOfOffset = offset & (~offset + 1);
981 if (lowBitOfOffset < fieldAlign)
982 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
983 }
984
985 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000986 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000987 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000988
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000989 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000990}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000991
John McCallea1471e2010-05-20 01:18:31 +0000992std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000993ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000994 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000995 return std::make_pair(toCharUnitsFromBits(Info.first),
996 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000997}
998
999std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001000ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001001 return getTypeInfoInChars(T.getTypePtr());
1002}
1003
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001004std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1005 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1006 if (it != MemoizedTypeInfo.end())
1007 return it->second;
1008
1009 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1010 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1011 return Info;
1012}
1013
1014/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1015/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001016///
1017/// FIXME: Pointers into different addr spaces could have different sizes and
1018/// alignment requirements: getPointerInfo should take an AddrSpace, this
1019/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001020std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001021ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001022 uint64_t Width=0;
1023 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001024 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001025#define TYPE(Class, Base)
1026#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001027#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001028#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1029#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001030 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001031
Chris Lattner692233e2007-07-13 22:27:08 +00001032 case Type::FunctionNoProto:
1033 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001034 // GCC extension: alignof(function) = 32 bits
1035 Width = 0;
1036 Align = 32;
1037 break;
1038
Douglas Gregor72564e72009-02-26 23:50:07 +00001039 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001040 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001041 Width = 0;
1042 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1043 break;
1044
Steve Narofffb22d962007-08-30 01:06:46 +00001045 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001046 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Chris Lattner98be4942008-03-05 18:54:05 +00001048 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001049 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001050 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1051 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001052 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001053 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001054 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001055 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001056 }
Nate Begeman213541a2008-04-18 23:10:10 +00001057 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001058 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001059 const VectorType *VT = cast<VectorType>(T);
1060 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1061 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001062 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001063 // If the alignment is not a power of 2, round up to the next power of 2.
1064 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001065 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001066 Align = llvm::NextPowerOf2(Align);
1067 Width = llvm::RoundUpToAlignment(Width, Align);
1068 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001069 // Adjust the alignment based on the target max.
1070 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1071 if (TargetVectorAlign && TargetVectorAlign < Align)
1072 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001073 break;
1074 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001075
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001076 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001077 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001078 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001079 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001080 // GCC extension: alignof(void) = 8 bits.
1081 Width = 0;
1082 Align = 8;
1083 break;
1084
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001085 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001086 Width = Target->getBoolWidth();
1087 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001088 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001089 case BuiltinType::Char_S:
1090 case BuiltinType::Char_U:
1091 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001092 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001093 Width = Target->getCharWidth();
1094 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001095 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001096 case BuiltinType::WChar_S:
1097 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001098 Width = Target->getWCharWidth();
1099 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001100 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001101 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001102 Width = Target->getChar16Width();
1103 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001104 break;
1105 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001106 Width = Target->getChar32Width();
1107 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001108 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001109 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001110 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001111 Width = Target->getShortWidth();
1112 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001113 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001114 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001115 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001116 Width = Target->getIntWidth();
1117 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001118 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001119 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001120 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001121 Width = Target->getLongWidth();
1122 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001123 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001124 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001125 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001126 Width = Target->getLongLongWidth();
1127 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001128 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001129 case BuiltinType::Int128:
1130 case BuiltinType::UInt128:
1131 Width = 128;
1132 Align = 128; // int128_t is 128-bit aligned on all targets.
1133 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001134 case BuiltinType::Half:
1135 Width = Target->getHalfWidth();
1136 Align = Target->getHalfAlign();
1137 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001138 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001139 Width = Target->getFloatWidth();
1140 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001141 break;
1142 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001143 Width = Target->getDoubleWidth();
1144 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001145 break;
1146 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001147 Width = Target->getLongDoubleWidth();
1148 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001149 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001150 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001151 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1152 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001153 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001154 case BuiltinType::ObjCId:
1155 case BuiltinType::ObjCClass:
1156 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001157 Width = Target->getPointerWidth(0);
1158 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001159 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001160 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001161 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001162 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001163 Width = Target->getPointerWidth(0);
1164 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001165 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001166 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001167 unsigned AS = getTargetAddressSpace(
1168 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001169 Width = Target->getPointerWidth(AS);
1170 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001171 break;
1172 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001173 case Type::LValueReference:
1174 case Type::RValueReference: {
1175 // alignof and sizeof should never enter this code path here, so we go
1176 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001177 unsigned AS = getTargetAddressSpace(
1178 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001179 Width = Target->getPointerWidth(AS);
1180 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001181 break;
1182 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001183 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001184 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001185 Width = Target->getPointerWidth(AS);
1186 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001187 break;
1188 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001189 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001190 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001191 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001192 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +00001193 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001194 Align = PtrDiffInfo.second;
1195 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001196 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001197 case Type::Complex: {
1198 // Complex types have the same alignment as their elements, but twice the
1199 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001200 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001201 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001202 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001203 Align = EltInfo.second;
1204 break;
1205 }
John McCallc12c5bb2010-05-15 11:32:37 +00001206 case Type::ObjCObject:
1207 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001208 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001209 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001210 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001211 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001212 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001213 break;
1214 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001215 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001216 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001217 const TagType *TT = cast<TagType>(T);
1218
1219 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001220 Width = 8;
1221 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001222 break;
1223 }
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Daniel Dunbar1d751182008-11-08 05:48:37 +00001225 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001226 return getTypeInfo(ET->getDecl()->getIntegerType());
1227
Daniel Dunbar1d751182008-11-08 05:48:37 +00001228 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001229 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001230 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001231 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001232 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001233 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001234
Chris Lattner9fcfe922009-10-22 05:17:15 +00001235 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001236 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1237 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001238
Richard Smith34b41d92011-02-20 03:19:35 +00001239 case Type::Auto: {
1240 const AutoType *A = cast<AutoType>(T);
1241 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001242 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001243 }
1244
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001245 case Type::Paren:
1246 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1247
Douglas Gregor18857642009-04-30 17:32:17 +00001248 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001249 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001250 std::pair<uint64_t, unsigned> Info
1251 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001252 // If the typedef has an aligned attribute on it, it overrides any computed
1253 // alignment we have. This violates the GCC documentation (which says that
1254 // attribute(aligned) can only round up) but matches its implementation.
1255 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1256 Align = AttrAlign;
1257 else
1258 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001259 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001260 break;
Chris Lattner71763312008-04-06 22:05:18 +00001261 }
Douglas Gregor18857642009-04-30 17:32:17 +00001262
1263 case Type::TypeOfExpr:
1264 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1265 .getTypePtr());
1266
1267 case Type::TypeOf:
1268 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1269
Anders Carlsson395b4752009-06-24 19:06:50 +00001270 case Type::Decltype:
1271 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1272 .getTypePtr());
1273
Sean Huntca63c202011-05-24 22:41:36 +00001274 case Type::UnaryTransform:
1275 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1276
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001277 case Type::Elaborated:
1278 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001279
John McCall9d156a72011-01-06 01:58:22 +00001280 case Type::Attributed:
1281 return getTypeInfo(
1282 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1283
Richard Smith3e4c6c42011-05-05 21:57:07 +00001284 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001285 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001286 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001287 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1288 // A type alias template specialization may refer to a typedef with the
1289 // aligned attribute on it.
1290 if (TST->isTypeAlias())
1291 return getTypeInfo(TST->getAliasedType().getTypePtr());
1292 else
1293 return getTypeInfo(getCanonicalType(T));
1294 }
1295
Eli Friedmanb001de72011-10-06 23:00:33 +00001296 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001297 std::pair<uint64_t, unsigned> Info
1298 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1299 Width = Info.first;
1300 Align = Info.second;
1301 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1302 llvm::isPowerOf2_64(Width)) {
1303 // We can potentially perform lock-free atomic operations for this
1304 // type; promote the alignment appropriately.
1305 // FIXME: We could potentially promote the width here as well...
1306 // is that worthwhile? (Non-struct atomic types generally have
1307 // power-of-two size anyway, but structs might not. Requires a bit
1308 // of implementation work to make sure we zero out the extra bits.)
1309 Align = static_cast<unsigned>(Width);
1310 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001311 }
1312
Douglas Gregor18857642009-04-30 17:32:17 +00001313 }
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Eli Friedman2be46072011-10-14 20:59:01 +00001315 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001316 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001317}
1318
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001319/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1320CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1321 return CharUnits::fromQuantity(BitSize / getCharWidth());
1322}
1323
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001324/// toBits - Convert a size in characters to a size in characters.
1325int64_t ASTContext::toBits(CharUnits CharSize) const {
1326 return CharSize.getQuantity() * getCharWidth();
1327}
1328
Ken Dyckbdc601b2009-12-22 14:23:30 +00001329/// getTypeSizeInChars - Return the size of the specified type, in characters.
1330/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001331CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001332 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001333}
Jay Foad4ba2a172011-01-12 09:06:06 +00001334CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001335 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001336}
1337
Ken Dyck16e20cc2010-01-26 17:25:18 +00001338/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001339/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001340CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001341 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001342}
Jay Foad4ba2a172011-01-12 09:06:06 +00001343CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001344 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001345}
1346
Chris Lattner34ebde42009-01-27 18:08:34 +00001347/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1348/// type for the current target in bits. This can be different than the ABI
1349/// alignment in cases where it is beneficial for performance to overalign
1350/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001351unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001352 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001353
1354 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001355 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001356 T = CT->getElementType().getTypePtr();
1357 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001358 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1359 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001360 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1361
Chris Lattner34ebde42009-01-27 18:08:34 +00001362 return ABIAlign;
1363}
1364
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001365/// DeepCollectObjCIvars -
1366/// This routine first collects all declared, but not synthesized, ivars in
1367/// super class and then collects all ivars, including those synthesized for
1368/// current class. This routine is used for implementation of current class
1369/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001370///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001371void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1372 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001373 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001374 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1375 DeepCollectObjCIvars(SuperClass, false, Ivars);
1376 if (!leafClass) {
1377 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1378 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001379 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001380 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001381 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001382 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001383 Iv= Iv->getNextIvar())
1384 Ivars.push_back(Iv);
1385 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001386}
1387
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001388/// CollectInheritedProtocols - Collect all protocols in current class and
1389/// those inherited by it.
1390void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001391 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001392 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001393 // We can use protocol_iterator here instead of
1394 // all_referenced_protocol_iterator since we are walking all categories.
1395 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1396 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001397 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001398 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001399 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001400 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001401 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001402 CollectInheritedProtocols(*P, Protocols);
1403 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001404 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001405
1406 // Categories of this Interface.
1407 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1408 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1409 CollectInheritedProtocols(CDeclChain, Protocols);
1410 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1411 while (SD) {
1412 CollectInheritedProtocols(SD, Protocols);
1413 SD = SD->getSuperClass();
1414 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001415 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001416 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001417 PE = OC->protocol_end(); P != PE; ++P) {
1418 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001419 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001420 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1421 PE = Proto->protocol_end(); P != PE; ++P)
1422 CollectInheritedProtocols(*P, Protocols);
1423 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001424 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001425 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1426 PE = OP->protocol_end(); P != PE; ++P) {
1427 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001428 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001429 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1430 PE = Proto->protocol_end(); P != PE; ++P)
1431 CollectInheritedProtocols(*P, Protocols);
1432 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001433 }
1434}
1435
Jay Foad4ba2a172011-01-12 09:06:06 +00001436unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001437 unsigned count = 0;
1438 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001439 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1440 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001441 count += CDecl->ivar_size();
1442
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001443 // Count ivar defined in this class's implementation. This
1444 // includes synthesized ivars.
1445 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001446 count += ImplDecl->ivar_size();
1447
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001448 return count;
1449}
1450
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001451bool ASTContext::isSentinelNullExpr(const Expr *E) {
1452 if (!E)
1453 return false;
1454
1455 // nullptr_t is always treated as null.
1456 if (E->getType()->isNullPtrType()) return true;
1457
1458 if (E->getType()->isAnyPointerType() &&
1459 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1460 Expr::NPC_ValueDependentIsNull))
1461 return true;
1462
1463 // Unfortunately, __null has type 'int'.
1464 if (isa<GNUNullExpr>(E)) return true;
1465
1466 return false;
1467}
1468
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001469/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1470ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1471 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1472 I = ObjCImpls.find(D);
1473 if (I != ObjCImpls.end())
1474 return cast<ObjCImplementationDecl>(I->second);
1475 return 0;
1476}
1477/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1478ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1479 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1480 I = ObjCImpls.find(D);
1481 if (I != ObjCImpls.end())
1482 return cast<ObjCCategoryImplDecl>(I->second);
1483 return 0;
1484}
1485
1486/// \brief Set the implementation of ObjCInterfaceDecl.
1487void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1488 ObjCImplementationDecl *ImplD) {
1489 assert(IFaceD && ImplD && "Passed null params");
1490 ObjCImpls[IFaceD] = ImplD;
1491}
1492/// \brief Set the implementation of ObjCCategoryDecl.
1493void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1494 ObjCCategoryImplDecl *ImplD) {
1495 assert(CatD && ImplD && "Passed null params");
1496 ObjCImpls[CatD] = ImplD;
1497}
1498
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001499ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1500 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1501 return ID;
1502 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1503 return CD->getClassInterface();
1504 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1505 return IMD->getClassInterface();
1506
1507 return 0;
1508}
1509
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001510/// \brief Get the copy initialization expression of VarDecl,or NULL if
1511/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001512Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001513 assert(VD && "Passed null params");
1514 assert(VD->hasAttr<BlocksAttr>() &&
1515 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001516 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001517 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001518 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1519}
1520
1521/// \brief Set the copy inialization expression of a block var decl.
1522void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1523 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001524 assert(VD->hasAttr<BlocksAttr>() &&
1525 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001526 BlockVarCopyInits[VD] = Init;
1527}
1528
John McCalla93c9342009-12-07 02:54:59 +00001529TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001530 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001531 if (!DataSize)
1532 DataSize = TypeLoc::getFullDataSizeForType(T);
1533 else
1534 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001535 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001536
John McCalla93c9342009-12-07 02:54:59 +00001537 TypeSourceInfo *TInfo =
1538 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1539 new (TInfo) TypeSourceInfo(T);
1540 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001541}
1542
John McCalla93c9342009-12-07 02:54:59 +00001543TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001544 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001545 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001546 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001547 return DI;
1548}
1549
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001550const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001551ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001552 return getObjCLayout(D, 0);
1553}
1554
1555const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001556ASTContext::getASTObjCImplementationLayout(
1557 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001558 return getObjCLayout(D->getClassInterface(), D);
1559}
1560
Chris Lattnera7674d82007-07-13 22:13:22 +00001561//===----------------------------------------------------------------------===//
1562// Type creation/memoization methods
1563//===----------------------------------------------------------------------===//
1564
Jay Foad4ba2a172011-01-12 09:06:06 +00001565QualType
John McCall3b657512011-01-19 10:06:00 +00001566ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1567 unsigned fastQuals = quals.getFastQualifiers();
1568 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001569
1570 // Check if we've already instantiated this type.
1571 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001572 ExtQuals::Profile(ID, baseType, quals);
1573 void *insertPos = 0;
1574 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1575 assert(eq->getQualifiers() == quals);
1576 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001577 }
1578
John McCall3b657512011-01-19 10:06:00 +00001579 // If the base type is not canonical, make the appropriate canonical type.
1580 QualType canon;
1581 if (!baseType->isCanonicalUnqualified()) {
1582 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001583 canonSplit.Quals.addConsistentQualifiers(quals);
1584 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001585
1586 // Re-find the insert position.
1587 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1588 }
1589
1590 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1591 ExtQualNodes.InsertNode(eq, insertPos);
1592 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001593}
1594
Jay Foad4ba2a172011-01-12 09:06:06 +00001595QualType
1596ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001597 QualType CanT = getCanonicalType(T);
1598 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001599 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001600
John McCall0953e762009-09-24 19:53:00 +00001601 // If we are composing extended qualifiers together, merge together
1602 // into one ExtQuals node.
1603 QualifierCollector Quals;
1604 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001605
John McCall0953e762009-09-24 19:53:00 +00001606 // If this type already has an address space specified, it cannot get
1607 // another one.
1608 assert(!Quals.hasAddressSpace() &&
1609 "Type cannot be in multiple addr spaces!");
1610 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001611
John McCall0953e762009-09-24 19:53:00 +00001612 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001613}
1614
Chris Lattnerb7d25532009-02-18 22:53:11 +00001615QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001616 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001617 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001618 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001619 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001620
John McCall7f040a92010-12-24 02:08:15 +00001621 if (const PointerType *ptr = T->getAs<PointerType>()) {
1622 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001623 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001624 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1625 return getPointerType(ResultType);
1626 }
1627 }
Mike Stump1eb44332009-09-09 15:08:12 +00001628
John McCall0953e762009-09-24 19:53:00 +00001629 // If we are composing extended qualifiers together, merge together
1630 // into one ExtQuals node.
1631 QualifierCollector Quals;
1632 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001633
John McCall0953e762009-09-24 19:53:00 +00001634 // If this type already has an ObjCGC specified, it cannot get
1635 // another one.
1636 assert(!Quals.hasObjCGCAttr() &&
1637 "Type cannot have multiple ObjCGCs!");
1638 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001639
John McCall0953e762009-09-24 19:53:00 +00001640 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001641}
Chris Lattnera7674d82007-07-13 22:13:22 +00001642
John McCalle6a365d2010-12-19 02:44:49 +00001643const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1644 FunctionType::ExtInfo Info) {
1645 if (T->getExtInfo() == Info)
1646 return T;
1647
1648 QualType Result;
1649 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1650 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1651 } else {
1652 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1653 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1654 EPI.ExtInfo = Info;
1655 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1656 FPT->getNumArgs(), EPI);
1657 }
1658
1659 return cast<FunctionType>(Result.getTypePtr());
1660}
1661
Reid Spencer5f016e22007-07-11 17:01:13 +00001662/// getComplexType - Return the uniqued reference to the type for a complex
1663/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001664QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001665 // Unique pointers, to guarantee there is only one pointer of a particular
1666 // structure.
1667 llvm::FoldingSetNodeID ID;
1668 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 void *InsertPos = 0;
1671 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1672 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Reid Spencer5f016e22007-07-11 17:01:13 +00001674 // If the pointee type isn't canonical, this won't be a canonical type either,
1675 // so fill in the canonical type field.
1676 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001677 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001678 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 // Get the new insert position for the node we care about.
1681 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001682 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001683 }
John McCall6b304a02009-09-24 23:30:46 +00001684 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 Types.push_back(New);
1686 ComplexTypes.InsertNode(New, InsertPos);
1687 return QualType(New, 0);
1688}
1689
Reid Spencer5f016e22007-07-11 17:01:13 +00001690/// getPointerType - Return the uniqued reference to the type for a pointer to
1691/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001692QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001693 // Unique pointers, to guarantee there is only one pointer of a particular
1694 // structure.
1695 llvm::FoldingSetNodeID ID;
1696 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 void *InsertPos = 0;
1699 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1700 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 // If the pointee type isn't canonical, this won't be a canonical type either,
1703 // so fill in the canonical type field.
1704 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001705 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001706 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001707
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 // Get the new insert position for the node we care about.
1709 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001710 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 }
John McCall6b304a02009-09-24 23:30:46 +00001712 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001713 Types.push_back(New);
1714 PointerTypes.InsertNode(New, InsertPos);
1715 return QualType(New, 0);
1716}
1717
Mike Stump1eb44332009-09-09 15:08:12 +00001718/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001719/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001720QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001721 assert(T->isFunctionType() && "block of function types only");
1722 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001723 // structure.
1724 llvm::FoldingSetNodeID ID;
1725 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Steve Naroff5618bd42008-08-27 16:04:49 +00001727 void *InsertPos = 0;
1728 if (BlockPointerType *PT =
1729 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1730 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001731
1732 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001733 // type either so fill in the canonical type field.
1734 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001735 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001736 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001737
Steve Naroff5618bd42008-08-27 16:04:49 +00001738 // Get the new insert position for the node we care about.
1739 BlockPointerType *NewIP =
1740 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001741 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001742 }
John McCall6b304a02009-09-24 23:30:46 +00001743 BlockPointerType *New
1744 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001745 Types.push_back(New);
1746 BlockPointerTypes.InsertNode(New, InsertPos);
1747 return QualType(New, 0);
1748}
1749
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001750/// getLValueReferenceType - Return the uniqued reference to the type for an
1751/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001752QualType
1753ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001754 assert(getCanonicalType(T) != OverloadTy &&
1755 "Unresolved overloaded function type");
1756
Reid Spencer5f016e22007-07-11 17:01:13 +00001757 // Unique pointers, to guarantee there is only one pointer of a particular
1758 // structure.
1759 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001760 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001761
1762 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001763 if (LValueReferenceType *RT =
1764 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001765 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001766
John McCall54e14c42009-10-22 22:37:11 +00001767 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1768
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 // If the referencee type isn't canonical, this won't be a canonical type
1770 // either, so fill in the canonical type field.
1771 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001772 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1773 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1774 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001775
Reid Spencer5f016e22007-07-11 17:01:13 +00001776 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001777 LValueReferenceType *NewIP =
1778 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001779 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001780 }
1781
John McCall6b304a02009-09-24 23:30:46 +00001782 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001783 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1784 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001785 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001786 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001787
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001788 return QualType(New, 0);
1789}
1790
1791/// getRValueReferenceType - Return the uniqued reference to the type for an
1792/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001793QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001794 // Unique pointers, to guarantee there is only one pointer of a particular
1795 // structure.
1796 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001797 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001798
1799 void *InsertPos = 0;
1800 if (RValueReferenceType *RT =
1801 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1802 return QualType(RT, 0);
1803
John McCall54e14c42009-10-22 22:37:11 +00001804 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1805
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001806 // If the referencee type isn't canonical, this won't be a canonical type
1807 // either, so fill in the canonical type field.
1808 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001809 if (InnerRef || !T.isCanonical()) {
1810 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1811 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001812
1813 // Get the new insert position for the node we care about.
1814 RValueReferenceType *NewIP =
1815 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001816 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001817 }
1818
John McCall6b304a02009-09-24 23:30:46 +00001819 RValueReferenceType *New
1820 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001821 Types.push_back(New);
1822 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001823 return QualType(New, 0);
1824}
1825
Sebastian Redlf30208a2009-01-24 21:16:55 +00001826/// getMemberPointerType - Return the uniqued reference to the type for a
1827/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001828QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001829 // Unique pointers, to guarantee there is only one pointer of a particular
1830 // structure.
1831 llvm::FoldingSetNodeID ID;
1832 MemberPointerType::Profile(ID, T, Cls);
1833
1834 void *InsertPos = 0;
1835 if (MemberPointerType *PT =
1836 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1837 return QualType(PT, 0);
1838
1839 // If the pointee or class type isn't canonical, this won't be a canonical
1840 // type either, so fill in the canonical type field.
1841 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001842 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001843 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1844
1845 // Get the new insert position for the node we care about.
1846 MemberPointerType *NewIP =
1847 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001848 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001849 }
John McCall6b304a02009-09-24 23:30:46 +00001850 MemberPointerType *New
1851 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001852 Types.push_back(New);
1853 MemberPointerTypes.InsertNode(New, InsertPos);
1854 return QualType(New, 0);
1855}
1856
Mike Stump1eb44332009-09-09 15:08:12 +00001857/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001858/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001859QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001860 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001861 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001862 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001863 assert((EltTy->isDependentType() ||
1864 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001865 "Constant array of VLAs is illegal!");
1866
Chris Lattner38aeec72009-05-13 04:12:56 +00001867 // Convert the array size into a canonical width matching the pointer size for
1868 // the target.
1869 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001870 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001871 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Reid Spencer5f016e22007-07-11 17:01:13 +00001873 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001874 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001875
Reid Spencer5f016e22007-07-11 17:01:13 +00001876 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001877 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001878 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001879 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001880
John McCall3b657512011-01-19 10:06:00 +00001881 // If the element type isn't canonical or has qualifiers, this won't
1882 // be a canonical type either, so fill in the canonical type field.
1883 QualType Canon;
1884 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1885 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00001886 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001887 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00001888 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001889
Reid Spencer5f016e22007-07-11 17:01:13 +00001890 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001891 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001892 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001893 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001894 }
Mike Stump1eb44332009-09-09 15:08:12 +00001895
John McCall6b304a02009-09-24 23:30:46 +00001896 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001897 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001898 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 Types.push_back(New);
1900 return QualType(New, 0);
1901}
1902
John McCallce889032011-01-18 08:40:38 +00001903/// getVariableArrayDecayedType - Turns the given type, which may be
1904/// variably-modified, into the corresponding type with all the known
1905/// sizes replaced with [*].
1906QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1907 // Vastly most common case.
1908 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001909
John McCallce889032011-01-18 08:40:38 +00001910 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001911
John McCallce889032011-01-18 08:40:38 +00001912 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00001913 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00001914 switch (ty->getTypeClass()) {
1915#define TYPE(Class, Base)
1916#define ABSTRACT_TYPE(Class, Base)
1917#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1918#include "clang/AST/TypeNodes.def"
1919 llvm_unreachable("didn't desugar past all non-canonical types?");
1920
1921 // These types should never be variably-modified.
1922 case Type::Builtin:
1923 case Type::Complex:
1924 case Type::Vector:
1925 case Type::ExtVector:
1926 case Type::DependentSizedExtVector:
1927 case Type::ObjCObject:
1928 case Type::ObjCInterface:
1929 case Type::ObjCObjectPointer:
1930 case Type::Record:
1931 case Type::Enum:
1932 case Type::UnresolvedUsing:
1933 case Type::TypeOfExpr:
1934 case Type::TypeOf:
1935 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001936 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001937 case Type::DependentName:
1938 case Type::InjectedClassName:
1939 case Type::TemplateSpecialization:
1940 case Type::DependentTemplateSpecialization:
1941 case Type::TemplateTypeParm:
1942 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001943 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001944 case Type::PackExpansion:
1945 llvm_unreachable("type should never be variably-modified");
1946
1947 // These types can be variably-modified but should never need to
1948 // further decay.
1949 case Type::FunctionNoProto:
1950 case Type::FunctionProto:
1951 case Type::BlockPointer:
1952 case Type::MemberPointer:
1953 return type;
1954
1955 // These types can be variably-modified. All these modifications
1956 // preserve structure except as noted by comments.
1957 // TODO: if we ever care about optimizing VLAs, there are no-op
1958 // optimizations available here.
1959 case Type::Pointer:
1960 result = getPointerType(getVariableArrayDecayedType(
1961 cast<PointerType>(ty)->getPointeeType()));
1962 break;
1963
1964 case Type::LValueReference: {
1965 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1966 result = getLValueReferenceType(
1967 getVariableArrayDecayedType(lv->getPointeeType()),
1968 lv->isSpelledAsLValue());
1969 break;
1970 }
1971
1972 case Type::RValueReference: {
1973 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1974 result = getRValueReferenceType(
1975 getVariableArrayDecayedType(lv->getPointeeType()));
1976 break;
1977 }
1978
Eli Friedmanb001de72011-10-06 23:00:33 +00001979 case Type::Atomic: {
1980 const AtomicType *at = cast<AtomicType>(ty);
1981 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1982 break;
1983 }
1984
John McCallce889032011-01-18 08:40:38 +00001985 case Type::ConstantArray: {
1986 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1987 result = getConstantArrayType(
1988 getVariableArrayDecayedType(cat->getElementType()),
1989 cat->getSize(),
1990 cat->getSizeModifier(),
1991 cat->getIndexTypeCVRQualifiers());
1992 break;
1993 }
1994
1995 case Type::DependentSizedArray: {
1996 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1997 result = getDependentSizedArrayType(
1998 getVariableArrayDecayedType(dat->getElementType()),
1999 dat->getSizeExpr(),
2000 dat->getSizeModifier(),
2001 dat->getIndexTypeCVRQualifiers(),
2002 dat->getBracketsRange());
2003 break;
2004 }
2005
2006 // Turn incomplete types into [*] types.
2007 case Type::IncompleteArray: {
2008 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2009 result = getVariableArrayType(
2010 getVariableArrayDecayedType(iat->getElementType()),
2011 /*size*/ 0,
2012 ArrayType::Normal,
2013 iat->getIndexTypeCVRQualifiers(),
2014 SourceRange());
2015 break;
2016 }
2017
2018 // Turn VLA types into [*] types.
2019 case Type::VariableArray: {
2020 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2021 result = getVariableArrayType(
2022 getVariableArrayDecayedType(vat->getElementType()),
2023 /*size*/ 0,
2024 ArrayType::Star,
2025 vat->getIndexTypeCVRQualifiers(),
2026 vat->getBracketsRange());
2027 break;
2028 }
2029 }
2030
2031 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002032 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002033}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002034
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002035/// getVariableArrayType - Returns a non-unique reference to the type for a
2036/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002037QualType ASTContext::getVariableArrayType(QualType EltTy,
2038 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002039 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002040 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002041 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002042 // Since we don't unique expressions, it isn't possible to unique VLA's
2043 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002044 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002045
John McCall3b657512011-01-19 10:06:00 +00002046 // Be sure to pull qualifiers off the element type.
2047 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2048 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002049 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002050 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002051 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002052 }
2053
John McCall6b304a02009-09-24 23:30:46 +00002054 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002055 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002056
2057 VariableArrayTypes.push_back(New);
2058 Types.push_back(New);
2059 return QualType(New, 0);
2060}
2061
Douglas Gregor898574e2008-12-05 23:32:09 +00002062/// getDependentSizedArrayType - Returns a non-unique reference to
2063/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002064/// type.
John McCall3b657512011-01-19 10:06:00 +00002065QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2066 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002067 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002068 unsigned elementTypeQuals,
2069 SourceRange brackets) const {
2070 assert((!numElements || numElements->isTypeDependent() ||
2071 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002072 "Size must be type- or value-dependent!");
2073
John McCall3b657512011-01-19 10:06:00 +00002074 // Dependently-sized array types that do not have a specified number
2075 // of elements will have their sizes deduced from a dependent
2076 // initializer. We do no canonicalization here at all, which is okay
2077 // because they can't be used in most locations.
2078 if (!numElements) {
2079 DependentSizedArrayType *newType
2080 = new (*this, TypeAlignment)
2081 DependentSizedArrayType(*this, elementType, QualType(),
2082 numElements, ASM, elementTypeQuals,
2083 brackets);
2084 Types.push_back(newType);
2085 return QualType(newType, 0);
2086 }
2087
2088 // Otherwise, we actually build a new type every time, but we
2089 // also build a canonical type.
2090
2091 SplitQualType canonElementType = getCanonicalType(elementType).split();
2092
2093 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002094 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002095 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002096 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002097 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002098
John McCall3b657512011-01-19 10:06:00 +00002099 // Look for an existing type with these properties.
2100 DependentSizedArrayType *canonTy =
2101 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002102
John McCall3b657512011-01-19 10:06:00 +00002103 // If we don't have one, build one.
2104 if (!canonTy) {
2105 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002106 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002107 QualType(), numElements, ASM, elementTypeQuals,
2108 brackets);
2109 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2110 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002111 }
2112
John McCall3b657512011-01-19 10:06:00 +00002113 // Apply qualifiers from the element type to the array.
2114 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002115 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002116
John McCall3b657512011-01-19 10:06:00 +00002117 // If we didn't need extra canonicalization for the element type,
2118 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002119 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002120 return canon;
2121
2122 // Otherwise, we need to build a type which follows the spelling
2123 // of the element type.
2124 DependentSizedArrayType *sugaredType
2125 = new (*this, TypeAlignment)
2126 DependentSizedArrayType(*this, elementType, canon, numElements,
2127 ASM, elementTypeQuals, brackets);
2128 Types.push_back(sugaredType);
2129 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002130}
2131
John McCall3b657512011-01-19 10:06:00 +00002132QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002133 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002134 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002135 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002136 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002137
John McCall3b657512011-01-19 10:06:00 +00002138 void *insertPos = 0;
2139 if (IncompleteArrayType *iat =
2140 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2141 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002142
2143 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002144 // either, so fill in the canonical type field. We also have to pull
2145 // qualifiers off the element type.
2146 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002147
John McCall3b657512011-01-19 10:06:00 +00002148 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2149 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002150 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002151 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002152 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002153
2154 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002155 IncompleteArrayType *existing =
2156 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2157 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002158 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002159
John McCall3b657512011-01-19 10:06:00 +00002160 IncompleteArrayType *newType = new (*this, TypeAlignment)
2161 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002162
John McCall3b657512011-01-19 10:06:00 +00002163 IncompleteArrayTypes.InsertNode(newType, insertPos);
2164 Types.push_back(newType);
2165 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002166}
2167
Steve Naroff73322922007-07-18 18:00:27 +00002168/// getVectorType - Return the unique reference to a vector type of
2169/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002170QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002171 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002172 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002173
Reid Spencer5f016e22007-07-11 17:01:13 +00002174 // Check if we've already instantiated a vector of this type.
2175 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002176 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002177
Reid Spencer5f016e22007-07-11 17:01:13 +00002178 void *InsertPos = 0;
2179 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2180 return QualType(VTP, 0);
2181
2182 // If the element type isn't canonical, this won't be a canonical type either,
2183 // so fill in the canonical type field.
2184 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002185 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002186 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002187
Reid Spencer5f016e22007-07-11 17:01:13 +00002188 // Get the new insert position for the node we care about.
2189 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002190 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002191 }
John McCall6b304a02009-09-24 23:30:46 +00002192 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002193 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002194 VectorTypes.InsertNode(New, InsertPos);
2195 Types.push_back(New);
2196 return QualType(New, 0);
2197}
2198
Nate Begeman213541a2008-04-18 23:10:10 +00002199/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002200/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002201QualType
2202ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002203 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002204
Steve Naroff73322922007-07-18 18:00:27 +00002205 // Check if we've already instantiated a vector of this type.
2206 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002207 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002208 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002209 void *InsertPos = 0;
2210 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2211 return QualType(VTP, 0);
2212
2213 // If the element type isn't canonical, this won't be a canonical type either,
2214 // so fill in the canonical type field.
2215 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002216 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002217 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002218
Steve Naroff73322922007-07-18 18:00:27 +00002219 // Get the new insert position for the node we care about.
2220 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002221 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002222 }
John McCall6b304a02009-09-24 23:30:46 +00002223 ExtVectorType *New = new (*this, TypeAlignment)
2224 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002225 VectorTypes.InsertNode(New, InsertPos);
2226 Types.push_back(New);
2227 return QualType(New, 0);
2228}
2229
Jay Foad4ba2a172011-01-12 09:06:06 +00002230QualType
2231ASTContext::getDependentSizedExtVectorType(QualType vecType,
2232 Expr *SizeExpr,
2233 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002234 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002235 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002236 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002238 void *InsertPos = 0;
2239 DependentSizedExtVectorType *Canon
2240 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2241 DependentSizedExtVectorType *New;
2242 if (Canon) {
2243 // We already have a canonical version of this array type; use it as
2244 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002245 New = new (*this, TypeAlignment)
2246 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2247 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002248 } else {
2249 QualType CanonVecTy = getCanonicalType(vecType);
2250 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002251 New = new (*this, TypeAlignment)
2252 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2253 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002254
2255 DependentSizedExtVectorType *CanonCheck
2256 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2257 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2258 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002259 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2260 } else {
2261 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2262 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002263 New = new (*this, TypeAlignment)
2264 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002265 }
2266 }
Mike Stump1eb44332009-09-09 15:08:12 +00002267
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002268 Types.push_back(New);
2269 return QualType(New, 0);
2270}
2271
Douglas Gregor72564e72009-02-26 23:50:07 +00002272/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002273///
Jay Foad4ba2a172011-01-12 09:06:06 +00002274QualType
2275ASTContext::getFunctionNoProtoType(QualType ResultTy,
2276 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002277 const CallingConv DefaultCC = Info.getCC();
2278 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2279 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002280 // Unique functions, to guarantee there is only one function of a particular
2281 // structure.
2282 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002283 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002284
Reid Spencer5f016e22007-07-11 17:01:13 +00002285 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002286 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002287 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002288 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002289
Reid Spencer5f016e22007-07-11 17:01:13 +00002290 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002291 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002292 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002293 Canonical =
2294 getFunctionNoProtoType(getCanonicalType(ResultTy),
2295 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002296
Reid Spencer5f016e22007-07-11 17:01:13 +00002297 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002298 FunctionNoProtoType *NewIP =
2299 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002300 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002301 }
Mike Stump1eb44332009-09-09 15:08:12 +00002302
Roman Divackycfe9af22011-03-01 17:40:53 +00002303 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002304 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002305 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002306 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002307 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002308 return QualType(New, 0);
2309}
2310
2311/// getFunctionType - Return a normal function type with a typed argument
2312/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002313QualType
2314ASTContext::getFunctionType(QualType ResultTy,
2315 const QualType *ArgArray, unsigned NumArgs,
2316 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002317 // Unique functions, to guarantee there is only one function of a particular
2318 // structure.
2319 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002320 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002321
2322 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002323 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002324 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002325 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002326
2327 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002328 bool isCanonical =
2329 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2330 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002331 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002332 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002333 isCanonical = false;
2334
Roman Divackycfe9af22011-03-01 17:40:53 +00002335 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2336 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2337 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002338
Reid Spencer5f016e22007-07-11 17:01:13 +00002339 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002340 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002341 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002342 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002343 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002344 CanonicalArgs.reserve(NumArgs);
2345 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002346 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002347
John McCalle23cf432010-12-14 08:05:40 +00002348 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002349 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002350 CanonicalEPI.ExceptionSpecType = EST_None;
2351 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002352 CanonicalEPI.ExtInfo
2353 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2354
Chris Lattnerf52ab252008-04-06 22:59:24 +00002355 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002356 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002357 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002358
Reid Spencer5f016e22007-07-11 17:01:13 +00002359 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002360 FunctionProtoType *NewIP =
2361 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002362 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002363 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002364
John McCallf85e1932011-06-15 23:02:42 +00002365 // FunctionProtoType objects are allocated with extra bytes after
2366 // them for three variable size arrays at the end:
2367 // - parameter types
2368 // - exception types
2369 // - consumed-arguments flags
2370 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002371 // expression, or information used to resolve the exception
2372 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002373 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002374 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002375 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002376 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002377 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002378 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002379 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002380 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002381 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2382 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002383 }
John McCallf85e1932011-06-15 23:02:42 +00002384 if (EPI.ConsumedArguments)
2385 Size += NumArgs * sizeof(bool);
2386
John McCalle23cf432010-12-14 08:05:40 +00002387 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002388 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2389 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002390 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002391 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002392 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002393 return QualType(FTP, 0);
2394}
2395
John McCall3cb0ebd2010-03-10 03:28:59 +00002396#ifndef NDEBUG
2397static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2398 if (!isa<CXXRecordDecl>(D)) return false;
2399 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2400 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2401 return true;
2402 if (RD->getDescribedClassTemplate() &&
2403 !isa<ClassTemplateSpecializationDecl>(RD))
2404 return true;
2405 return false;
2406}
2407#endif
2408
2409/// getInjectedClassNameType - Return the unique reference to the
2410/// injected class name type for the specified templated declaration.
2411QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002412 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002413 assert(NeedsInjectedClassNameType(Decl));
2414 if (Decl->TypeForDecl) {
2415 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002416 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002417 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2418 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2419 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2420 } else {
John McCallf4c73712011-01-19 06:33:43 +00002421 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002422 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002423 Decl->TypeForDecl = newType;
2424 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002425 }
2426 return QualType(Decl->TypeForDecl, 0);
2427}
2428
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002429/// getTypeDeclType - Return the unique reference to the type for the
2430/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002431QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002432 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002433 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002434
Richard Smith162e1c12011-04-15 14:24:37 +00002435 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002436 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002437
John McCallbecb8d52010-03-10 06:48:02 +00002438 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2439 "Template type parameter types are always available.");
2440
John McCall19c85762010-02-16 03:57:14 +00002441 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002442 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002443 "struct/union has previous declaration");
2444 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002445 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002446 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002447 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002448 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002449 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002450 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002451 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002452 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2453 Decl->TypeForDecl = newType;
2454 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002455 } else
John McCallbecb8d52010-03-10 06:48:02 +00002456 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002457
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002458 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002459}
2460
Reid Spencer5f016e22007-07-11 17:01:13 +00002461/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002462/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002463QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002464ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2465 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002466 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002467
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002468 if (Canonical.isNull())
2469 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002470 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002471 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002472 Decl->TypeForDecl = newType;
2473 Types.push_back(newType);
2474 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002475}
2476
Jay Foad4ba2a172011-01-12 09:06:06 +00002477QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002478 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2479
Douglas Gregoref96ee02012-01-14 16:38:05 +00002480 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002481 if (PrevDecl->TypeForDecl)
2482 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2483
John McCallf4c73712011-01-19 06:33:43 +00002484 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2485 Decl->TypeForDecl = newType;
2486 Types.push_back(newType);
2487 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002488}
2489
Jay Foad4ba2a172011-01-12 09:06:06 +00002490QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002491 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2492
Douglas Gregoref96ee02012-01-14 16:38:05 +00002493 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002494 if (PrevDecl->TypeForDecl)
2495 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2496
John McCallf4c73712011-01-19 06:33:43 +00002497 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2498 Decl->TypeForDecl = newType;
2499 Types.push_back(newType);
2500 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002501}
2502
John McCall9d156a72011-01-06 01:58:22 +00002503QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2504 QualType modifiedType,
2505 QualType equivalentType) {
2506 llvm::FoldingSetNodeID id;
2507 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2508
2509 void *insertPos = 0;
2510 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2511 if (type) return QualType(type, 0);
2512
2513 QualType canon = getCanonicalType(equivalentType);
2514 type = new (*this, TypeAlignment)
2515 AttributedType(canon, attrKind, modifiedType, equivalentType);
2516
2517 Types.push_back(type);
2518 AttributedTypes.InsertNode(type, insertPos);
2519
2520 return QualType(type, 0);
2521}
2522
2523
John McCall49a832b2009-10-18 09:09:24 +00002524/// \brief Retrieve a substitution-result type.
2525QualType
2526ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002527 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002528 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002529 && "replacement types must always be canonical");
2530
2531 llvm::FoldingSetNodeID ID;
2532 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2533 void *InsertPos = 0;
2534 SubstTemplateTypeParmType *SubstParm
2535 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2536
2537 if (!SubstParm) {
2538 SubstParm = new (*this, TypeAlignment)
2539 SubstTemplateTypeParmType(Parm, Replacement);
2540 Types.push_back(SubstParm);
2541 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2542 }
2543
2544 return QualType(SubstParm, 0);
2545}
2546
Douglas Gregorc3069d62011-01-14 02:55:32 +00002547/// \brief Retrieve a
2548QualType ASTContext::getSubstTemplateTypeParmPackType(
2549 const TemplateTypeParmType *Parm,
2550 const TemplateArgument &ArgPack) {
2551#ifndef NDEBUG
2552 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2553 PEnd = ArgPack.pack_end();
2554 P != PEnd; ++P) {
2555 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2556 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2557 }
2558#endif
2559
2560 llvm::FoldingSetNodeID ID;
2561 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2562 void *InsertPos = 0;
2563 if (SubstTemplateTypeParmPackType *SubstParm
2564 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2565 return QualType(SubstParm, 0);
2566
2567 QualType Canon;
2568 if (!Parm->isCanonicalUnqualified()) {
2569 Canon = getCanonicalType(QualType(Parm, 0));
2570 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2571 ArgPack);
2572 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2573 }
2574
2575 SubstTemplateTypeParmPackType *SubstParm
2576 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2577 ArgPack);
2578 Types.push_back(SubstParm);
2579 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2580 return QualType(SubstParm, 0);
2581}
2582
Douglas Gregorfab9d672009-02-05 23:33:38 +00002583/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002584/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002585/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002586QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002587 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002588 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002589 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002590 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002591 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002592 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002593 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2594
2595 if (TypeParm)
2596 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002597
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002598 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002599 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002600 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002601
2602 TemplateTypeParmType *TypeCheck
2603 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2604 assert(!TypeCheck && "Template type parameter canonical type broken");
2605 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002606 } else
John McCall6b304a02009-09-24 23:30:46 +00002607 TypeParm = new (*this, TypeAlignment)
2608 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002609
2610 Types.push_back(TypeParm);
2611 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2612
2613 return QualType(TypeParm, 0);
2614}
2615
John McCall3cb0ebd2010-03-10 03:28:59 +00002616TypeSourceInfo *
2617ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2618 SourceLocation NameLoc,
2619 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002620 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002621 assert(!Name.getAsDependentTemplateName() &&
2622 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002623 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002624
2625 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2626 TemplateSpecializationTypeLoc TL
2627 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002628 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002629 TL.setTemplateNameLoc(NameLoc);
2630 TL.setLAngleLoc(Args.getLAngleLoc());
2631 TL.setRAngleLoc(Args.getRAngleLoc());
2632 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2633 TL.setArgLocInfo(i, Args[i].getLocInfo());
2634 return DI;
2635}
2636
Mike Stump1eb44332009-09-09 15:08:12 +00002637QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002638ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002639 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002640 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002641 assert(!Template.getAsDependentTemplateName() &&
2642 "No dependent template names here!");
2643
John McCalld5532b62009-11-23 01:53:49 +00002644 unsigned NumArgs = Args.size();
2645
Chris Lattner5f9e2722011-07-23 10:55:15 +00002646 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002647 ArgVec.reserve(NumArgs);
2648 for (unsigned i = 0; i != NumArgs; ++i)
2649 ArgVec.push_back(Args[i].getArgument());
2650
John McCall31f17ec2010-04-27 00:57:59 +00002651 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002652 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002653}
2654
Douglas Gregorb70126a2012-02-03 17:16:23 +00002655#ifndef NDEBUG
2656static bool hasAnyPackExpansions(const TemplateArgument *Args,
2657 unsigned NumArgs) {
2658 for (unsigned I = 0; I != NumArgs; ++I)
2659 if (Args[I].isPackExpansion())
2660 return true;
2661
2662 return true;
2663}
2664#endif
2665
John McCall833ca992009-10-29 08:12:44 +00002666QualType
2667ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002668 const TemplateArgument *Args,
2669 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002670 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002671 assert(!Template.getAsDependentTemplateName() &&
2672 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002673 // Look through qualified template names.
2674 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2675 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002676
Douglas Gregorb70126a2012-02-03 17:16:23 +00002677 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00002678 Template.getAsTemplateDecl() &&
2679 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00002680 QualType CanonType;
2681 if (!Underlying.isNull())
2682 CanonType = getCanonicalType(Underlying);
2683 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00002684 // We can get here with an alias template when the specialization contains
2685 // a pack expansion that does not match up with a parameter pack.
2686 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2687 "Caller must compute aliased type");
2688 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00002689 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2690 NumArgs);
2691 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002692
Douglas Gregor1275ae02009-07-28 23:00:59 +00002693 // Allocate the (non-canonical) template specialization type, but don't
2694 // try to unique it: these types typically have location information that
2695 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002696 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2697 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00002698 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002699 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002700 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00002701 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2702 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002703
Douglas Gregor55f6b142009-02-09 18:46:07 +00002704 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002705 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002706}
2707
Mike Stump1eb44332009-09-09 15:08:12 +00002708QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002709ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2710 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002711 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002712 assert(!Template.getAsDependentTemplateName() &&
2713 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002714
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002715 // Look through qualified template names.
2716 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2717 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002718
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002719 // Build the canonical template specialization type.
2720 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002721 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002722 CanonArgs.reserve(NumArgs);
2723 for (unsigned I = 0; I != NumArgs; ++I)
2724 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2725
2726 // Determine whether this canonical template specialization type already
2727 // exists.
2728 llvm::FoldingSetNodeID ID;
2729 TemplateSpecializationType::Profile(ID, CanonTemplate,
2730 CanonArgs.data(), NumArgs, *this);
2731
2732 void *InsertPos = 0;
2733 TemplateSpecializationType *Spec
2734 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2735
2736 if (!Spec) {
2737 // Allocate a new canonical template specialization type.
2738 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2739 sizeof(TemplateArgument) * NumArgs),
2740 TypeAlignment);
2741 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2742 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002743 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002744 Types.push_back(Spec);
2745 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2746 }
2747
2748 assert(Spec->isDependentType() &&
2749 "Non-dependent template-id type must have a canonical type");
2750 return QualType(Spec, 0);
2751}
2752
2753QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002754ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2755 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002756 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002757 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002758 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002759
2760 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002761 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002762 if (T)
2763 return QualType(T, 0);
2764
Douglas Gregor789b1f62010-02-04 18:10:26 +00002765 QualType Canon = NamedType;
2766 if (!Canon.isCanonical()) {
2767 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002768 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2769 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002770 (void)CheckT;
2771 }
2772
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002773 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002774 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002775 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002776 return QualType(T, 0);
2777}
2778
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002779QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002780ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002781 llvm::FoldingSetNodeID ID;
2782 ParenType::Profile(ID, InnerType);
2783
2784 void *InsertPos = 0;
2785 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2786 if (T)
2787 return QualType(T, 0);
2788
2789 QualType Canon = InnerType;
2790 if (!Canon.isCanonical()) {
2791 Canon = getCanonicalType(InnerType);
2792 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2793 assert(!CheckT && "Paren canonical type broken");
2794 (void)CheckT;
2795 }
2796
2797 T = new (*this) ParenType(InnerType, Canon);
2798 Types.push_back(T);
2799 ParenTypes.InsertNode(T, InsertPos);
2800 return QualType(T, 0);
2801}
2802
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002803QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2804 NestedNameSpecifier *NNS,
2805 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002806 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002807 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2808
2809 if (Canon.isNull()) {
2810 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002811 ElaboratedTypeKeyword CanonKeyword = Keyword;
2812 if (Keyword == ETK_None)
2813 CanonKeyword = ETK_Typename;
2814
2815 if (CanonNNS != NNS || CanonKeyword != Keyword)
2816 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002817 }
2818
2819 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002820 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002821
2822 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002823 DependentNameType *T
2824 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002825 if (T)
2826 return QualType(T, 0);
2827
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002828 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002829 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002830 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002831 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002832}
2833
Mike Stump1eb44332009-09-09 15:08:12 +00002834QualType
John McCall33500952010-06-11 00:33:02 +00002835ASTContext::getDependentTemplateSpecializationType(
2836 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002837 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002838 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002839 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002840 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002841 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002842 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2843 ArgCopy.push_back(Args[I].getArgument());
2844 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2845 ArgCopy.size(),
2846 ArgCopy.data());
2847}
2848
2849QualType
2850ASTContext::getDependentTemplateSpecializationType(
2851 ElaboratedTypeKeyword Keyword,
2852 NestedNameSpecifier *NNS,
2853 const IdentifierInfo *Name,
2854 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002855 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002856 assert((!NNS || NNS->isDependent()) &&
2857 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002858
Douglas Gregor789b1f62010-02-04 18:10:26 +00002859 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002860 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2861 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002862
2863 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002864 DependentTemplateSpecializationType *T
2865 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002866 if (T)
2867 return QualType(T, 0);
2868
John McCall33500952010-06-11 00:33:02 +00002869 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002870
John McCall33500952010-06-11 00:33:02 +00002871 ElaboratedTypeKeyword CanonKeyword = Keyword;
2872 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2873
2874 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002875 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002876 for (unsigned I = 0; I != NumArgs; ++I) {
2877 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2878 if (!CanonArgs[I].structurallyEquals(Args[I]))
2879 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002880 }
2881
John McCall33500952010-06-11 00:33:02 +00002882 QualType Canon;
2883 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2884 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2885 Name, NumArgs,
2886 CanonArgs.data());
2887
2888 // Find the insert position again.
2889 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2890 }
2891
2892 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2893 sizeof(TemplateArgument) * NumArgs),
2894 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002895 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002896 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002897 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002898 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002899 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002900}
2901
Douglas Gregorcded4f62011-01-14 17:04:44 +00002902QualType ASTContext::getPackExpansionType(QualType Pattern,
2903 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002904 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002905 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002906
2907 assert(Pattern->containsUnexpandedParameterPack() &&
2908 "Pack expansions must expand one or more parameter packs");
2909 void *InsertPos = 0;
2910 PackExpansionType *T
2911 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2912 if (T)
2913 return QualType(T, 0);
2914
2915 QualType Canon;
2916 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00002917 Canon = getCanonicalType(Pattern);
2918 // The canonical type might not contain an unexpanded parameter pack, if it
2919 // contains an alias template specialization which ignores one of its
2920 // parameters.
2921 if (Canon->containsUnexpandedParameterPack()) {
2922 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002923
Richard Smithd8672ef2012-07-16 00:20:35 +00002924 // Find the insert position again, in case we inserted an element into
2925 // PackExpansionTypes and invalidated our insert position.
2926 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2927 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00002928 }
2929
Douglas Gregorcded4f62011-01-14 17:04:44 +00002930 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002931 Types.push_back(T);
2932 PackExpansionTypes.InsertNode(T, InsertPos);
2933 return QualType(T, 0);
2934}
2935
Chris Lattner88cb27a2008-04-07 04:56:42 +00002936/// CmpProtocolNames - Comparison predicate for sorting protocols
2937/// alphabetically.
2938static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2939 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002940 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002941}
2942
John McCallc12c5bb2010-05-15 11:32:37 +00002943static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002944 unsigned NumProtocols) {
2945 if (NumProtocols == 0) return true;
2946
Douglas Gregor61cc2962012-01-02 02:00:30 +00002947 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2948 return false;
2949
John McCall54e14c42009-10-22 22:37:11 +00002950 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00002951 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2952 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00002953 return false;
2954 return true;
2955}
2956
2957static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002958 unsigned &NumProtocols) {
2959 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002960
Chris Lattner88cb27a2008-04-07 04:56:42 +00002961 // Sort protocols, keyed by name.
2962 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2963
Douglas Gregor61cc2962012-01-02 02:00:30 +00002964 // Canonicalize.
2965 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2966 Protocols[I] = Protocols[I]->getCanonicalDecl();
2967
Chris Lattner88cb27a2008-04-07 04:56:42 +00002968 // Remove duplicates.
2969 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2970 NumProtocols = ProtocolsEnd-Protocols;
2971}
2972
John McCallc12c5bb2010-05-15 11:32:37 +00002973QualType ASTContext::getObjCObjectType(QualType BaseType,
2974 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002975 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002976 // If the base type is an interface and there aren't any protocols
2977 // to add, then the interface type will do just fine.
2978 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2979 return BaseType;
2980
2981 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002982 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002983 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002984 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002985 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2986 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002987
John McCallc12c5bb2010-05-15 11:32:37 +00002988 // Build the canonical type, which has the canonical base type and
2989 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002990 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002991 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2992 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2993 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002994 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002995 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002996 unsigned UniqueCount = NumProtocols;
2997
John McCall54e14c42009-10-22 22:37:11 +00002998 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002999 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3000 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003001 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003002 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3003 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003004 }
3005
3006 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003007 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3008 }
3009
3010 unsigned Size = sizeof(ObjCObjectTypeImpl);
3011 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3012 void *Mem = Allocate(Size, TypeAlignment);
3013 ObjCObjectTypeImpl *T =
3014 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3015
3016 Types.push_back(T);
3017 ObjCObjectTypes.InsertNode(T, InsertPos);
3018 return QualType(T, 0);
3019}
3020
3021/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3022/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003023QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003024 llvm::FoldingSetNodeID ID;
3025 ObjCObjectPointerType::Profile(ID, ObjectT);
3026
3027 void *InsertPos = 0;
3028 if (ObjCObjectPointerType *QT =
3029 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3030 return QualType(QT, 0);
3031
3032 // Find the canonical object type.
3033 QualType Canonical;
3034 if (!ObjectT.isCanonical()) {
3035 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3036
3037 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003038 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3039 }
3040
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003041 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003042 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3043 ObjCObjectPointerType *QType =
3044 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003045
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003046 Types.push_back(QType);
3047 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003048 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003049}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003050
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003051/// getObjCInterfaceType - Return the unique reference to the type for the
3052/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003053QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3054 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003055 if (Decl->TypeForDecl)
3056 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003057
Douglas Gregor0af55012011-12-16 03:12:41 +00003058 if (PrevDecl) {
3059 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3060 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3061 return QualType(PrevDecl->TypeForDecl, 0);
3062 }
3063
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003064 // Prefer the definition, if there is one.
3065 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3066 Decl = Def;
3067
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003068 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3069 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3070 Decl->TypeForDecl = T;
3071 Types.push_back(T);
3072 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003073}
3074
Douglas Gregor72564e72009-02-26 23:50:07 +00003075/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3076/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003077/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003078/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003079/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003080QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003081 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003082 if (tofExpr->isTypeDependent()) {
3083 llvm::FoldingSetNodeID ID;
3084 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003085
Douglas Gregorb1975722009-07-30 23:18:24 +00003086 void *InsertPos = 0;
3087 DependentTypeOfExprType *Canon
3088 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3089 if (Canon) {
3090 // We already have a "canonical" version of an identical, dependent
3091 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003092 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003093 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003094 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003095 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003096 Canon
3097 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003098 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3099 toe = Canon;
3100 }
3101 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003102 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003103 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003104 }
Steve Naroff9752f252007-08-01 18:02:17 +00003105 Types.push_back(toe);
3106 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003107}
3108
Steve Naroff9752f252007-08-01 18:02:17 +00003109/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3110/// TypeOfType AST's. The only motivation to unique these nodes would be
3111/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003112/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003113/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003114QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003115 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003116 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003117 Types.push_back(tot);
3118 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003119}
3120
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003121
Anders Carlsson395b4752009-06-24 19:06:50 +00003122/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3123/// DecltypeType AST's. The only motivation to unique these nodes would be
3124/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003125/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003126/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003127QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003128 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003129
3130 // C++0x [temp.type]p2:
3131 // If an expression e involves a template parameter, decltype(e) denotes a
3132 // unique dependent type. Two such decltype-specifiers refer to the same
3133 // type only if their expressions are equivalent (14.5.6.1).
3134 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003135 llvm::FoldingSetNodeID ID;
3136 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003137
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003138 void *InsertPos = 0;
3139 DependentDecltypeType *Canon
3140 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3141 if (Canon) {
3142 // We already have a "canonical" version of an equivalent, dependent
3143 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003144 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003145 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003146 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003147 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003148 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003149 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3150 dt = Canon;
3151 }
3152 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003153 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3154 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003155 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003156 Types.push_back(dt);
3157 return QualType(dt, 0);
3158}
3159
Sean Huntca63c202011-05-24 22:41:36 +00003160/// getUnaryTransformationType - We don't unique these, since the memory
3161/// savings are minimal and these are rare.
3162QualType ASTContext::getUnaryTransformType(QualType BaseType,
3163 QualType UnderlyingType,
3164 UnaryTransformType::UTTKind Kind)
3165 const {
3166 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003167 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3168 Kind,
3169 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003170 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003171 Types.push_back(Ty);
3172 return QualType(Ty, 0);
3173}
3174
Richard Smith483b9f32011-02-21 20:05:19 +00003175/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00003176QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00003177 void *InsertPos = 0;
3178 if (!DeducedType.isNull()) {
3179 // Look in the folding set for an existing type.
3180 llvm::FoldingSetNodeID ID;
3181 AutoType::Profile(ID, DeducedType);
3182 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3183 return QualType(AT, 0);
3184 }
3185
3186 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3187 Types.push_back(AT);
3188 if (InsertPos)
3189 AutoTypes.InsertNode(AT, InsertPos);
3190 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003191}
3192
Eli Friedmanb001de72011-10-06 23:00:33 +00003193/// getAtomicType - Return the uniqued reference to the atomic type for
3194/// the given value type.
3195QualType ASTContext::getAtomicType(QualType T) const {
3196 // Unique pointers, to guarantee there is only one pointer of a particular
3197 // structure.
3198 llvm::FoldingSetNodeID ID;
3199 AtomicType::Profile(ID, T);
3200
3201 void *InsertPos = 0;
3202 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3203 return QualType(AT, 0);
3204
3205 // If the atomic value type isn't canonical, this won't be a canonical type
3206 // either, so fill in the canonical type field.
3207 QualType Canonical;
3208 if (!T.isCanonical()) {
3209 Canonical = getAtomicType(getCanonicalType(T));
3210
3211 // Get the new insert position for the node we care about.
3212 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3213 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3214 }
3215 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3216 Types.push_back(New);
3217 AtomicTypes.InsertNode(New, InsertPos);
3218 return QualType(New, 0);
3219}
3220
Richard Smithad762fc2011-04-14 22:09:26 +00003221/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3222QualType ASTContext::getAutoDeductType() const {
3223 if (AutoDeductTy.isNull())
3224 AutoDeductTy = getAutoType(QualType());
3225 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3226 return AutoDeductTy;
3227}
3228
3229/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3230QualType ASTContext::getAutoRRefDeductType() const {
3231 if (AutoRRefDeductTy.isNull())
3232 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3233 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3234 return AutoRRefDeductTy;
3235}
3236
Reid Spencer5f016e22007-07-11 17:01:13 +00003237/// getTagDeclType - Return the unique reference to the type for the
3238/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003239QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003240 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003241 // FIXME: What is the design on getTagDeclType when it requires casting
3242 // away const? mutable?
3243 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003244}
3245
Mike Stump1eb44332009-09-09 15:08:12 +00003246/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3247/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3248/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003249CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003250 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003251}
3252
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003253/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3254CanQualType ASTContext::getIntMaxType() const {
3255 return getFromTargetType(Target->getIntMaxType());
3256}
3257
3258/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3259CanQualType ASTContext::getUIntMaxType() const {
3260 return getFromTargetType(Target->getUIntMaxType());
3261}
3262
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003263/// getSignedWCharType - Return the type of "signed wchar_t".
3264/// Used when in C++, as a GCC extension.
3265QualType ASTContext::getSignedWCharType() const {
3266 // FIXME: derive from "Target" ?
3267 return WCharTy;
3268}
3269
3270/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3271/// Used when in C++, as a GCC extension.
3272QualType ASTContext::getUnsignedWCharType() const {
3273 // FIXME: derive from "Target" ?
3274 return UnsignedIntTy;
3275}
3276
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003277/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003278/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3279QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003280 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003281}
3282
Chris Lattnere6327742008-04-02 05:18:44 +00003283//===----------------------------------------------------------------------===//
3284// Type Operators
3285//===----------------------------------------------------------------------===//
3286
Jay Foad4ba2a172011-01-12 09:06:06 +00003287CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003288 // Push qualifiers into arrays, and then discard any remaining
3289 // qualifiers.
3290 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003291 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003292 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003293 QualType Result;
3294 if (isa<ArrayType>(Ty)) {
3295 Result = getArrayDecayedType(QualType(Ty,0));
3296 } else if (isa<FunctionType>(Ty)) {
3297 Result = getPointerType(QualType(Ty, 0));
3298 } else {
3299 Result = QualType(Ty, 0);
3300 }
3301
3302 return CanQualType::CreateUnsafe(Result);
3303}
3304
John McCall62c28c82011-01-18 07:41:22 +00003305QualType ASTContext::getUnqualifiedArrayType(QualType type,
3306 Qualifiers &quals) {
3307 SplitQualType splitType = type.getSplitUnqualifiedType();
3308
3309 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3310 // the unqualified desugared type and then drops it on the floor.
3311 // We then have to strip that sugar back off with
3312 // getUnqualifiedDesugaredType(), which is silly.
3313 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003314 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003315
3316 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003317 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003318 quals = splitType.Quals;
3319 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003320 }
3321
John McCall62c28c82011-01-18 07:41:22 +00003322 // Otherwise, recurse on the array's element type.
3323 QualType elementType = AT->getElementType();
3324 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3325
3326 // If that didn't change the element type, AT has no qualifiers, so we
3327 // can just use the results in splitType.
3328 if (elementType == unqualElementType) {
3329 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003330 quals = splitType.Quals;
3331 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003332 }
3333
3334 // Otherwise, add in the qualifiers from the outermost type, then
3335 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003336 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003337
Douglas Gregor9dadd942010-05-17 18:45:21 +00003338 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003339 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003340 CAT->getSizeModifier(), 0);
3341 }
3342
Douglas Gregor9dadd942010-05-17 18:45:21 +00003343 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003344 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003345 }
3346
Douglas Gregor9dadd942010-05-17 18:45:21 +00003347 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003348 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003349 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003350 VAT->getSizeModifier(),
3351 VAT->getIndexTypeCVRQualifiers(),
3352 VAT->getBracketsRange());
3353 }
3354
3355 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003356 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003357 DSAT->getSizeModifier(), 0,
3358 SourceRange());
3359}
3360
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003361/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3362/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3363/// they point to and return true. If T1 and T2 aren't pointer types
3364/// or pointer-to-member types, or if they are not similar at this
3365/// level, returns false and leaves T1 and T2 unchanged. Top-level
3366/// qualifiers on T1 and T2 are ignored. This function will typically
3367/// be called in a loop that successively "unwraps" pointer and
3368/// pointer-to-member types to compare them at each level.
3369bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3370 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3371 *T2PtrType = T2->getAs<PointerType>();
3372 if (T1PtrType && T2PtrType) {
3373 T1 = T1PtrType->getPointeeType();
3374 T2 = T2PtrType->getPointeeType();
3375 return true;
3376 }
3377
3378 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3379 *T2MPType = T2->getAs<MemberPointerType>();
3380 if (T1MPType && T2MPType &&
3381 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3382 QualType(T2MPType->getClass(), 0))) {
3383 T1 = T1MPType->getPointeeType();
3384 T2 = T2MPType->getPointeeType();
3385 return true;
3386 }
3387
David Blaikie4e4d0842012-03-11 07:00:24 +00003388 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003389 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3390 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3391 if (T1OPType && T2OPType) {
3392 T1 = T1OPType->getPointeeType();
3393 T2 = T2OPType->getPointeeType();
3394 return true;
3395 }
3396 }
3397
3398 // FIXME: Block pointers, too?
3399
3400 return false;
3401}
3402
Jay Foad4ba2a172011-01-12 09:06:06 +00003403DeclarationNameInfo
3404ASTContext::getNameForTemplate(TemplateName Name,
3405 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003406 switch (Name.getKind()) {
3407 case TemplateName::QualifiedTemplate:
3408 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003409 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003410 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3411 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003412
John McCall14606042011-06-30 08:33:18 +00003413 case TemplateName::OverloadedTemplate: {
3414 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3415 // DNInfo work in progress: CHECKME: what about DNLoc?
3416 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3417 }
3418
3419 case TemplateName::DependentTemplate: {
3420 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003421 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003422 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003423 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3424 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003425 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003426 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3427 // DNInfo work in progress: FIXME: source locations?
3428 DeclarationNameLoc DNLoc;
3429 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3430 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3431 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003432 }
3433 }
3434
John McCall14606042011-06-30 08:33:18 +00003435 case TemplateName::SubstTemplateTemplateParm: {
3436 SubstTemplateTemplateParmStorage *subst
3437 = Name.getAsSubstTemplateTemplateParm();
3438 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3439 NameLoc);
3440 }
3441
3442 case TemplateName::SubstTemplateTemplateParmPack: {
3443 SubstTemplateTemplateParmPackStorage *subst
3444 = Name.getAsSubstTemplateTemplateParmPack();
3445 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3446 NameLoc);
3447 }
3448 }
3449
3450 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003451}
3452
Jay Foad4ba2a172011-01-12 09:06:06 +00003453TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003454 switch (Name.getKind()) {
3455 case TemplateName::QualifiedTemplate:
3456 case TemplateName::Template: {
3457 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003458 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003459 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003460 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3461
3462 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003463 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003464 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003465
John McCall14606042011-06-30 08:33:18 +00003466 case TemplateName::OverloadedTemplate:
3467 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003468
John McCall14606042011-06-30 08:33:18 +00003469 case TemplateName::DependentTemplate: {
3470 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3471 assert(DTN && "Non-dependent template names must refer to template decls.");
3472 return DTN->CanonicalTemplateName;
3473 }
3474
3475 case TemplateName::SubstTemplateTemplateParm: {
3476 SubstTemplateTemplateParmStorage *subst
3477 = Name.getAsSubstTemplateTemplateParm();
3478 return getCanonicalTemplateName(subst->getReplacement());
3479 }
3480
3481 case TemplateName::SubstTemplateTemplateParmPack: {
3482 SubstTemplateTemplateParmPackStorage *subst
3483 = Name.getAsSubstTemplateTemplateParmPack();
3484 TemplateTemplateParmDecl *canonParameter
3485 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3486 TemplateArgument canonArgPack
3487 = getCanonicalTemplateArgument(subst->getArgumentPack());
3488 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3489 }
3490 }
3491
3492 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003493}
3494
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003495bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3496 X = getCanonicalTemplateName(X);
3497 Y = getCanonicalTemplateName(Y);
3498 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3499}
3500
Mike Stump1eb44332009-09-09 15:08:12 +00003501TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003502ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003503 switch (Arg.getKind()) {
3504 case TemplateArgument::Null:
3505 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003506
Douglas Gregor1275ae02009-07-28 23:00:59 +00003507 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003508 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003509
Douglas Gregord2008e22012-04-06 22:40:38 +00003510 case TemplateArgument::Declaration: {
3511 if (Decl *D = Arg.getAsDecl())
3512 return TemplateArgument(D->getCanonicalDecl());
3513 return TemplateArgument((Decl*)0);
3514 }
Mike Stump1eb44332009-09-09 15:08:12 +00003515
Douglas Gregor788cd062009-11-11 01:00:40 +00003516 case TemplateArgument::Template:
3517 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003518
3519 case TemplateArgument::TemplateExpansion:
3520 return TemplateArgument(getCanonicalTemplateName(
3521 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003522 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003523
Douglas Gregor1275ae02009-07-28 23:00:59 +00003524 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00003525 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003526
Douglas Gregor1275ae02009-07-28 23:00:59 +00003527 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003528 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003529
Douglas Gregor1275ae02009-07-28 23:00:59 +00003530 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003531 if (Arg.pack_size() == 0)
3532 return Arg;
3533
Douglas Gregor910f8002010-11-07 23:05:16 +00003534 TemplateArgument *CanonArgs
3535 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003536 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003537 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003538 AEnd = Arg.pack_end();
3539 A != AEnd; (void)++A, ++Idx)
3540 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003541
Douglas Gregor910f8002010-11-07 23:05:16 +00003542 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003543 }
3544 }
3545
3546 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003547 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003548}
3549
Douglas Gregord57959a2009-03-27 23:10:48 +00003550NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003551ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003552 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003553 return 0;
3554
3555 switch (NNS->getKind()) {
3556 case NestedNameSpecifier::Identifier:
3557 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003558 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003559 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3560 NNS->getAsIdentifier());
3561
3562 case NestedNameSpecifier::Namespace:
3563 // A namespace is canonical; build a nested-name-specifier with
3564 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003565 return NestedNameSpecifier::Create(*this, 0,
3566 NNS->getAsNamespace()->getOriginalNamespace());
3567
3568 case NestedNameSpecifier::NamespaceAlias:
3569 // A namespace is canonical; build a nested-name-specifier with
3570 // this namespace and no prefix.
3571 return NestedNameSpecifier::Create(*this, 0,
3572 NNS->getAsNamespaceAlias()->getNamespace()
3573 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003574
3575 case NestedNameSpecifier::TypeSpec:
3576 case NestedNameSpecifier::TypeSpecWithTemplate: {
3577 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003578
3579 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3580 // break it apart into its prefix and identifier, then reconsititute those
3581 // as the canonical nested-name-specifier. This is required to canonicalize
3582 // a dependent nested-name-specifier involving typedefs of dependent-name
3583 // types, e.g.,
3584 // typedef typename T::type T1;
3585 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00003586 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3587 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00003588 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00003589
Eli Friedman16412ef2012-03-03 04:09:56 +00003590 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3591 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3592 // first place?
John McCall3b657512011-01-19 10:06:00 +00003593 return NestedNameSpecifier::Create(*this, 0, false,
3594 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003595 }
3596
3597 case NestedNameSpecifier::Global:
3598 // The global specifier is canonical and unique.
3599 return NNS;
3600 }
3601
David Blaikie7530c032012-01-17 06:56:22 +00003602 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003603}
3604
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003605
Jay Foad4ba2a172011-01-12 09:06:06 +00003606const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003607 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003608 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003609 // Handle the common positive case fast.
3610 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3611 return AT;
3612 }
Mike Stump1eb44332009-09-09 15:08:12 +00003613
John McCall0953e762009-09-24 19:53:00 +00003614 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003615 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003616 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003617
John McCall0953e762009-09-24 19:53:00 +00003618 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003619 // implements C99 6.7.3p8: "If the specification of an array type includes
3620 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003621
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003622 // If we get here, we either have type qualifiers on the type, or we have
3623 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003624 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003625
John McCall3b657512011-01-19 10:06:00 +00003626 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003627 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00003628
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003629 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00003630 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00003631 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003632 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003633
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003634 // Otherwise, we have an array and we have qualifiers on it. Push the
3635 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003636 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003637
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003638 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3639 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3640 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003641 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003642 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3643 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3644 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003645 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003646
Mike Stump1eb44332009-09-09 15:08:12 +00003647 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003648 = dyn_cast<DependentSizedArrayType>(ATy))
3649 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003650 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003651 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003652 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003653 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003654 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003655
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003656 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003657 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003658 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003659 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003660 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003661 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003662}
3663
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003664QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003665 // C99 6.7.5.3p7:
3666 // A declaration of a parameter as "array of type" shall be
3667 // adjusted to "qualified pointer to type", where the type
3668 // qualifiers (if any) are those specified within the [ and ] of
3669 // the array type derivation.
3670 if (T->isArrayType())
3671 return getArrayDecayedType(T);
3672
3673 // C99 6.7.5.3p8:
3674 // A declaration of a parameter as "function returning type"
3675 // shall be adjusted to "pointer to function returning type", as
3676 // in 6.3.2.1.
3677 if (T->isFunctionType())
3678 return getPointerType(T);
3679
3680 return T;
3681}
3682
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003683QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003684 T = getVariableArrayDecayedType(T);
3685 T = getAdjustedParameterType(T);
3686 return T.getUnqualifiedType();
3687}
3688
Chris Lattnere6327742008-04-02 05:18:44 +00003689/// getArrayDecayedType - Return the properly qualified result of decaying the
3690/// specified array type to a pointer. This operation is non-trivial when
3691/// handling typedefs etc. The canonical type of "T" must be an array type,
3692/// this returns a pointer to a properly qualified element of the array.
3693///
3694/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003695QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003696 // Get the element type with 'getAsArrayType' so that we don't lose any
3697 // typedefs in the element type of the array. This also handles propagation
3698 // of type qualifiers from the array type into the element type if present
3699 // (C99 6.7.3p8).
3700 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3701 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003702
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003703 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003704
3705 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003706 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003707}
3708
John McCall3b657512011-01-19 10:06:00 +00003709QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3710 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003711}
3712
John McCall3b657512011-01-19 10:06:00 +00003713QualType ASTContext::getBaseElementType(QualType type) const {
3714 Qualifiers qs;
3715 while (true) {
3716 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003717 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00003718 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003719
John McCall3b657512011-01-19 10:06:00 +00003720 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00003721 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00003722 }
Mike Stump1eb44332009-09-09 15:08:12 +00003723
John McCall3b657512011-01-19 10:06:00 +00003724 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003725}
3726
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003727/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003728uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003729ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3730 uint64_t ElementCount = 1;
3731 do {
3732 ElementCount *= CA->getSize().getZExtValue();
3733 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3734 } while (CA);
3735 return ElementCount;
3736}
3737
Reid Spencer5f016e22007-07-11 17:01:13 +00003738/// getFloatingRank - Return a relative rank for floating point types.
3739/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003740static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003741 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003742 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003743
John McCall183700f2009-09-21 23:43:11 +00003744 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3745 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003746 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003747 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003748 case BuiltinType::Float: return FloatRank;
3749 case BuiltinType::Double: return DoubleRank;
3750 case BuiltinType::LongDouble: return LongDoubleRank;
3751 }
3752}
3753
Mike Stump1eb44332009-09-09 15:08:12 +00003754/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3755/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003756/// 'typeDomain' is a real floating point or complex type.
3757/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003758QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3759 QualType Domain) const {
3760 FloatingRank EltRank = getFloatingRank(Size);
3761 if (Domain->isComplexType()) {
3762 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003763 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00003764 case FloatRank: return FloatComplexTy;
3765 case DoubleRank: return DoubleComplexTy;
3766 case LongDoubleRank: return LongDoubleComplexTy;
3767 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003768 }
Chris Lattner1361b112008-04-06 23:58:54 +00003769
3770 assert(Domain->isRealFloatingType() && "Unknown domain!");
3771 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003772 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattner1361b112008-04-06 23:58:54 +00003773 case FloatRank: return FloatTy;
3774 case DoubleRank: return DoubleTy;
3775 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003776 }
David Blaikie561d3ab2012-01-17 02:30:50 +00003777 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00003778}
3779
Chris Lattner7cfeb082008-04-06 23:55:33 +00003780/// getFloatingTypeOrder - Compare the rank of the two specified floating
3781/// point types, ignoring the domain of the type (i.e. 'double' ==
3782/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003783/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003784int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003785 FloatingRank LHSR = getFloatingRank(LHS);
3786 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003787
Chris Lattnera75cea32008-04-06 23:38:49 +00003788 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003789 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003790 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003791 return 1;
3792 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003793}
3794
Chris Lattnerf52ab252008-04-06 22:59:24 +00003795/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3796/// routine will assert if passed a built-in type that isn't an integer or enum,
3797/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003798unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003799 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003800
Chris Lattnerf52ab252008-04-06 22:59:24 +00003801 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003802 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003803 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003804 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003805 case BuiltinType::Char_S:
3806 case BuiltinType::Char_U:
3807 case BuiltinType::SChar:
3808 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003809 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003810 case BuiltinType::Short:
3811 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003812 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003813 case BuiltinType::Int:
3814 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003815 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003816 case BuiltinType::Long:
3817 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003818 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003819 case BuiltinType::LongLong:
3820 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003821 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003822 case BuiltinType::Int128:
3823 case BuiltinType::UInt128:
3824 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003825 }
3826}
3827
Eli Friedman04e83572009-08-20 04:21:42 +00003828/// \brief Whether this is a promotable bitfield reference according
3829/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3830///
3831/// \returns the type this bit-field will promote to, or NULL if no
3832/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003833QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003834 if (E->isTypeDependent() || E->isValueDependent())
3835 return QualType();
3836
Eli Friedman04e83572009-08-20 04:21:42 +00003837 FieldDecl *Field = E->getBitField();
3838 if (!Field)
3839 return QualType();
3840
3841 QualType FT = Field->getType();
3842
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003843 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00003844 uint64_t IntSize = getTypeSize(IntTy);
3845 // GCC extension compatibility: if the bit-field size is less than or equal
3846 // to the size of int, it gets promoted no matter what its type is.
3847 // For instance, unsigned long bf : 4 gets promoted to signed int.
3848 if (BitWidth < IntSize)
3849 return IntTy;
3850
3851 if (BitWidth == IntSize)
3852 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3853
3854 // Types bigger than int are not subject to promotions, and therefore act
3855 // like the base type.
3856 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3857 // is ridiculous.
3858 return QualType();
3859}
3860
Eli Friedmana95d7572009-08-19 07:44:53 +00003861/// getPromotedIntegerType - Returns the type that Promotable will
3862/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3863/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003864QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003865 assert(!Promotable.isNull());
3866 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003867 if (const EnumType *ET = Promotable->getAs<EnumType>())
3868 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00003869
3870 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3871 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3872 // (3.9.1) can be converted to a prvalue of the first of the following
3873 // types that can represent all the values of its underlying type:
3874 // int, unsigned int, long int, unsigned long int, long long int, or
3875 // unsigned long long int [...]
3876 // FIXME: Is there some better way to compute this?
3877 if (BT->getKind() == BuiltinType::WChar_S ||
3878 BT->getKind() == BuiltinType::WChar_U ||
3879 BT->getKind() == BuiltinType::Char16 ||
3880 BT->getKind() == BuiltinType::Char32) {
3881 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3882 uint64_t FromSize = getTypeSize(BT);
3883 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3884 LongLongTy, UnsignedLongLongTy };
3885 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3886 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3887 if (FromSize < ToSize ||
3888 (FromSize == ToSize &&
3889 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3890 return PromoteTypes[Idx];
3891 }
3892 llvm_unreachable("char type should fit into long long");
3893 }
3894 }
3895
3896 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00003897 if (Promotable->isSignedIntegerType())
3898 return IntTy;
3899 uint64_t PromotableSize = getTypeSize(Promotable);
3900 uint64_t IntSize = getTypeSize(IntTy);
3901 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3902 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3903}
3904
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003905/// \brief Recurses in pointer/array types until it finds an objc retainable
3906/// type and returns its ownership.
3907Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3908 while (!T.isNull()) {
3909 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3910 return T.getObjCLifetime();
3911 if (T->isArrayType())
3912 T = getBaseElementType(T);
3913 else if (const PointerType *PT = T->getAs<PointerType>())
3914 T = PT->getPointeeType();
3915 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003916 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003917 else
3918 break;
3919 }
3920
3921 return Qualifiers::OCL_None;
3922}
3923
Mike Stump1eb44332009-09-09 15:08:12 +00003924/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003925/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003926/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003927int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003928 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3929 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003930 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003931
Chris Lattnerf52ab252008-04-06 22:59:24 +00003932 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3933 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003934
Chris Lattner7cfeb082008-04-06 23:55:33 +00003935 unsigned LHSRank = getIntegerRank(LHSC);
3936 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003937
Chris Lattner7cfeb082008-04-06 23:55:33 +00003938 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3939 if (LHSRank == RHSRank) return 0;
3940 return LHSRank > RHSRank ? 1 : -1;
3941 }
Mike Stump1eb44332009-09-09 15:08:12 +00003942
Chris Lattner7cfeb082008-04-06 23:55:33 +00003943 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3944 if (LHSUnsigned) {
3945 // If the unsigned [LHS] type is larger, return it.
3946 if (LHSRank >= RHSRank)
3947 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003948
Chris Lattner7cfeb082008-04-06 23:55:33 +00003949 // If the signed type can represent all values of the unsigned type, it
3950 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003951 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003952 return -1;
3953 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003954
Chris Lattner7cfeb082008-04-06 23:55:33 +00003955 // If the unsigned [RHS] type is larger, return it.
3956 if (RHSRank >= LHSRank)
3957 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003958
Chris Lattner7cfeb082008-04-06 23:55:33 +00003959 // If the signed type can represent all values of the unsigned type, it
3960 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003961 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003962 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003963}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003964
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003965static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003966CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3967 DeclContext *DC, IdentifierInfo *Id) {
3968 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00003969 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003970 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003971 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003972 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003973}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003974
Mike Stump1eb44332009-09-09 15:08:12 +00003975// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003976QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003977 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003978 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003979 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003980 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003981 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003982
Anders Carlssonf06273f2007-11-19 00:25:30 +00003983 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003984
Anders Carlsson71993dd2007-08-17 05:31:46 +00003985 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003986 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003987 // int flags;
3988 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003989 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003990 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003991 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003992 FieldTypes[3] = LongTy;
3993
Anders Carlsson71993dd2007-08-17 05:31:46 +00003994 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003995 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003996 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003997 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003998 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003999 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004000 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004001 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004002 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004003 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004004 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004005 }
4006
Douglas Gregor838db382010-02-11 01:19:42 +00004007 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004008 }
Mike Stump1eb44332009-09-09 15:08:12 +00004009
Anders Carlsson71993dd2007-08-17 05:31:46 +00004010 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004011}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004012
Douglas Gregor319ac892009-04-23 22:29:11 +00004013void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004014 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004015 assert(Rec && "Invalid CFConstantStringType");
4016 CFConstantStringTypeDecl = Rec->getDecl();
4017}
4018
Jay Foad4ba2a172011-01-12 09:06:06 +00004019QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004020 if (BlockDescriptorType)
4021 return getTagDeclType(BlockDescriptorType);
4022
4023 RecordDecl *T;
4024 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004025 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004026 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004027 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004028
4029 QualType FieldTypes[] = {
4030 UnsignedLongTy,
4031 UnsignedLongTy,
4032 };
4033
4034 const char *FieldNames[] = {
4035 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004036 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004037 };
4038
4039 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004040 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004041 SourceLocation(),
4042 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004043 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004044 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004045 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004046 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004047 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004048 T->addDecl(Field);
4049 }
4050
Douglas Gregor838db382010-02-11 01:19:42 +00004051 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004052
4053 BlockDescriptorType = T;
4054
4055 return getTagDeclType(BlockDescriptorType);
4056}
4057
Jay Foad4ba2a172011-01-12 09:06:06 +00004058QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004059 if (BlockDescriptorExtendedType)
4060 return getTagDeclType(BlockDescriptorExtendedType);
4061
4062 RecordDecl *T;
4063 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004064 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004065 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004066 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004067
4068 QualType FieldTypes[] = {
4069 UnsignedLongTy,
4070 UnsignedLongTy,
4071 getPointerType(VoidPtrTy),
4072 getPointerType(VoidPtrTy)
4073 };
4074
4075 const char *FieldNames[] = {
4076 "reserved",
4077 "Size",
4078 "CopyFuncPtr",
4079 "DestroyFuncPtr"
4080 };
4081
4082 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004083 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004084 SourceLocation(),
4085 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004086 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004087 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004088 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004089 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004090 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004091 T->addDecl(Field);
4092 }
4093
Douglas Gregor838db382010-02-11 01:19:42 +00004094 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004095
4096 BlockDescriptorExtendedType = T;
4097
4098 return getTagDeclType(BlockDescriptorExtendedType);
4099}
4100
Jay Foad4ba2a172011-01-12 09:06:06 +00004101bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00004102 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004103 return true;
David Blaikie4e4d0842012-03-11 07:00:24 +00004104 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004105 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4106 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00004107 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004108
4109 }
4110 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004111 return false;
4112}
4113
Jay Foad4ba2a172011-01-12 09:06:06 +00004114QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00004115ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004116 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00004117 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004118 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00004119 // unsigned int __flags;
4120 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00004121 // void *__copy_helper; // as needed
4122 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004123 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00004124 // } *
4125
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004126 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4127
4128 // FIXME: Move up
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00004129 SmallString<36> Name;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00004130 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4131 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004132 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004133 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004134 T->startDefinition();
4135 QualType Int32Ty = IntTy;
4136 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4137 QualType FieldTypes[] = {
4138 getPointerType(VoidPtrTy),
4139 getPointerType(getTagDeclType(T)),
4140 Int32Ty,
4141 Int32Ty,
4142 getPointerType(VoidPtrTy),
4143 getPointerType(VoidPtrTy),
4144 Ty
4145 };
4146
Chris Lattner5f9e2722011-07-23 10:55:15 +00004147 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004148 "__isa",
4149 "__forwarding",
4150 "__flags",
4151 "__size",
4152 "__copy_helper",
4153 "__destroy_helper",
4154 DeclName,
4155 };
4156
4157 for (size_t i = 0; i < 7; ++i) {
4158 if (!HasCopyAndDispose && i >=4 && i <= 5)
4159 continue;
4160 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004161 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004162 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004163 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004164 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004165 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004166 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004167 T->addDecl(Field);
4168 }
4169
Douglas Gregor838db382010-02-11 01:19:42 +00004170 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004171
4172 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00004173}
4174
Douglas Gregore97179c2011-09-08 01:46:34 +00004175TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4176 if (!ObjCInstanceTypeDecl)
4177 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4178 getTranslationUnitDecl(),
4179 SourceLocation(),
4180 SourceLocation(),
4181 &Idents.get("instancetype"),
4182 getTrivialTypeSourceInfo(getObjCIdType()));
4183 return ObjCInstanceTypeDecl;
4184}
4185
Anders Carlssone8c49532007-10-29 06:33:42 +00004186// This returns true if a type has been typedefed to BOOL:
4187// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004188static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004189 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004190 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4191 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004192
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004193 return false;
4194}
4195
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004196/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004197/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004198CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004199 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4200 return CharUnits::Zero();
4201
Ken Dyck199c3d62010-01-11 17:06:35 +00004202 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004203
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004204 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004205 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004206 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004207 // Treat arrays as pointers, since that's how they're passed in.
4208 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004209 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004210 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004211}
4212
4213static inline
4214std::string charUnitsToString(const CharUnits &CU) {
4215 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004216}
4217
John McCall6b5a61b2011-02-07 10:33:21 +00004218/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004219/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004220std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4221 std::string S;
4222
David Chisnall5e530af2009-11-17 19:33:30 +00004223 const BlockDecl *Decl = Expr->getBlockDecl();
4224 QualType BlockTy =
4225 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4226 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004227 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004228 // Compute size of all parameters.
4229 // Start with computing size of a pointer in number of bytes.
4230 // FIXME: There might(should) be a better way of doing this computation!
4231 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004232 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4233 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004234 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004235 E = Decl->param_end(); PI != E; ++PI) {
4236 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004237 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004238 if (sz.isZero())
4239 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004240 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004241 ParmOffset += sz;
4242 }
4243 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004244 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004245 // Block pointer and offset.
4246 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004247
4248 // Argument types.
4249 ParmOffset = PtrSize;
4250 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4251 Decl->param_end(); PI != E; ++PI) {
4252 ParmVarDecl *PVDecl = *PI;
4253 QualType PType = PVDecl->getOriginalType();
4254 if (const ArrayType *AT =
4255 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4256 // Use array's original type only if it has known number of
4257 // elements.
4258 if (!isa<ConstantArrayType>(AT))
4259 PType = PVDecl->getType();
4260 } else if (PType->isFunctionType())
4261 PType = PVDecl->getType();
4262 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004263 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004264 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004265 }
John McCall6b5a61b2011-02-07 10:33:21 +00004266
4267 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004268}
4269
Douglas Gregorf968d832011-05-27 01:19:52 +00004270bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004271 std::string& S) {
4272 // Encode result type.
4273 getObjCEncodingForType(Decl->getResultType(), S);
4274 CharUnits ParmOffset;
4275 // Compute size of all parameters.
4276 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4277 E = Decl->param_end(); PI != E; ++PI) {
4278 QualType PType = (*PI)->getType();
4279 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004280 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004281 continue;
4282
David Chisnall5389f482010-12-30 14:05:53 +00004283 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004284 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004285 ParmOffset += sz;
4286 }
4287 S += charUnitsToString(ParmOffset);
4288 ParmOffset = CharUnits::Zero();
4289
4290 // Argument types.
4291 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4292 E = Decl->param_end(); PI != E; ++PI) {
4293 ParmVarDecl *PVDecl = *PI;
4294 QualType PType = PVDecl->getOriginalType();
4295 if (const ArrayType *AT =
4296 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4297 // Use array's original type only if it has known number of
4298 // elements.
4299 if (!isa<ConstantArrayType>(AT))
4300 PType = PVDecl->getType();
4301 } else if (PType->isFunctionType())
4302 PType = PVDecl->getType();
4303 getObjCEncodingForType(PType, S);
4304 S += charUnitsToString(ParmOffset);
4305 ParmOffset += getObjCEncodingTypeSize(PType);
4306 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004307
4308 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004309}
4310
Bob Wilsondc8dab62011-11-30 01:57:58 +00004311/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4312/// method parameter or return type. If Extended, include class names and
4313/// block object types.
4314void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4315 QualType T, std::string& S,
4316 bool Extended) const {
4317 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4318 getObjCEncodingForTypeQualifier(QT, S);
4319 // Encode parameter type.
4320 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4321 true /*OutermostType*/,
4322 false /*EncodingProperty*/,
4323 false /*StructField*/,
4324 Extended /*EncodeBlockParameters*/,
4325 Extended /*EncodeClassNames*/);
4326}
4327
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004328/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004329/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004330bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004331 std::string& S,
4332 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004333 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004334 // Encode return type.
4335 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4336 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004337 // Compute size of all parameters.
4338 // Start with computing size of a pointer in number of bytes.
4339 // FIXME: There might(should) be a better way of doing this computation!
4340 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004341 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004342 // The first two arguments (self and _cmd) are pointers; account for
4343 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004344 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004345 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004346 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004347 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004348 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004349 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004350 continue;
4351
Ken Dyck199c3d62010-01-11 17:06:35 +00004352 assert (sz.isPositive() &&
4353 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004354 ParmOffset += sz;
4355 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004356 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004357 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004358 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004359
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004360 // Argument types.
4361 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004362 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004363 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004364 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004365 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004366 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004367 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4368 // Use array's original type only if it has known number of
4369 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004370 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004371 PType = PVDecl->getType();
4372 } else if (PType->isFunctionType())
4373 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004374 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4375 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004376 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004377 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004378 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004379
4380 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004381}
4382
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004383/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004384/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004385/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4386/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004387/// Property attributes are stored as a comma-delimited C string. The simple
4388/// attributes readonly and bycopy are encoded as single characters. The
4389/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4390/// encoded as single characters, followed by an identifier. Property types
4391/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004392/// these attributes are defined by the following enumeration:
4393/// @code
4394/// enum PropertyAttributes {
4395/// kPropertyReadOnly = 'R', // property is read-only.
4396/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4397/// kPropertyByref = '&', // property is a reference to the value last assigned
4398/// kPropertyDynamic = 'D', // property is dynamic
4399/// kPropertyGetter = 'G', // followed by getter selector name
4400/// kPropertySetter = 'S', // followed by setter selector name
4401/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004402/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004403/// kPropertyWeak = 'W' // 'weak' property
4404/// kPropertyStrong = 'P' // property GC'able
4405/// kPropertyNonAtomic = 'N' // property non-atomic
4406/// };
4407/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004408void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004409 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004410 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004411 // Collect information from the property implementation decl(s).
4412 bool Dynamic = false;
4413 ObjCPropertyImplDecl *SynthesizePID = 0;
4414
4415 // FIXME: Duplicated code due to poor abstraction.
4416 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004417 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004418 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4419 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004420 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004421 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004422 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004423 if (PID->getPropertyDecl() == PD) {
4424 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4425 Dynamic = true;
4426 } else {
4427 SynthesizePID = PID;
4428 }
4429 }
4430 }
4431 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004432 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004433 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004434 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004435 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004436 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004437 if (PID->getPropertyDecl() == PD) {
4438 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4439 Dynamic = true;
4440 } else {
4441 SynthesizePID = PID;
4442 }
4443 }
Mike Stump1eb44332009-09-09 15:08:12 +00004444 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004445 }
4446 }
4447
4448 // FIXME: This is not very efficient.
4449 S = "T";
4450
4451 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004452 // GCC has some special rules regarding encoding of properties which
4453 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004454 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004455 true /* outermost type */,
4456 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004457
4458 if (PD->isReadOnly()) {
4459 S += ",R";
4460 } else {
4461 switch (PD->getSetterKind()) {
4462 case ObjCPropertyDecl::Assign: break;
4463 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004464 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004465 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004466 }
4467 }
4468
4469 // It really isn't clear at all what this means, since properties
4470 // are "dynamic by default".
4471 if (Dynamic)
4472 S += ",D";
4473
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004474 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4475 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004476
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004477 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4478 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004479 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004480 }
4481
4482 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4483 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004484 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004485 }
4486
4487 if (SynthesizePID) {
4488 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4489 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004490 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004491 }
4492
4493 // FIXME: OBJCGC: weak & strong
4494}
4495
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004496/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004497/// Another legacy compatibility encoding: 32-bit longs are encoded as
4498/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004499/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4500///
4501void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004502 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004503 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004504 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004505 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004506 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004507 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004508 PointeeTy = IntTy;
4509 }
4510 }
4511}
4512
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004513void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004514 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004515 // We follow the behavior of gcc, expanding structures which are
4516 // directly pointed to, and expanding embedded structures. Note that
4517 // these rules are sufficient to prevent recursive encoding of the
4518 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004519 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004520 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004521}
4522
David Chisnall64fd7e82010-06-04 01:10:52 +00004523static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4524 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004525 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004526 case BuiltinType::Void: return 'v';
4527 case BuiltinType::Bool: return 'B';
4528 case BuiltinType::Char_U:
4529 case BuiltinType::UChar: return 'C';
4530 case BuiltinType::UShort: return 'S';
4531 case BuiltinType::UInt: return 'I';
4532 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004533 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004534 case BuiltinType::UInt128: return 'T';
4535 case BuiltinType::ULongLong: return 'Q';
4536 case BuiltinType::Char_S:
4537 case BuiltinType::SChar: return 'c';
4538 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004539 case BuiltinType::WChar_S:
4540 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004541 case BuiltinType::Int: return 'i';
4542 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004543 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004544 case BuiltinType::LongLong: return 'q';
4545 case BuiltinType::Int128: return 't';
4546 case BuiltinType::Float: return 'f';
4547 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004548 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004549 }
4550}
4551
Douglas Gregor5471bc82011-09-08 17:18:35 +00004552static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4553 EnumDecl *Enum = ET->getDecl();
4554
4555 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4556 if (!Enum->isFixed())
4557 return 'i';
4558
4559 // The encoding of a fixed enum type matches its fixed underlying type.
4560 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4561}
4562
Jay Foad4ba2a172011-01-12 09:06:06 +00004563static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004564 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004565 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004566 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004567 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4568 // The GNU runtime requires more information; bitfields are encoded as b,
4569 // then the offset (in bits) of the first element, then the type of the
4570 // bitfield, then the size in bits. For example, in this structure:
4571 //
4572 // struct
4573 // {
4574 // int integer;
4575 // int flags:2;
4576 // };
4577 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4578 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4579 // information is not especially sensible, but we're stuck with it for
4580 // compatibility with GCC, although providing it breaks anything that
4581 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00004582 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004583 const RecordDecl *RD = FD->getParent();
4584 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004585 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004586 if (const EnumType *ET = T->getAs<EnumType>())
4587 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004588 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004589 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004590 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004591 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004592}
4593
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004594// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004595void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4596 bool ExpandPointedToStructures,
4597 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004598 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004599 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004600 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004601 bool StructField,
4602 bool EncodeBlockParameters,
4603 bool EncodeClassNames) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004604 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004605 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004606 return EncodeBitField(this, S, T, FD);
4607 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004608 return;
4609 }
Mike Stump1eb44332009-09-09 15:08:12 +00004610
John McCall183700f2009-09-21 23:43:11 +00004611 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004612 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004613 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004614 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004615 return;
4616 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004617
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004618 // encoding for pointer or r3eference types.
4619 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004620 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004621 if (PT->isObjCSelType()) {
4622 S += ':';
4623 return;
4624 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004625 PointeeTy = PT->getPointeeType();
4626 }
4627 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4628 PointeeTy = RT->getPointeeType();
4629 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004630 bool isReadOnly = false;
4631 // For historical/compatibility reasons, the read-only qualifier of the
4632 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4633 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004634 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004635 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004636 if (OutermostType && T.isConstQualified()) {
4637 isReadOnly = true;
4638 S += 'r';
4639 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004640 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004641 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004642 while (P->getAs<PointerType>())
4643 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004644 if (P.isConstQualified()) {
4645 isReadOnly = true;
4646 S += 'r';
4647 }
4648 }
4649 if (isReadOnly) {
4650 // Another legacy compatibility encoding. Some ObjC qualifier and type
4651 // combinations need to be rearranged.
4652 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004653 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004654 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004655 }
Mike Stump1eb44332009-09-09 15:08:12 +00004656
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004657 if (PointeeTy->isCharType()) {
4658 // char pointer types should be encoded as '*' unless it is a
4659 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004660 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004661 S += '*';
4662 return;
4663 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004664 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004665 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4666 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4667 S += '#';
4668 return;
4669 }
4670 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4671 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4672 S += '@';
4673 return;
4674 }
4675 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004676 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004677 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004678 getLegacyIntegralTypeEncoding(PointeeTy);
4679
Mike Stump1eb44332009-09-09 15:08:12 +00004680 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004681 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004682 return;
4683 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004684
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004685 if (const ArrayType *AT =
4686 // Ignore type qualifiers etc.
4687 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004688 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004689 // Incomplete arrays are encoded as a pointer to the array element.
4690 S += '^';
4691
Mike Stump1eb44332009-09-09 15:08:12 +00004692 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004693 false, ExpandStructures, FD);
4694 } else {
4695 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004696
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004697 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4698 if (getTypeSize(CAT->getElementType()) == 0)
4699 S += '0';
4700 else
4701 S += llvm::utostr(CAT->getSize().getZExtValue());
4702 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004703 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004704 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4705 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004706 S += '0';
4707 }
Mike Stump1eb44332009-09-09 15:08:12 +00004708
4709 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004710 false, ExpandStructures, FD);
4711 S += ']';
4712 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004713 return;
4714 }
Mike Stump1eb44332009-09-09 15:08:12 +00004715
John McCall183700f2009-09-21 23:43:11 +00004716 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004717 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004718 return;
4719 }
Mike Stump1eb44332009-09-09 15:08:12 +00004720
Ted Kremenek6217b802009-07-29 21:53:49 +00004721 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004722 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004723 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004724 // Anonymous structures print as '?'
4725 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4726 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004727 if (ClassTemplateSpecializationDecl *Spec
4728 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4729 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4730 std::string TemplateArgsStr
4731 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004732 TemplateArgs.data(),
4733 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004734 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004735
4736 S += TemplateArgsStr;
4737 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004738 } else {
4739 S += '?';
4740 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004741 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004742 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004743 if (!RDecl->isUnion()) {
4744 getObjCEncodingForStructureImpl(RDecl, S, FD);
4745 } else {
4746 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4747 FieldEnd = RDecl->field_end();
4748 Field != FieldEnd; ++Field) {
4749 if (FD) {
4750 S += '"';
4751 S += Field->getNameAsString();
4752 S += '"';
4753 }
Mike Stump1eb44332009-09-09 15:08:12 +00004754
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004755 // Special case bit-fields.
4756 if (Field->isBitField()) {
4757 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00004758 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004759 } else {
4760 QualType qt = Field->getType();
4761 getLegacyIntegralTypeEncoding(qt);
4762 getObjCEncodingForTypeImpl(qt, S, false, true,
4763 FD, /*OutermostType*/false,
4764 /*EncodingProperty*/false,
4765 /*StructField*/true);
4766 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004767 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004768 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004769 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004770 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004771 return;
4772 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004773
Douglas Gregor5471bc82011-09-08 17:18:35 +00004774 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004775 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004776 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004777 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004778 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004779 return;
4780 }
Mike Stump1eb44332009-09-09 15:08:12 +00004781
Bob Wilsondc8dab62011-11-30 01:57:58 +00004782 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004783 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00004784 if (EncodeBlockParameters) {
4785 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4786
4787 S += '<';
4788 // Block return type
4789 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4790 ExpandPointedToStructures, ExpandStructures,
4791 FD,
4792 false /* OutermostType */,
4793 EncodingProperty,
4794 false /* StructField */,
4795 EncodeBlockParameters,
4796 EncodeClassNames);
4797 // Block self
4798 S += "@?";
4799 // Block parameters
4800 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4801 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4802 E = FPT->arg_type_end(); I && (I != E); ++I) {
4803 getObjCEncodingForTypeImpl(*I, S,
4804 ExpandPointedToStructures,
4805 ExpandStructures,
4806 FD,
4807 false /* OutermostType */,
4808 EncodingProperty,
4809 false /* StructField */,
4810 EncodeBlockParameters,
4811 EncodeClassNames);
4812 }
4813 }
4814 S += '>';
4815 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004816 return;
4817 }
Mike Stump1eb44332009-09-09 15:08:12 +00004818
John McCallc12c5bb2010-05-15 11:32:37 +00004819 // Ignore protocol qualifiers when mangling at this level.
4820 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4821 T = OT->getBaseType();
4822
John McCall0953e762009-09-24 19:53:00 +00004823 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004824 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004825 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004826 S += '{';
4827 const IdentifierInfo *II = OI->getIdentifier();
4828 S += II->getName();
4829 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004830 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004831 DeepCollectObjCIvars(OI, true, Ivars);
4832 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004833 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004834 if (Field->isBitField())
4835 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004836 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004837 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004838 }
4839 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004840 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004841 }
Mike Stump1eb44332009-09-09 15:08:12 +00004842
John McCall183700f2009-09-21 23:43:11 +00004843 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004844 if (OPT->isObjCIdType()) {
4845 S += '@';
4846 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004847 }
Mike Stump1eb44332009-09-09 15:08:12 +00004848
Steve Naroff27d20a22009-10-28 22:03:49 +00004849 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4850 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4851 // Since this is a binary compatibility issue, need to consult with runtime
4852 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004853 S += '#';
4854 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004855 }
Mike Stump1eb44332009-09-09 15:08:12 +00004856
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004857 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004858 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004859 ExpandPointedToStructures,
4860 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00004861 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00004862 // Note that we do extended encoding of protocol qualifer list
4863 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004864 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004865 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4866 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004867 S += '<';
4868 S += (*I)->getNameAsString();
4869 S += '>';
4870 }
4871 S += '"';
4872 }
4873 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004874 }
Mike Stump1eb44332009-09-09 15:08:12 +00004875
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004876 QualType PointeeTy = OPT->getPointeeType();
4877 if (!EncodingProperty &&
4878 isa<TypedefType>(PointeeTy.getTypePtr())) {
4879 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004880 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004881 // {...};
4882 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004883 getObjCEncodingForTypeImpl(PointeeTy, S,
4884 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004885 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004886 return;
4887 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004888
4889 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00004890 if (OPT->getInterfaceDecl() &&
4891 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004892 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004893 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004894 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4895 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004896 S += '<';
4897 S += (*I)->getNameAsString();
4898 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004899 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004900 S += '"';
4901 }
4902 return;
4903 }
Mike Stump1eb44332009-09-09 15:08:12 +00004904
John McCall532ec7b2010-05-17 23:56:34 +00004905 // gcc just blithely ignores member pointers.
4906 // TODO: maybe there should be a mangling for these
4907 if (T->getAs<MemberPointerType>())
4908 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004909
4910 if (T->isVectorType()) {
4911 // This matches gcc's encoding, even though technically it is
4912 // insufficient.
4913 // FIXME. We should do a better job than gcc.
4914 return;
4915 }
4916
David Blaikieb219cfc2011-09-23 05:06:16 +00004917 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004918}
4919
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004920void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4921 std::string &S,
4922 const FieldDecl *FD,
4923 bool includeVBases) const {
4924 assert(RDecl && "Expected non-null RecordDecl");
4925 assert(!RDecl->isUnion() && "Should not be called for unions");
4926 if (!RDecl->getDefinition())
4927 return;
4928
4929 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4930 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4931 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4932
4933 if (CXXRec) {
4934 for (CXXRecordDecl::base_class_iterator
4935 BI = CXXRec->bases_begin(),
4936 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4937 if (!BI->isVirtual()) {
4938 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004939 if (base->isEmpty())
4940 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00004941 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004942 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4943 std::make_pair(offs, base));
4944 }
4945 }
4946 }
4947
4948 unsigned i = 0;
4949 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4950 FieldEnd = RDecl->field_end();
4951 Field != FieldEnd; ++Field, ++i) {
4952 uint64_t offs = layout.getFieldOffset(i);
4953 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00004954 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004955 }
4956
4957 if (CXXRec && includeVBases) {
4958 for (CXXRecordDecl::base_class_iterator
4959 BI = CXXRec->vbases_begin(),
4960 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4961 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004962 if (base->isEmpty())
4963 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00004964 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00004965 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4966 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4967 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004968 }
4969 }
4970
4971 CharUnits size;
4972 if (CXXRec) {
4973 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4974 } else {
4975 size = layout.getSize();
4976 }
4977
4978 uint64_t CurOffs = 0;
4979 std::multimap<uint64_t, NamedDecl *>::iterator
4980 CurLayObj = FieldOrBaseOffsets.begin();
4981
Douglas Gregor58db7a52012-04-27 22:30:01 +00004982 if (CXXRec && CXXRec->isDynamicClass() &&
4983 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004984 if (FD) {
4985 S += "\"_vptr$";
4986 std::string recname = CXXRec->getNameAsString();
4987 if (recname.empty()) recname = "?";
4988 S += recname;
4989 S += '"';
4990 }
4991 S += "^^?";
4992 CurOffs += getTypeSize(VoidPtrTy);
4993 }
4994
4995 if (!RDecl->hasFlexibleArrayMember()) {
4996 // Mark the end of the structure.
4997 uint64_t offs = toBits(size);
4998 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4999 std::make_pair(offs, (NamedDecl*)0));
5000 }
5001
5002 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5003 assert(CurOffs <= CurLayObj->first);
5004
5005 if (CurOffs < CurLayObj->first) {
5006 uint64_t padding = CurLayObj->first - CurOffs;
5007 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5008 // packing/alignment of members is different that normal, in which case
5009 // the encoding will be out-of-sync with the real layout.
5010 // If the runtime switches to just consider the size of types without
5011 // taking into account alignment, we could make padding explicit in the
5012 // encoding (e.g. using arrays of chars). The encoding strings would be
5013 // longer then though.
5014 CurOffs += padding;
5015 }
5016
5017 NamedDecl *dcl = CurLayObj->second;
5018 if (dcl == 0)
5019 break; // reached end of structure.
5020
5021 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5022 // We expand the bases without their virtual bases since those are going
5023 // in the initial structure. Note that this differs from gcc which
5024 // expands virtual bases each time one is encountered in the hierarchy,
5025 // making the encoding type bigger than it really is.
5026 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005027 assert(!base->isEmpty());
5028 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005029 } else {
5030 FieldDecl *field = cast<FieldDecl>(dcl);
5031 if (FD) {
5032 S += '"';
5033 S += field->getNameAsString();
5034 S += '"';
5035 }
5036
5037 if (field->isBitField()) {
5038 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005039 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005040 } else {
5041 QualType qt = field->getType();
5042 getLegacyIntegralTypeEncoding(qt);
5043 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5044 /*OutermostType*/false,
5045 /*EncodingProperty*/false,
5046 /*StructField*/true);
5047 CurOffs += getTypeSize(field->getType());
5048 }
5049 }
5050 }
5051}
5052
Mike Stump1eb44332009-09-09 15:08:12 +00005053void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005054 std::string& S) const {
5055 if (QT & Decl::OBJC_TQ_In)
5056 S += 'n';
5057 if (QT & Decl::OBJC_TQ_Inout)
5058 S += 'N';
5059 if (QT & Decl::OBJC_TQ_Out)
5060 S += 'o';
5061 if (QT & Decl::OBJC_TQ_Bycopy)
5062 S += 'O';
5063 if (QT & Decl::OBJC_TQ_Byref)
5064 S += 'R';
5065 if (QT & Decl::OBJC_TQ_Oneway)
5066 S += 'V';
5067}
5068
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005069TypedefDecl *ASTContext::getObjCIdDecl() const {
5070 if (!ObjCIdDecl) {
5071 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5072 T = getObjCObjectPointerType(T);
5073 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5074 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5075 getTranslationUnitDecl(),
5076 SourceLocation(), SourceLocation(),
5077 &Idents.get("id"), IdInfo);
5078 }
5079
5080 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005081}
5082
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005083TypedefDecl *ASTContext::getObjCSelDecl() const {
5084 if (!ObjCSelDecl) {
5085 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5086 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5087 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5088 getTranslationUnitDecl(),
5089 SourceLocation(), SourceLocation(),
5090 &Idents.get("SEL"), SelInfo);
5091 }
5092 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005093}
5094
Douglas Gregor79d67262011-08-12 05:59:41 +00005095TypedefDecl *ASTContext::getObjCClassDecl() const {
5096 if (!ObjCClassDecl) {
5097 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5098 T = getObjCObjectPointerType(T);
5099 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5100 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5101 getTranslationUnitDecl(),
5102 SourceLocation(), SourceLocation(),
5103 &Idents.get("Class"), ClassInfo);
5104 }
5105
5106 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005107}
5108
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005109ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5110 if (!ObjCProtocolClassDecl) {
5111 ObjCProtocolClassDecl
5112 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5113 SourceLocation(),
5114 &Idents.get("Protocol"),
5115 /*PrevDecl=*/0,
5116 SourceLocation(), true);
5117 }
5118
5119 return ObjCProtocolClassDecl;
5120}
5121
Meador Ingec5613b22012-06-16 03:34:49 +00005122//===----------------------------------------------------------------------===//
5123// __builtin_va_list Construction Functions
5124//===----------------------------------------------------------------------===//
5125
5126static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5127 // typedef char* __builtin_va_list;
5128 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5129 TypeSourceInfo *TInfo
5130 = Context->getTrivialTypeSourceInfo(CharPtrType);
5131
5132 TypedefDecl *VaListTypeDecl
5133 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5134 Context->getTranslationUnitDecl(),
5135 SourceLocation(), SourceLocation(),
5136 &Context->Idents.get("__builtin_va_list"),
5137 TInfo);
5138 return VaListTypeDecl;
5139}
5140
5141static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5142 // typedef void* __builtin_va_list;
5143 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5144 TypeSourceInfo *TInfo
5145 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5146
5147 TypedefDecl *VaListTypeDecl
5148 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5149 Context->getTranslationUnitDecl(),
5150 SourceLocation(), SourceLocation(),
5151 &Context->Idents.get("__builtin_va_list"),
5152 TInfo);
5153 return VaListTypeDecl;
5154}
5155
5156static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5157 // typedef struct __va_list_tag {
5158 RecordDecl *VaListTagDecl;
5159
5160 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5161 Context->getTranslationUnitDecl(),
5162 &Context->Idents.get("__va_list_tag"));
5163 VaListTagDecl->startDefinition();
5164
5165 const size_t NumFields = 5;
5166 QualType FieldTypes[NumFields];
5167 const char *FieldNames[NumFields];
5168
5169 // unsigned char gpr;
5170 FieldTypes[0] = Context->UnsignedCharTy;
5171 FieldNames[0] = "gpr";
5172
5173 // unsigned char fpr;
5174 FieldTypes[1] = Context->UnsignedCharTy;
5175 FieldNames[1] = "fpr";
5176
5177 // unsigned short reserved;
5178 FieldTypes[2] = Context->UnsignedShortTy;
5179 FieldNames[2] = "reserved";
5180
5181 // void* overflow_arg_area;
5182 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5183 FieldNames[3] = "overflow_arg_area";
5184
5185 // void* reg_save_area;
5186 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5187 FieldNames[4] = "reg_save_area";
5188
5189 // Create fields
5190 for (unsigned i = 0; i < NumFields; ++i) {
5191 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5192 SourceLocation(),
5193 SourceLocation(),
5194 &Context->Idents.get(FieldNames[i]),
5195 FieldTypes[i], /*TInfo=*/0,
5196 /*BitWidth=*/0,
5197 /*Mutable=*/false,
5198 ICIS_NoInit);
5199 Field->setAccess(AS_public);
5200 VaListTagDecl->addDecl(Field);
5201 }
5202 VaListTagDecl->completeDefinition();
5203 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005204 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005205
5206 // } __va_list_tag;
5207 TypedefDecl *VaListTagTypedefDecl
5208 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5209 Context->getTranslationUnitDecl(),
5210 SourceLocation(), SourceLocation(),
5211 &Context->Idents.get("__va_list_tag"),
5212 Context->getTrivialTypeSourceInfo(VaListTagType));
5213 QualType VaListTagTypedefType =
5214 Context->getTypedefType(VaListTagTypedefDecl);
5215
5216 // typedef __va_list_tag __builtin_va_list[1];
5217 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5218 QualType VaListTagArrayType
5219 = Context->getConstantArrayType(VaListTagTypedefType,
5220 Size, ArrayType::Normal, 0);
5221 TypeSourceInfo *TInfo
5222 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5223 TypedefDecl *VaListTypedefDecl
5224 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5225 Context->getTranslationUnitDecl(),
5226 SourceLocation(), SourceLocation(),
5227 &Context->Idents.get("__builtin_va_list"),
5228 TInfo);
5229
5230 return VaListTypedefDecl;
5231}
5232
5233static TypedefDecl *
5234CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5235 // typedef struct __va_list_tag {
5236 RecordDecl *VaListTagDecl;
5237 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5238 Context->getTranslationUnitDecl(),
5239 &Context->Idents.get("__va_list_tag"));
5240 VaListTagDecl->startDefinition();
5241
5242 const size_t NumFields = 4;
5243 QualType FieldTypes[NumFields];
5244 const char *FieldNames[NumFields];
5245
5246 // unsigned gp_offset;
5247 FieldTypes[0] = Context->UnsignedIntTy;
5248 FieldNames[0] = "gp_offset";
5249
5250 // unsigned fp_offset;
5251 FieldTypes[1] = Context->UnsignedIntTy;
5252 FieldNames[1] = "fp_offset";
5253
5254 // void* overflow_arg_area;
5255 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5256 FieldNames[2] = "overflow_arg_area";
5257
5258 // void* reg_save_area;
5259 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5260 FieldNames[3] = "reg_save_area";
5261
5262 // Create fields
5263 for (unsigned i = 0; i < NumFields; ++i) {
5264 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5265 VaListTagDecl,
5266 SourceLocation(),
5267 SourceLocation(),
5268 &Context->Idents.get(FieldNames[i]),
5269 FieldTypes[i], /*TInfo=*/0,
5270 /*BitWidth=*/0,
5271 /*Mutable=*/false,
5272 ICIS_NoInit);
5273 Field->setAccess(AS_public);
5274 VaListTagDecl->addDecl(Field);
5275 }
5276 VaListTagDecl->completeDefinition();
5277 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005278 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005279
5280 // } __va_list_tag;
5281 TypedefDecl *VaListTagTypedefDecl
5282 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5283 Context->getTranslationUnitDecl(),
5284 SourceLocation(), SourceLocation(),
5285 &Context->Idents.get("__va_list_tag"),
5286 Context->getTrivialTypeSourceInfo(VaListTagType));
5287 QualType VaListTagTypedefType =
5288 Context->getTypedefType(VaListTagTypedefDecl);
5289
5290 // typedef __va_list_tag __builtin_va_list[1];
5291 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5292 QualType VaListTagArrayType
5293 = Context->getConstantArrayType(VaListTagTypedefType,
5294 Size, ArrayType::Normal,0);
5295 TypeSourceInfo *TInfo
5296 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5297 TypedefDecl *VaListTypedefDecl
5298 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5299 Context->getTranslationUnitDecl(),
5300 SourceLocation(), SourceLocation(),
5301 &Context->Idents.get("__builtin_va_list"),
5302 TInfo);
5303
5304 return VaListTypedefDecl;
5305}
5306
5307static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5308 // typedef int __builtin_va_list[4];
5309 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5310 QualType IntArrayType
5311 = Context->getConstantArrayType(Context->IntTy,
5312 Size, ArrayType::Normal, 0);
5313 TypedefDecl *VaListTypedefDecl
5314 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5315 Context->getTranslationUnitDecl(),
5316 SourceLocation(), SourceLocation(),
5317 &Context->Idents.get("__builtin_va_list"),
5318 Context->getTrivialTypeSourceInfo(IntArrayType));
5319
5320 return VaListTypedefDecl;
5321}
5322
5323static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5324 TargetInfo::BuiltinVaListKind Kind) {
5325 switch (Kind) {
5326 case TargetInfo::CharPtrBuiltinVaList:
5327 return CreateCharPtrBuiltinVaListDecl(Context);
5328 case TargetInfo::VoidPtrBuiltinVaList:
5329 return CreateVoidPtrBuiltinVaListDecl(Context);
5330 case TargetInfo::PowerABIBuiltinVaList:
5331 return CreatePowerABIBuiltinVaListDecl(Context);
5332 case TargetInfo::X86_64ABIBuiltinVaList:
5333 return CreateX86_64ABIBuiltinVaListDecl(Context);
5334 case TargetInfo::PNaClABIBuiltinVaList:
5335 return CreatePNaClABIBuiltinVaListDecl(Context);
5336 }
5337
5338 llvm_unreachable("Unhandled __builtin_va_list type kind");
5339}
5340
5341TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5342 if (!BuiltinVaListDecl)
5343 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5344
5345 return BuiltinVaListDecl;
5346}
5347
Meador Ingefb40e3f2012-07-01 15:57:25 +00005348QualType ASTContext::getVaListTagType() const {
5349 // Force the creation of VaListTagTy by building the __builtin_va_list
5350 // declaration.
5351 if (VaListTagTy.isNull())
5352 (void) getBuiltinVaListDecl();
5353
5354 return VaListTagTy;
5355}
5356
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005357void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00005358 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00005359 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00005360
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005361 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00005362}
5363
John McCall0bd6feb2009-12-02 08:04:21 +00005364/// \brief Retrieve the template name that corresponds to a non-empty
5365/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00005366TemplateName
5367ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5368 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00005369 unsigned size = End - Begin;
5370 assert(size > 1 && "set is not overloaded!");
5371
5372 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5373 size * sizeof(FunctionTemplateDecl*));
5374 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5375
5376 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00005377 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00005378 NamedDecl *D = *I;
5379 assert(isa<FunctionTemplateDecl>(D) ||
5380 (isa<UsingShadowDecl>(D) &&
5381 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5382 *Storage++ = D;
5383 }
5384
5385 return TemplateName(OT);
5386}
5387
Douglas Gregor7532dc62009-03-30 22:58:21 +00005388/// \brief Retrieve the template name that represents a qualified
5389/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00005390TemplateName
5391ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5392 bool TemplateKeyword,
5393 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00005394 assert(NNS && "Missing nested-name-specifier in qualified template name");
5395
Douglas Gregor789b1f62010-02-04 18:10:26 +00005396 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00005397 llvm::FoldingSetNodeID ID;
5398 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5399
5400 void *InsertPos = 0;
5401 QualifiedTemplateName *QTN =
5402 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5403 if (!QTN) {
5404 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5405 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5406 }
5407
5408 return TemplateName(QTN);
5409}
5410
5411/// \brief Retrieve the template name that represents a dependent
5412/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00005413TemplateName
5414ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5415 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00005416 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00005417 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00005418
5419 llvm::FoldingSetNodeID ID;
5420 DependentTemplateName::Profile(ID, NNS, Name);
5421
5422 void *InsertPos = 0;
5423 DependentTemplateName *QTN =
5424 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5425
5426 if (QTN)
5427 return TemplateName(QTN);
5428
5429 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5430 if (CanonNNS == NNS) {
5431 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5432 } else {
5433 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5434 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005435 DependentTemplateName *CheckQTN =
5436 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5437 assert(!CheckQTN && "Dependent type name canonicalization broken");
5438 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005439 }
5440
5441 DependentTemplateNames.InsertNode(QTN, InsertPos);
5442 return TemplateName(QTN);
5443}
5444
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005445/// \brief Retrieve the template name that represents a dependent
5446/// template name such as \c MetaFun::template operator+.
5447TemplateName
5448ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005449 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005450 assert((!NNS || NNS->isDependent()) &&
5451 "Nested name specifier must be dependent");
5452
5453 llvm::FoldingSetNodeID ID;
5454 DependentTemplateName::Profile(ID, NNS, Operator);
5455
5456 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005457 DependentTemplateName *QTN
5458 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005459
5460 if (QTN)
5461 return TemplateName(QTN);
5462
5463 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5464 if (CanonNNS == NNS) {
5465 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5466 } else {
5467 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5468 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005469
5470 DependentTemplateName *CheckQTN
5471 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5472 assert(!CheckQTN && "Dependent template name canonicalization broken");
5473 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005474 }
5475
5476 DependentTemplateNames.InsertNode(QTN, InsertPos);
5477 return TemplateName(QTN);
5478}
5479
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005480TemplateName
John McCall14606042011-06-30 08:33:18 +00005481ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5482 TemplateName replacement) const {
5483 llvm::FoldingSetNodeID ID;
5484 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5485
5486 void *insertPos = 0;
5487 SubstTemplateTemplateParmStorage *subst
5488 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5489
5490 if (!subst) {
5491 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5492 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5493 }
5494
5495 return TemplateName(subst);
5496}
5497
5498TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005499ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5500 const TemplateArgument &ArgPack) const {
5501 ASTContext &Self = const_cast<ASTContext &>(*this);
5502 llvm::FoldingSetNodeID ID;
5503 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5504
5505 void *InsertPos = 0;
5506 SubstTemplateTemplateParmPackStorage *Subst
5507 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5508
5509 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005510 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005511 ArgPack.pack_size(),
5512 ArgPack.pack_begin());
5513 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5514 }
5515
5516 return TemplateName(Subst);
5517}
5518
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005519/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005520/// TargetInfo, produce the corresponding type. The unsigned @p Type
5521/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005522CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005523 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005524 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005525 case TargetInfo::SignedShort: return ShortTy;
5526 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5527 case TargetInfo::SignedInt: return IntTy;
5528 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5529 case TargetInfo::SignedLong: return LongTy;
5530 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5531 case TargetInfo::SignedLongLong: return LongLongTy;
5532 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5533 }
5534
David Blaikieb219cfc2011-09-23 05:06:16 +00005535 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005536}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005537
5538//===----------------------------------------------------------------------===//
5539// Type Predicates.
5540//===----------------------------------------------------------------------===//
5541
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005542/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5543/// garbage collection attribute.
5544///
John McCallae278a32011-01-12 00:34:59 +00005545Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00005546 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005547 return Qualifiers::GCNone;
5548
David Blaikie4e4d0842012-03-11 07:00:24 +00005549 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00005550 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5551
5552 // Default behaviour under objective-C's gc is for ObjC pointers
5553 // (or pointers to them) be treated as though they were declared
5554 // as __strong.
5555 if (GCAttrs == Qualifiers::GCNone) {
5556 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5557 return Qualifiers::Strong;
5558 else if (Ty->isPointerType())
5559 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5560 } else {
5561 // It's not valid to set GC attributes on anything that isn't a
5562 // pointer.
5563#ifndef NDEBUG
5564 QualType CT = Ty->getCanonicalTypeInternal();
5565 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5566 CT = AT->getElementType();
5567 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5568#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005569 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005570 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005571}
5572
Chris Lattner6ac46a42008-04-07 06:51:04 +00005573//===----------------------------------------------------------------------===//
5574// Type Compatibility Testing
5575//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005576
Mike Stump1eb44332009-09-09 15:08:12 +00005577/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005578/// compatible.
5579static bool areCompatVectorTypes(const VectorType *LHS,
5580 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005581 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005582 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005583 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005584}
5585
Douglas Gregor255210e2010-08-06 10:14:59 +00005586bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5587 QualType SecondVec) {
5588 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5589 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5590
5591 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5592 return true;
5593
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005594 // Treat Neon vector types and most AltiVec vector types as if they are the
5595 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005596 const VectorType *First = FirstVec->getAs<VectorType>();
5597 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005598 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005599 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005600 First->getVectorKind() != VectorType::AltiVecPixel &&
5601 First->getVectorKind() != VectorType::AltiVecBool &&
5602 Second->getVectorKind() != VectorType::AltiVecPixel &&
5603 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005604 return true;
5605
5606 return false;
5607}
5608
Steve Naroff4084c302009-07-23 01:01:38 +00005609//===----------------------------------------------------------------------===//
5610// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5611//===----------------------------------------------------------------------===//
5612
5613/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5614/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005615bool
5616ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5617 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005618 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00005619 return true;
5620 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5621 E = rProto->protocol_end(); PI != E; ++PI)
5622 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5623 return true;
5624 return false;
5625}
5626
Steve Naroff4084c302009-07-23 01:01:38 +00005627/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5628/// return true if lhs's protocols conform to rhs's protocol; false
5629/// otherwise.
5630bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5631 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5632 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5633 return false;
5634}
5635
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005636/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5637/// Class<p1, ...>.
5638bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5639 QualType rhs) {
5640 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5641 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5642 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5643
5644 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5645 E = lhsQID->qual_end(); I != E; ++I) {
5646 bool match = false;
5647 ObjCProtocolDecl *lhsProto = *I;
5648 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5649 E = rhsOPT->qual_end(); J != E; ++J) {
5650 ObjCProtocolDecl *rhsProto = *J;
5651 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5652 match = true;
5653 break;
5654 }
5655 }
5656 if (!match)
5657 return false;
5658 }
5659 return true;
5660}
5661
Steve Naroff4084c302009-07-23 01:01:38 +00005662/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5663/// ObjCQualifiedIDType.
5664bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5665 bool compare) {
5666 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005667 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005668 lhs->isObjCIdType() || lhs->isObjCClassType())
5669 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005670 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005671 rhs->isObjCIdType() || rhs->isObjCClassType())
5672 return true;
5673
5674 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005675 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005676
Steve Naroff4084c302009-07-23 01:01:38 +00005677 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005678
Steve Naroff4084c302009-07-23 01:01:38 +00005679 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005680 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005681 // make sure we check the class hierarchy.
5682 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5683 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5684 E = lhsQID->qual_end(); I != E; ++I) {
5685 // when comparing an id<P> on lhs with a static type on rhs,
5686 // see if static class implements all of id's protocols, directly or
5687 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005688 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005689 return false;
5690 }
5691 }
5692 // If there are no qualifiers and no interface, we have an 'id'.
5693 return true;
5694 }
Mike Stump1eb44332009-09-09 15:08:12 +00005695 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005696 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5697 E = lhsQID->qual_end(); I != E; ++I) {
5698 ObjCProtocolDecl *lhsProto = *I;
5699 bool match = false;
5700
5701 // when comparing an id<P> on lhs with a static type on rhs,
5702 // see if static class implements all of id's protocols, directly or
5703 // through its super class and categories.
5704 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5705 E = rhsOPT->qual_end(); J != E; ++J) {
5706 ObjCProtocolDecl *rhsProto = *J;
5707 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5708 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5709 match = true;
5710 break;
5711 }
5712 }
Mike Stump1eb44332009-09-09 15:08:12 +00005713 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005714 // make sure we check the class hierarchy.
5715 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5716 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5717 E = lhsQID->qual_end(); I != E; ++I) {
5718 // when comparing an id<P> on lhs with a static type on rhs,
5719 // see if static class implements all of id's protocols, directly or
5720 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005721 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005722 match = true;
5723 break;
5724 }
5725 }
5726 }
5727 if (!match)
5728 return false;
5729 }
Mike Stump1eb44332009-09-09 15:08:12 +00005730
Steve Naroff4084c302009-07-23 01:01:38 +00005731 return true;
5732 }
Mike Stump1eb44332009-09-09 15:08:12 +00005733
Steve Naroff4084c302009-07-23 01:01:38 +00005734 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5735 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5736
Mike Stump1eb44332009-09-09 15:08:12 +00005737 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005738 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005739 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005740 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5741 E = lhsOPT->qual_end(); I != E; ++I) {
5742 ObjCProtocolDecl *lhsProto = *I;
5743 bool match = false;
5744
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005745 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005746 // see if static class implements all of id's protocols, directly or
5747 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005748 // First, lhs protocols in the qualifier list must be found, direct
5749 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005750 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5751 E = rhsQID->qual_end(); J != E; ++J) {
5752 ObjCProtocolDecl *rhsProto = *J;
5753 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5754 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5755 match = true;
5756 break;
5757 }
5758 }
5759 if (!match)
5760 return false;
5761 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005762
5763 // Static class's protocols, or its super class or category protocols
5764 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5765 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5766 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5767 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5768 // This is rather dubious but matches gcc's behavior. If lhs has
5769 // no type qualifier and its class has no static protocol(s)
5770 // assume that it is mismatch.
5771 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5772 return false;
5773 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5774 LHSInheritedProtocols.begin(),
5775 E = LHSInheritedProtocols.end(); I != E; ++I) {
5776 bool match = false;
5777 ObjCProtocolDecl *lhsProto = (*I);
5778 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5779 E = rhsQID->qual_end(); J != E; ++J) {
5780 ObjCProtocolDecl *rhsProto = *J;
5781 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5782 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5783 match = true;
5784 break;
5785 }
5786 }
5787 if (!match)
5788 return false;
5789 }
5790 }
Steve Naroff4084c302009-07-23 01:01:38 +00005791 return true;
5792 }
5793 return false;
5794}
5795
Eli Friedman3d815e72008-08-22 00:56:42 +00005796/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005797/// compatible for assignment from RHS to LHS. This handles validation of any
5798/// protocol qualifiers on the LHS or RHS.
5799///
Steve Naroff14108da2009-07-10 23:34:53 +00005800bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5801 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005802 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5803 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5804
Steve Naroffde2e22d2009-07-15 18:40:39 +00005805 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005806 if (LHS->isObjCUnqualifiedIdOrClass() ||
5807 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005808 return true;
5809
John McCallc12c5bb2010-05-15 11:32:37 +00005810 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005811 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5812 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005813 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005814
5815 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5816 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5817 QualType(RHSOPT,0));
5818
John McCallc12c5bb2010-05-15 11:32:37 +00005819 // If we have 2 user-defined types, fall into that path.
5820 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005821 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005822
Steve Naroff4084c302009-07-23 01:01:38 +00005823 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005824}
5825
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005826/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005827/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005828/// arguments in block literals. When passed as arguments, passing 'A*' where
5829/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5830/// not OK. For the return type, the opposite is not OK.
5831bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5832 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005833 const ObjCObjectPointerType *RHSOPT,
5834 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005835 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005836 return true;
5837
5838 if (LHSOPT->isObjCBuiltinType()) {
5839 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5840 }
5841
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005842 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005843 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5844 QualType(RHSOPT,0),
5845 false);
5846
5847 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5848 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5849 if (LHS && RHS) { // We have 2 user-defined types.
5850 if (LHS != RHS) {
5851 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005852 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005853 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005854 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005855 }
5856 else
5857 return true;
5858 }
5859 return false;
5860}
5861
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005862/// getIntersectionOfProtocols - This routine finds the intersection of set
5863/// of protocols inherited from two distinct objective-c pointer objects.
5864/// It is used to build composite qualifier list of the composite type of
5865/// the conditional expression involving two objective-c pointer objects.
5866static
5867void getIntersectionOfProtocols(ASTContext &Context,
5868 const ObjCObjectPointerType *LHSOPT,
5869 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005870 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005871
John McCallc12c5bb2010-05-15 11:32:37 +00005872 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5873 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5874 assert(LHS->getInterface() && "LHS must have an interface base");
5875 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005876
5877 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5878 unsigned LHSNumProtocols = LHS->getNumProtocols();
5879 if (LHSNumProtocols > 0)
5880 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5881 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005882 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005883 Context.CollectInheritedProtocols(LHS->getInterface(),
5884 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005885 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5886 LHSInheritedProtocols.end());
5887 }
5888
5889 unsigned RHSNumProtocols = RHS->getNumProtocols();
5890 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005891 ObjCProtocolDecl **RHSProtocols =
5892 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005893 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5894 if (InheritedProtocolSet.count(RHSProtocols[i]))
5895 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00005896 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005897 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005898 Context.CollectInheritedProtocols(RHS->getInterface(),
5899 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005900 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5901 RHSInheritedProtocols.begin(),
5902 E = RHSInheritedProtocols.end(); I != E; ++I)
5903 if (InheritedProtocolSet.count((*I)))
5904 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005905 }
5906}
5907
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005908/// areCommonBaseCompatible - Returns common base class of the two classes if
5909/// one found. Note that this is O'2 algorithm. But it will be called as the
5910/// last type comparison in a ?-exp of ObjC pointer types before a
5911/// warning is issued. So, its invokation is extremely rare.
5912QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005913 const ObjCObjectPointerType *Lptr,
5914 const ObjCObjectPointerType *Rptr) {
5915 const ObjCObjectType *LHS = Lptr->getObjectType();
5916 const ObjCObjectType *RHS = Rptr->getObjectType();
5917 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5918 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00005919 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005920 return QualType();
5921
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005922 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005923 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005924 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005925 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005926 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5927
5928 QualType Result = QualType(LHS, 0);
5929 if (!Protocols.empty())
5930 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5931 Result = getObjCObjectPointerType(Result);
5932 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005933 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005934 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005935
5936 return QualType();
5937}
5938
John McCallc12c5bb2010-05-15 11:32:37 +00005939bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5940 const ObjCObjectType *RHS) {
5941 assert(LHS->getInterface() && "LHS is not an interface type");
5942 assert(RHS->getInterface() && "RHS is not an interface type");
5943
Chris Lattner6ac46a42008-04-07 06:51:04 +00005944 // Verify that the base decls are compatible: the RHS must be a subclass of
5945 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005946 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005947 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005948
Chris Lattner6ac46a42008-04-07 06:51:04 +00005949 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5950 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005951 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005952 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005953
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005954 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5955 // more detailed analysis is required.
5956 if (RHS->getNumProtocols() == 0) {
5957 // OK, if LHS is a superclass of RHS *and*
5958 // this superclass is assignment compatible with LHS.
5959 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005960 bool IsSuperClass =
5961 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5962 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005963 // OK if conversion of LHS to SuperClass results in narrowing of types
5964 // ; i.e., SuperClass may implement at least one of the protocols
5965 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5966 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5967 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005968 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005969 // If super class has no protocols, it is not a match.
5970 if (SuperClassInheritedProtocols.empty())
5971 return false;
5972
5973 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5974 LHSPE = LHS->qual_end();
5975 LHSPI != LHSPE; LHSPI++) {
5976 bool SuperImplementsProtocol = false;
5977 ObjCProtocolDecl *LHSProto = (*LHSPI);
5978
5979 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5980 SuperClassInheritedProtocols.begin(),
5981 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5982 ObjCProtocolDecl *SuperClassProto = (*I);
5983 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5984 SuperImplementsProtocol = true;
5985 break;
5986 }
5987 }
5988 if (!SuperImplementsProtocol)
5989 return false;
5990 }
5991 return true;
5992 }
5993 return false;
5994 }
Mike Stump1eb44332009-09-09 15:08:12 +00005995
John McCallc12c5bb2010-05-15 11:32:37 +00005996 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5997 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005998 LHSPI != LHSPE; LHSPI++) {
5999 bool RHSImplementsProtocol = false;
6000
6001 // If the RHS doesn't implement the protocol on the left, the types
6002 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006003 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6004 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006005 RHSPI != RHSPE; RHSPI++) {
6006 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006007 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006008 break;
6009 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006010 }
6011 // FIXME: For better diagnostics, consider passing back the protocol name.
6012 if (!RHSImplementsProtocol)
6013 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006014 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006015 // The RHS implements all protocols listed on the LHS.
6016 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006017}
6018
Steve Naroff389bf462009-02-12 17:52:19 +00006019bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6020 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006021 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6022 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006023
Steve Naroff14108da2009-07-10 23:34:53 +00006024 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006025 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006026
6027 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6028 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006029}
6030
Douglas Gregor569c3162010-08-07 11:51:51 +00006031bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6032 return canAssignObjCInterfaces(
6033 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6034 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6035}
6036
Mike Stump1eb44332009-09-09 15:08:12 +00006037/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006038/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006039/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006040/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006041bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6042 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006043 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006044 return hasSameType(LHS, RHS);
6045
Douglas Gregor447234d2010-07-29 15:18:02 +00006046 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006047}
6048
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006049bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006050 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006051}
6052
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006053bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6054 return !mergeTypes(LHS, RHS, true).isNull();
6055}
6056
Peter Collingbourne48466752010-10-24 18:30:18 +00006057/// mergeTransparentUnionType - if T is a transparent union type and a member
6058/// of T is compatible with SubType, return the merged type, else return
6059/// QualType()
6060QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6061 bool OfBlockPointer,
6062 bool Unqualified) {
6063 if (const RecordType *UT = T->getAsUnionType()) {
6064 RecordDecl *UD = UT->getDecl();
6065 if (UD->hasAttr<TransparentUnionAttr>()) {
6066 for (RecordDecl::field_iterator it = UD->field_begin(),
6067 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006068 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006069 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6070 if (!MT.isNull())
6071 return MT;
6072 }
6073 }
6074 }
6075
6076 return QualType();
6077}
6078
6079/// mergeFunctionArgumentTypes - merge two types which appear as function
6080/// argument types
6081QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6082 bool OfBlockPointer,
6083 bool Unqualified) {
6084 // GNU extension: two types are compatible if they appear as a function
6085 // argument, one of the types is a transparent union type and the other
6086 // type is compatible with a union member
6087 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6088 Unqualified);
6089 if (!lmerge.isNull())
6090 return lmerge;
6091
6092 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6093 Unqualified);
6094 if (!rmerge.isNull())
6095 return rmerge;
6096
6097 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6098}
6099
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006100QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006101 bool OfBlockPointer,
6102 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006103 const FunctionType *lbase = lhs->getAs<FunctionType>();
6104 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006105 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6106 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006107 bool allLTypes = true;
6108 bool allRTypes = true;
6109
6110 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006111 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006112 if (OfBlockPointer) {
6113 QualType RHS = rbase->getResultType();
6114 QualType LHS = lbase->getResultType();
6115 bool UnqualifiedResult = Unqualified;
6116 if (!UnqualifiedResult)
6117 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006118 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006119 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006120 else
John McCall8cc246c2010-12-15 01:06:38 +00006121 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6122 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006123 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006124
6125 if (Unqualified)
6126 retType = retType.getUnqualifiedType();
6127
6128 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6129 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6130 if (Unqualified) {
6131 LRetType = LRetType.getUnqualifiedType();
6132 RRetType = RRetType.getUnqualifiedType();
6133 }
6134
6135 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006136 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006137 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006138 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006139
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006140 // FIXME: double check this
6141 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6142 // rbase->getRegParmAttr() != 0 &&
6143 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006144 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6145 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006146
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006147 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006148 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006149 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006150
John McCall8cc246c2010-12-15 01:06:38 +00006151 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006152 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6153 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006154 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6155 return QualType();
6156
John McCallf85e1932011-06-15 23:02:42 +00006157 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6158 return QualType();
6159
Fariborz Jahanian53c81672011-10-05 00:05:34 +00006160 // functypes which return are preferred over those that do not.
6161 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6162 allLTypes = false;
6163 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6164 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006165 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6166 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006167
John McCallf85e1932011-06-15 23:02:42 +00006168 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006169
Eli Friedman3d815e72008-08-22 00:56:42 +00006170 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006171 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6172 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006173 unsigned lproto_nargs = lproto->getNumArgs();
6174 unsigned rproto_nargs = rproto->getNumArgs();
6175
6176 // Compatible functions must have the same number of arguments
6177 if (lproto_nargs != rproto_nargs)
6178 return QualType();
6179
6180 // Variadic and non-variadic functions aren't compatible
6181 if (lproto->isVariadic() != rproto->isVariadic())
6182 return QualType();
6183
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006184 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6185 return QualType();
6186
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006187 if (LangOpts.ObjCAutoRefCount &&
6188 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6189 return QualType();
6190
Eli Friedman3d815e72008-08-22 00:56:42 +00006191 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006192 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006193 for (unsigned i = 0; i < lproto_nargs; i++) {
6194 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6195 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006196 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6197 OfBlockPointer,
6198 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006199 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006200
6201 if (Unqualified)
6202 argtype = argtype.getUnqualifiedType();
6203
Eli Friedman3d815e72008-08-22 00:56:42 +00006204 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006205 if (Unqualified) {
6206 largtype = largtype.getUnqualifiedType();
6207 rargtype = rargtype.getUnqualifiedType();
6208 }
6209
Chris Lattner61710852008-10-05 17:34:18 +00006210 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6211 allLTypes = false;
6212 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6213 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006214 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006215
Eli Friedman3d815e72008-08-22 00:56:42 +00006216 if (allLTypes) return lhs;
6217 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006218
6219 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6220 EPI.ExtInfo = einfo;
6221 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006222 }
6223
6224 if (lproto) allRTypes = false;
6225 if (rproto) allLTypes = false;
6226
Douglas Gregor72564e72009-02-26 23:50:07 +00006227 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00006228 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00006229 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006230 if (proto->isVariadic()) return QualType();
6231 // Check that the types are compatible with the types that
6232 // would result from default argument promotions (C99 6.7.5.3p15).
6233 // The only types actually affected are promotable integer
6234 // types and floats, which would be passed as a different
6235 // type depending on whether the prototype is visible.
6236 unsigned proto_nargs = proto->getNumArgs();
6237 for (unsigned i = 0; i < proto_nargs; ++i) {
6238 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006239
6240 // Look at the promotion type of enum types, since that is the type used
6241 // to pass enum values.
6242 if (const EnumType *Enum = argTy->getAs<EnumType>())
6243 argTy = Enum->getDecl()->getPromotionType();
6244
Eli Friedman3d815e72008-08-22 00:56:42 +00006245 if (argTy->isPromotableIntegerType() ||
6246 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6247 return QualType();
6248 }
6249
6250 if (allLTypes) return lhs;
6251 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006252
6253 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6254 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00006255 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006256 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006257 }
6258
6259 if (allLTypes) return lhs;
6260 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00006261 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00006262}
6263
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006264QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00006265 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006266 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00006267 // C++ [expr]: If an expression initially has the type "reference to T", the
6268 // type is adjusted to "T" prior to any further analysis, the expression
6269 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006270 // expression is an lvalue unless the reference is an rvalue reference and
6271 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006272 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6273 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00006274
6275 if (Unqualified) {
6276 LHS = LHS.getUnqualifiedType();
6277 RHS = RHS.getUnqualifiedType();
6278 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006279
Eli Friedman3d815e72008-08-22 00:56:42 +00006280 QualType LHSCan = getCanonicalType(LHS),
6281 RHSCan = getCanonicalType(RHS);
6282
6283 // If two types are identical, they are compatible.
6284 if (LHSCan == RHSCan)
6285 return LHS;
6286
John McCall0953e762009-09-24 19:53:00 +00006287 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006288 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6289 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00006290 if (LQuals != RQuals) {
6291 // If any of these qualifiers are different, we have a type
6292 // mismatch.
6293 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00006294 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6295 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00006296 return QualType();
6297
6298 // Exactly one GC qualifier difference is allowed: __strong is
6299 // okay if the other type has no GC qualifier but is an Objective
6300 // C object pointer (i.e. implicitly strong by default). We fix
6301 // this by pretending that the unqualified type was actually
6302 // qualified __strong.
6303 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6304 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6305 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6306
6307 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6308 return QualType();
6309
6310 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6311 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6312 }
6313 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6314 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6315 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006316 return QualType();
John McCall0953e762009-09-24 19:53:00 +00006317 }
6318
6319 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00006320
Eli Friedman852d63b2009-06-01 01:22:52 +00006321 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6322 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00006323
Chris Lattner1adb8832008-01-14 05:45:46 +00006324 // We want to consider the two function types to be the same for these
6325 // comparisons, just force one to the other.
6326 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6327 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00006328
6329 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00006330 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6331 LHSClass = Type::ConstantArray;
6332 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6333 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00006334
John McCallc12c5bb2010-05-15 11:32:37 +00006335 // ObjCInterfaces are just specialized ObjCObjects.
6336 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6337 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6338
Nate Begeman213541a2008-04-18 23:10:10 +00006339 // Canonicalize ExtVector -> Vector.
6340 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6341 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00006342
Chris Lattnera36a61f2008-04-07 05:43:21 +00006343 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006344 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00006345 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00006346 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00006347 // Compatibility is based on the underlying type, not the promotion
6348 // type.
John McCall183700f2009-09-21 23:43:11 +00006349 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006350 QualType TINT = ETy->getDecl()->getIntegerType();
6351 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006352 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006353 }
John McCall183700f2009-09-21 23:43:11 +00006354 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006355 QualType TINT = ETy->getDecl()->getIntegerType();
6356 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006357 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006358 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006359 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00006360 if (OfBlockPointer && !BlockReturnType) {
6361 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6362 return LHS;
6363 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6364 return RHS;
6365 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006366
Eli Friedman3d815e72008-08-22 00:56:42 +00006367 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00006368 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006369
Steve Naroff4a746782008-01-09 22:43:08 +00006370 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006371 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00006372#define TYPE(Class, Base)
6373#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00006374#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00006375#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6376#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6377#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00006378 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00006379
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006380 case Type::LValueReference:
6381 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00006382 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00006383 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00006384
John McCallc12c5bb2010-05-15 11:32:37 +00006385 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00006386 case Type::IncompleteArray:
6387 case Type::VariableArray:
6388 case Type::FunctionProto:
6389 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00006390 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00006391
Chris Lattner1adb8832008-01-14 05:45:46 +00006392 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00006393 {
6394 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006395 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6396 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006397 if (Unqualified) {
6398 LHSPointee = LHSPointee.getUnqualifiedType();
6399 RHSPointee = RHSPointee.getUnqualifiedType();
6400 }
6401 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6402 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006403 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00006404 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006405 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00006406 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006407 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006408 return getPointerType(ResultType);
6409 }
Steve Naroffc0febd52008-12-10 17:49:55 +00006410 case Type::BlockPointer:
6411 {
6412 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006413 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6414 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006415 if (Unqualified) {
6416 LHSPointee = LHSPointee.getUnqualifiedType();
6417 RHSPointee = RHSPointee.getUnqualifiedType();
6418 }
6419 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6420 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00006421 if (ResultType.isNull()) return QualType();
6422 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6423 return LHS;
6424 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6425 return RHS;
6426 return getBlockPointerType(ResultType);
6427 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006428 case Type::Atomic:
6429 {
6430 // Merge two pointer types, while trying to preserve typedef info
6431 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6432 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6433 if (Unqualified) {
6434 LHSValue = LHSValue.getUnqualifiedType();
6435 RHSValue = RHSValue.getUnqualifiedType();
6436 }
6437 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6438 Unqualified);
6439 if (ResultType.isNull()) return QualType();
6440 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6441 return LHS;
6442 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6443 return RHS;
6444 return getAtomicType(ResultType);
6445 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006446 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006447 {
6448 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6449 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6450 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6451 return QualType();
6452
6453 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6454 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006455 if (Unqualified) {
6456 LHSElem = LHSElem.getUnqualifiedType();
6457 RHSElem = RHSElem.getUnqualifiedType();
6458 }
6459
6460 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006461 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006462 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6463 return LHS;
6464 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6465 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006466 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6467 ArrayType::ArraySizeModifier(), 0);
6468 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6469 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006470 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6471 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006472 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6473 return LHS;
6474 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6475 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006476 if (LVAT) {
6477 // FIXME: This isn't correct! But tricky to implement because
6478 // the array's size has to be the size of LHS, but the type
6479 // has to be different.
6480 return LHS;
6481 }
6482 if (RVAT) {
6483 // FIXME: This isn't correct! But tricky to implement because
6484 // the array's size has to be the size of RHS, but the type
6485 // has to be different.
6486 return RHS;
6487 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006488 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6489 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006490 return getIncompleteArrayType(ResultType,
6491 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006492 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006493 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006494 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006495 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006496 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006497 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006498 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006499 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006500 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006501 case Type::Complex:
6502 // Distinct complex types are incompatible.
6503 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006504 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006505 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006506 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6507 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006508 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006509 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006510 case Type::ObjCObject: {
6511 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006512 // FIXME: This should be type compatibility, e.g. whether
6513 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006514 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6515 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6516 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006517 return LHS;
6518
Eli Friedman3d815e72008-08-22 00:56:42 +00006519 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006520 }
Steve Naroff14108da2009-07-10 23:34:53 +00006521 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006522 if (OfBlockPointer) {
6523 if (canAssignObjCInterfacesInBlockPointer(
6524 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006525 RHS->getAs<ObjCObjectPointerType>(),
6526 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00006527 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006528 return QualType();
6529 }
John McCall183700f2009-09-21 23:43:11 +00006530 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6531 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006532 return LHS;
6533
Steve Naroffbc76dd02008-12-10 22:14:21 +00006534 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00006535 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006536 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006537
David Blaikie7530c032012-01-17 06:56:22 +00006538 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00006539}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006540
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006541bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6542 const FunctionProtoType *FromFunctionType,
6543 const FunctionProtoType *ToFunctionType) {
6544 if (FromFunctionType->hasAnyConsumedArgs() !=
6545 ToFunctionType->hasAnyConsumedArgs())
6546 return false;
6547 FunctionProtoType::ExtProtoInfo FromEPI =
6548 FromFunctionType->getExtProtoInfo();
6549 FunctionProtoType::ExtProtoInfo ToEPI =
6550 ToFunctionType->getExtProtoInfo();
6551 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6552 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6553 ArgIdx != NumArgs; ++ArgIdx) {
6554 if (FromEPI.ConsumedArguments[ArgIdx] !=
6555 ToEPI.ConsumedArguments[ArgIdx])
6556 return false;
6557 }
6558 return true;
6559}
6560
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006561/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6562/// 'RHS' attributes and returns the merged version; including for function
6563/// return types.
6564QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6565 QualType LHSCan = getCanonicalType(LHS),
6566 RHSCan = getCanonicalType(RHS);
6567 // If two types are identical, they are compatible.
6568 if (LHSCan == RHSCan)
6569 return LHS;
6570 if (RHSCan->isFunctionType()) {
6571 if (!LHSCan->isFunctionType())
6572 return QualType();
6573 QualType OldReturnType =
6574 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6575 QualType NewReturnType =
6576 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6577 QualType ResReturnType =
6578 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6579 if (ResReturnType.isNull())
6580 return QualType();
6581 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6582 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6583 // In either case, use OldReturnType to build the new function type.
6584 const FunctionType *F = LHS->getAs<FunctionType>();
6585 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006586 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6587 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006588 QualType ResultType
6589 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006590 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006591 return ResultType;
6592 }
6593 }
6594 return QualType();
6595 }
6596
6597 // If the qualifiers are different, the types can still be merged.
6598 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6599 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6600 if (LQuals != RQuals) {
6601 // If any of these qualifiers are different, we have a type mismatch.
6602 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6603 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6604 return QualType();
6605
6606 // Exactly one GC qualifier difference is allowed: __strong is
6607 // okay if the other type has no GC qualifier but is an Objective
6608 // C object pointer (i.e. implicitly strong by default). We fix
6609 // this by pretending that the unqualified type was actually
6610 // qualified __strong.
6611 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6612 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6613 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6614
6615 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6616 return QualType();
6617
6618 if (GC_L == Qualifiers::Strong)
6619 return LHS;
6620 if (GC_R == Qualifiers::Strong)
6621 return RHS;
6622 return QualType();
6623 }
6624
6625 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6626 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6627 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6628 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6629 if (ResQT == LHSBaseQT)
6630 return LHS;
6631 if (ResQT == RHSBaseQT)
6632 return RHS;
6633 }
6634 return QualType();
6635}
6636
Chris Lattner5426bf62008-04-07 07:01:58 +00006637//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006638// Integer Predicates
6639//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006640
Jay Foad4ba2a172011-01-12 09:06:06 +00006641unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006642 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006643 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006644 if (T->isBooleanType())
6645 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006646 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006647 return (unsigned)getTypeSize(T);
6648}
6649
6650QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006651 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006652
6653 // Turn <4 x signed int> -> <4 x unsigned int>
6654 if (const VectorType *VTy = T->getAs<VectorType>())
6655 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006656 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006657
6658 // For enums, we return the unsigned version of the base type.
6659 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006660 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006661
6662 const BuiltinType *BTy = T->getAs<BuiltinType>();
6663 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006664 switch (BTy->getKind()) {
6665 case BuiltinType::Char_S:
6666 case BuiltinType::SChar:
6667 return UnsignedCharTy;
6668 case BuiltinType::Short:
6669 return UnsignedShortTy;
6670 case BuiltinType::Int:
6671 return UnsignedIntTy;
6672 case BuiltinType::Long:
6673 return UnsignedLongTy;
6674 case BuiltinType::LongLong:
6675 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006676 case BuiltinType::Int128:
6677 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006678 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006679 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006680 }
6681}
6682
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006683ASTMutationListener::~ASTMutationListener() { }
6684
Chris Lattner86df27b2009-06-14 00:45:47 +00006685
6686//===----------------------------------------------------------------------===//
6687// Builtin Type Computation
6688//===----------------------------------------------------------------------===//
6689
6690/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006691/// pointer over the consumed characters. This returns the resultant type. If
6692/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6693/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6694/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006695///
6696/// RequiresICE is filled in on return to indicate whether the value is required
6697/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006698static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006699 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006700 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006701 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006702 // Modifiers.
6703 int HowLong = 0;
6704 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006705 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006706
Chris Lattner33daae62010-10-01 22:42:38 +00006707 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006708 bool Done = false;
6709 while (!Done) {
6710 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006711 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006712 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006713 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006714 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006715 case 'S':
6716 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6717 assert(!Signed && "Can't use 'S' modifier multiple times!");
6718 Signed = true;
6719 break;
6720 case 'U':
6721 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6722 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6723 Unsigned = true;
6724 break;
6725 case 'L':
6726 assert(HowLong <= 2 && "Can't have LLLL modifier");
6727 ++HowLong;
6728 break;
6729 }
6730 }
6731
6732 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006733
Chris Lattner86df27b2009-06-14 00:45:47 +00006734 // Read the base type.
6735 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006736 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006737 case 'v':
6738 assert(HowLong == 0 && !Signed && !Unsigned &&
6739 "Bad modifiers used with 'v'!");
6740 Type = Context.VoidTy;
6741 break;
6742 case 'f':
6743 assert(HowLong == 0 && !Signed && !Unsigned &&
6744 "Bad modifiers used with 'f'!");
6745 Type = Context.FloatTy;
6746 break;
6747 case 'd':
6748 assert(HowLong < 2 && !Signed && !Unsigned &&
6749 "Bad modifiers used with 'd'!");
6750 if (HowLong)
6751 Type = Context.LongDoubleTy;
6752 else
6753 Type = Context.DoubleTy;
6754 break;
6755 case 's':
6756 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6757 if (Unsigned)
6758 Type = Context.UnsignedShortTy;
6759 else
6760 Type = Context.ShortTy;
6761 break;
6762 case 'i':
6763 if (HowLong == 3)
6764 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6765 else if (HowLong == 2)
6766 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6767 else if (HowLong == 1)
6768 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6769 else
6770 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6771 break;
6772 case 'c':
6773 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6774 if (Signed)
6775 Type = Context.SignedCharTy;
6776 else if (Unsigned)
6777 Type = Context.UnsignedCharTy;
6778 else
6779 Type = Context.CharTy;
6780 break;
6781 case 'b': // boolean
6782 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6783 Type = Context.BoolTy;
6784 break;
6785 case 'z': // size_t.
6786 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6787 Type = Context.getSizeType();
6788 break;
6789 case 'F':
6790 Type = Context.getCFConstantStringType();
6791 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006792 case 'G':
6793 Type = Context.getObjCIdType();
6794 break;
6795 case 'H':
6796 Type = Context.getObjCSelType();
6797 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006798 case 'a':
6799 Type = Context.getBuiltinVaListType();
6800 assert(!Type.isNull() && "builtin va list type not initialized!");
6801 break;
6802 case 'A':
6803 // This is a "reference" to a va_list; however, what exactly
6804 // this means depends on how va_list is defined. There are two
6805 // different kinds of va_list: ones passed by value, and ones
6806 // passed by reference. An example of a by-value va_list is
6807 // x86, where va_list is a char*. An example of by-ref va_list
6808 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6809 // we want this argument to be a char*&; for x86-64, we want
6810 // it to be a __va_list_tag*.
6811 Type = Context.getBuiltinVaListType();
6812 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006813 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006814 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006815 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006816 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006817 break;
6818 case 'V': {
6819 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006820 unsigned NumElements = strtoul(Str, &End, 10);
6821 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006822 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006823
Chris Lattner14e0e742010-10-01 22:53:11 +00006824 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6825 RequiresICE, false);
6826 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006827
6828 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006829 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006830 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006831 break;
6832 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00006833 case 'E': {
6834 char *End;
6835
6836 unsigned NumElements = strtoul(Str, &End, 10);
6837 assert(End != Str && "Missing vector size");
6838
6839 Str = End;
6840
6841 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6842 false);
6843 Type = Context.getExtVectorType(ElementType, NumElements);
6844 break;
6845 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006846 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006847 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6848 false);
6849 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006850 Type = Context.getComplexType(ElementType);
6851 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00006852 }
6853 case 'Y' : {
6854 Type = Context.getPointerDiffType();
6855 break;
6856 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006857 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006858 Type = Context.getFILEType();
6859 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006860 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006861 return QualType();
6862 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006863 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006864 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006865 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006866 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006867 else
6868 Type = Context.getjmp_bufType();
6869
Mike Stumpfd612db2009-07-28 23:47:15 +00006870 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006871 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006872 return QualType();
6873 }
6874 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00006875 case 'K':
6876 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6877 Type = Context.getucontext_tType();
6878
6879 if (Type.isNull()) {
6880 Error = ASTContext::GE_Missing_ucontext;
6881 return QualType();
6882 }
6883 break;
Mike Stump782fa302009-07-28 02:25:19 +00006884 }
Mike Stump1eb44332009-09-09 15:08:12 +00006885
Chris Lattner33daae62010-10-01 22:42:38 +00006886 // If there are modifiers and if we're allowed to parse them, go for it.
6887 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006888 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006889 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006890 default: Done = true; --Str; break;
6891 case '*':
6892 case '&': {
6893 // Both pointers and references can have their pointee types
6894 // qualified with an address space.
6895 char *End;
6896 unsigned AddrSpace = strtoul(Str, &End, 10);
6897 if (End != Str && AddrSpace != 0) {
6898 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6899 Str = End;
6900 }
6901 if (c == '*')
6902 Type = Context.getPointerType(Type);
6903 else
6904 Type = Context.getLValueReferenceType(Type);
6905 break;
6906 }
6907 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6908 case 'C':
6909 Type = Type.withConst();
6910 break;
6911 case 'D':
6912 Type = Context.getVolatileType(Type);
6913 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00006914 case 'R':
6915 Type = Type.withRestrict();
6916 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006917 }
6918 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006919
Chris Lattner14e0e742010-10-01 22:53:11 +00006920 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006921 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006922
Chris Lattner86df27b2009-06-14 00:45:47 +00006923 return Type;
6924}
6925
6926/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006927QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006928 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006929 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006930 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006931
Chris Lattner5f9e2722011-07-23 10:55:15 +00006932 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006933
Chris Lattner14e0e742010-10-01 22:53:11 +00006934 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006935 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006936 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6937 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006938 if (Error != GE_None)
6939 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006940
6941 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6942
Chris Lattner86df27b2009-06-14 00:45:47 +00006943 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006944 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006945 if (Error != GE_None)
6946 return QualType();
6947
Chris Lattner14e0e742010-10-01 22:53:11 +00006948 // If this argument is required to be an IntegerConstantExpression and the
6949 // caller cares, fill in the bitmask we return.
6950 if (RequiresICE && IntegerConstantArgs)
6951 *IntegerConstantArgs |= 1 << ArgTypes.size();
6952
Chris Lattner86df27b2009-06-14 00:45:47 +00006953 // Do array -> pointer decay. The builtin should use the decayed type.
6954 if (Ty->isArrayType())
6955 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006956
Chris Lattner86df27b2009-06-14 00:45:47 +00006957 ArgTypes.push_back(Ty);
6958 }
6959
6960 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6961 "'.' should only occur at end of builtin type list!");
6962
John McCall00ccbef2010-12-21 00:44:39 +00006963 FunctionType::ExtInfo EI;
6964 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6965
6966 bool Variadic = (TypeStr[0] == '.');
6967
6968 // We really shouldn't be making a no-proto type here, especially in C++.
6969 if (ArgTypes.empty() && Variadic)
6970 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006971
John McCalle23cf432010-12-14 08:05:40 +00006972 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006973 EPI.ExtInfo = EI;
6974 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006975
6976 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006977}
Eli Friedmana95d7572009-08-19 07:44:53 +00006978
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006979GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6980 GVALinkage External = GVA_StrongExternal;
6981
6982 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006983 switch (L) {
6984 case NoLinkage:
6985 case InternalLinkage:
6986 case UniqueExternalLinkage:
6987 return GVA_Internal;
6988
6989 case ExternalLinkage:
6990 switch (FD->getTemplateSpecializationKind()) {
6991 case TSK_Undeclared:
6992 case TSK_ExplicitSpecialization:
6993 External = GVA_StrongExternal;
6994 break;
6995
6996 case TSK_ExplicitInstantiationDefinition:
6997 return GVA_ExplicitTemplateInstantiation;
6998
6999 case TSK_ExplicitInstantiationDeclaration:
7000 case TSK_ImplicitInstantiation:
7001 External = GVA_TemplateInstantiation;
7002 break;
7003 }
7004 }
7005
7006 if (!FD->isInlined())
7007 return External;
7008
David Blaikie4e4d0842012-03-11 07:00:24 +00007009 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007010 // GNU or C99 inline semantics. Determine whether this symbol should be
7011 // externally visible.
7012 if (FD->isInlineDefinitionExternallyVisible())
7013 return External;
7014
7015 // C99 inline semantics, where the symbol is not externally visible.
7016 return GVA_C99Inline;
7017 }
7018
7019 // C++0x [temp.explicit]p9:
7020 // [ Note: The intent is that an inline function that is the subject of
7021 // an explicit instantiation declaration will still be implicitly
7022 // instantiated when used so that the body can be considered for
7023 // inlining, but that no out-of-line copy of the inline function would be
7024 // generated in the translation unit. -- end note ]
7025 if (FD->getTemplateSpecializationKind()
7026 == TSK_ExplicitInstantiationDeclaration)
7027 return GVA_C99Inline;
7028
7029 return GVA_CXXInline;
7030}
7031
7032GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7033 // If this is a static data member, compute the kind of template
7034 // specialization. Otherwise, this variable is not part of a
7035 // template.
7036 TemplateSpecializationKind TSK = TSK_Undeclared;
7037 if (VD->isStaticDataMember())
7038 TSK = VD->getTemplateSpecializationKind();
7039
7040 Linkage L = VD->getLinkage();
David Blaikie4e4d0842012-03-11 07:00:24 +00007041 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007042 VD->getType()->getLinkage() == UniqueExternalLinkage)
7043 L = UniqueExternalLinkage;
7044
7045 switch (L) {
7046 case NoLinkage:
7047 case InternalLinkage:
7048 case UniqueExternalLinkage:
7049 return GVA_Internal;
7050
7051 case ExternalLinkage:
7052 switch (TSK) {
7053 case TSK_Undeclared:
7054 case TSK_ExplicitSpecialization:
7055 return GVA_StrongExternal;
7056
7057 case TSK_ExplicitInstantiationDeclaration:
7058 llvm_unreachable("Variable should not be instantiated");
7059 // Fall through to treat this like any other instantiation.
7060
7061 case TSK_ExplicitInstantiationDefinition:
7062 return GVA_ExplicitTemplateInstantiation;
7063
7064 case TSK_ImplicitInstantiation:
7065 return GVA_TemplateInstantiation;
7066 }
7067 }
7068
David Blaikie7530c032012-01-17 06:56:22 +00007069 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007070}
7071
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007072bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007073 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7074 if (!VD->isFileVarDecl())
7075 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00007076 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007077 return false;
7078
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007079 // Weak references don't produce any output by themselves.
7080 if (D->hasAttr<WeakRefAttr>())
7081 return false;
7082
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007083 // Aliases and used decls are required.
7084 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7085 return true;
7086
7087 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7088 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007089 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007090 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007091
7092 // Constructors and destructors are required.
7093 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7094 return true;
7095
7096 // The key function for a class is required.
7097 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7098 const CXXRecordDecl *RD = MD->getParent();
7099 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7100 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7101 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7102 return true;
7103 }
7104 }
7105
7106 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7107
7108 // static, static inline, always_inline, and extern inline functions can
7109 // always be deferred. Normal inline functions can be deferred in C99/C++.
7110 // Implicit template instantiations can also be deferred in C++.
7111 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007112 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007113 return false;
7114 return true;
7115 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007116
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007117 const VarDecl *VD = cast<VarDecl>(D);
7118 assert(VD->isFileVarDecl() && "Expected file scoped var");
7119
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007120 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7121 return false;
7122
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007123 // Structs that have non-trivial constructors or destructors are required.
7124
7125 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00007126 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007127 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7128 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00007129 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7130 RD->hasTrivialCopyConstructor() &&
7131 RD->hasTrivialMoveConstructor() &&
7132 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007133 return true;
7134 }
7135 }
7136
7137 GVALinkage L = GetGVALinkageForVariable(VD);
7138 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7139 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7140 return false;
7141 }
7142
7143 return true;
7144}
Charles Davis071cc7d2010-08-16 03:33:14 +00007145
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007146CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007147 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007148 return ABI->getDefaultMethodCallConv(isVariadic);
7149}
7150
7151CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7152 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7153 return CC_Default;
7154 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007155}
7156
Jay Foad4ba2a172011-01-12 09:06:06 +00007157bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007158 // Pass through to the C++ ABI object
7159 return ABI->isNearlyEmpty(RD);
7160}
7161
Peter Collingbourne14110472011-01-13 18:57:25 +00007162MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007163 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00007164 case CXXABI_ARM:
7165 case CXXABI_Itanium:
7166 return createItaniumMangleContext(*this, getDiagnostics());
7167 case CXXABI_Microsoft:
7168 return createMicrosoftMangleContext(*this, getDiagnostics());
7169 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007170 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007171}
7172
Charles Davis071cc7d2010-08-16 03:33:14 +00007173CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007174
7175size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007176 return ASTRecordLayouts.getMemorySize()
7177 + llvm::capacity_in_bytes(ObjCLayouts)
7178 + llvm::capacity_in_bytes(KeyFunctions)
7179 + llvm::capacity_in_bytes(ObjCImpls)
7180 + llvm::capacity_in_bytes(BlockVarCopyInits)
7181 + llvm::capacity_in_bytes(DeclAttrs)
7182 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7183 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7184 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7185 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7186 + llvm::capacity_in_bytes(OverriddenMethods)
7187 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007188 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007189 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007190}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007191
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00007192unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7193 CXXRecordDecl *Lambda = CallOperator->getParent();
7194 return LambdaMangleContexts[Lambda->getDeclContext()]
7195 .getManglingNumber(CallOperator);
7196}
7197
7198
Ted Kremenekd211cb72011-10-06 05:00:56 +00007199void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7200 ParamIndices[D] = index;
7201}
7202
7203unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7204 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7205 assert(I != ParamIndices.end() &&
7206 "ParmIndices lacks entry set by ParmVarDecl");
7207 return I->second;
7208}