blob: 12f1d4de039a258f0a0758663e80f7f6998bd514 [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 Gribenkoaa0cd852012-06-20 00:34:58 +000059const RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
60 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
81 // If the declaration doesn't map directly to a location in a file, we
82 // can't find the comment.
83 SourceLocation DeclLoc = D->getLocation();
84 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
85 return NULL;
86
87 // Find the comment that occurs just after this declaration.
Dmitri Gribenko811c8202012-07-06 18:19:34 +000088 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
89 ArrayRef<RawComment *>::iterator Comment
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000090 = std::lower_bound(RawComments.begin(),
91 RawComments.end(),
Dmitri Gribenko811c8202012-07-06 18:19:34 +000092 &CommentAtDeclLoc,
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000093 BeforeThanCompare<RawComment>(SourceMgr));
94
95 // Decompose the location for the declaration and find the beginning of the
96 // file buffer.
97 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
98
99 // First check whether we have a trailing comment.
100 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000101 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000102 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D)) {
103 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000104 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000105 // Check that Doxygen trailing comment comes after the declaration, starts
106 // on the same line and in the same file as the declaration.
107 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
108 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
109 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
110 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000111 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000112 }
113 }
114
115 // The comment just after the declaration was not a trailing comment.
116 // Let's look at the previous comment.
117 if (Comment == RawComments.begin())
118 return NULL;
119 --Comment;
120
121 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000122 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000123 return NULL;
124
125 // Decompose the end of the comment.
126 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000127 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000128
129 // If the comment and the declaration aren't in the same file, then they
130 // aren't related.
131 if (DeclLocDecomp.first != CommentEndDecomp.first)
132 return NULL;
133
134 // Get the corresponding buffer.
135 bool Invalid = false;
136 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
137 &Invalid).data();
138 if (Invalid)
139 return NULL;
140
141 // Extract text between the comment and declaration.
142 StringRef Text(Buffer + CommentEndDecomp.second,
143 DeclLocDecomp.second - CommentEndDecomp.second);
144
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000145 // There should be no other declarations or preprocessor directives between
146 // comment and declaration.
147 if (Text.find_first_of(",;{}#") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000148 return NULL;
149
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000150 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000151}
152
153const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const {
154 // Check whether we have cached a comment string for this declaration
155 // already.
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000156 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000157 = DeclComments.find(D);
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000158 if (Pos != DeclComments.end()) {
159 RawAndParsedComment C = Pos->second;
160 return C.first;
161 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000162
163 const RawComment *RC = getRawCommentForDeclNoCache(D);
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000164 // If we found a comment, it should be a documentation comment.
165 assert(!RC || RC->isDocumentation());
Dmitri Gribenko9bf997e2012-07-06 15:40:08 +0000166 DeclComments[D] =
167 RawAndParsedComment(RC, static_cast<comments::FullComment *>(NULL));
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000168 return RC;
169}
170
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000171comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const {
172 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
173 = DeclComments.find(D);
174 const RawComment *RC;
175 if (Pos != DeclComments.end()) {
176 RawAndParsedComment C = Pos->second;
177 if (comments::FullComment *FC = C.second)
178 return FC;
179 RC = C.first;
180 } else
181 RC = getRawCommentForDecl(D);
182
183 if (!RC)
184 return NULL;
185
186 const StringRef RawText = RC->getRawText(SourceMgr);
187 comments::Lexer L(RC->getSourceRange().getBegin(), comments::CommentOptions(),
188 RawText.begin(), RawText.end());
189
190 comments::Sema S(this->BumpAlloc);
191 comments::Parser P(L, S, this->BumpAlloc);
192
193 comments::FullComment *FC = P.parseFullComment();
194 DeclComments[D].second = FC;
195 return FC;
196}
197
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000198void
199ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
200 TemplateTemplateParmDecl *Parm) {
201 ID.AddInteger(Parm->getDepth());
202 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000203 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000204
205 TemplateParameterList *Params = Parm->getTemplateParameters();
206 ID.AddInteger(Params->size());
207 for (TemplateParameterList::const_iterator P = Params->begin(),
208 PEnd = Params->end();
209 P != PEnd; ++P) {
210 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
211 ID.AddInteger(0);
212 ID.AddBoolean(TTP->isParameterPack());
213 continue;
214 }
215
216 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
217 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000218 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000219 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000220 if (NTTP->isExpandedParameterPack()) {
221 ID.AddBoolean(true);
222 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000223 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
224 QualType T = NTTP->getExpansionType(I);
225 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
226 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000227 } else
228 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000229 continue;
230 }
231
232 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
233 ID.AddInteger(2);
234 Profile(ID, TTP);
235 }
236}
237
238TemplateTemplateParmDecl *
239ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000240 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000241 // Check if we already have a canonical template template parameter.
242 llvm::FoldingSetNodeID ID;
243 CanonicalTemplateTemplateParm::Profile(ID, TTP);
244 void *InsertPos = 0;
245 CanonicalTemplateTemplateParm *Canonical
246 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
247 if (Canonical)
248 return Canonical->getParam();
249
250 // Build a canonical template parameter list.
251 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000252 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000253 CanonParams.reserve(Params->size());
254 for (TemplateParameterList::const_iterator P = Params->begin(),
255 PEnd = Params->end();
256 P != PEnd; ++P) {
257 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
258 CanonParams.push_back(
259 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000260 SourceLocation(),
261 SourceLocation(),
262 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000263 TTP->getIndex(), 0, false,
264 TTP->isParameterPack()));
265 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000266 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
267 QualType T = getCanonicalType(NTTP->getType());
268 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
269 NonTypeTemplateParmDecl *Param;
270 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000271 SmallVector<QualType, 2> ExpandedTypes;
272 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000273 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
274 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
275 ExpandedTInfos.push_back(
276 getTrivialTypeSourceInfo(ExpandedTypes.back()));
277 }
278
279 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000280 SourceLocation(),
281 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000282 NTTP->getDepth(),
283 NTTP->getPosition(), 0,
284 T,
285 TInfo,
286 ExpandedTypes.data(),
287 ExpandedTypes.size(),
288 ExpandedTInfos.data());
289 } else {
290 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000291 SourceLocation(),
292 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000293 NTTP->getDepth(),
294 NTTP->getPosition(), 0,
295 T,
296 NTTP->isParameterPack(),
297 TInfo);
298 }
299 CanonParams.push_back(Param);
300
301 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000302 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
303 cast<TemplateTemplateParmDecl>(*P)));
304 }
305
306 TemplateTemplateParmDecl *CanonTTP
307 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
308 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000309 TTP->getPosition(),
310 TTP->isParameterPack(),
311 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000312 TemplateParameterList::Create(*this, SourceLocation(),
313 SourceLocation(),
314 CanonParams.data(),
315 CanonParams.size(),
316 SourceLocation()));
317
318 // Get the new insert position for the node we care about.
319 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
320 assert(Canonical == 0 && "Shouldn't be in the map!");
321 (void)Canonical;
322
323 // Create the canonical template template parameter entry.
324 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
325 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
326 return CanonTTP;
327}
328
Charles Davis071cc7d2010-08-16 03:33:14 +0000329CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000330 if (!LangOpts.CPlusPlus) return 0;
331
Charles Davis20cf7172010-08-19 02:18:14 +0000332 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000333 case CXXABI_ARM:
334 return CreateARMCXXABI(*this);
335 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000336 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000337 case CXXABI_Microsoft:
338 return CreateMicrosoftCXXABI(*this);
339 }
David Blaikie7530c032012-01-17 06:56:22 +0000340 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000341}
342
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000343static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000344 const LangOptions &LOpts) {
345 if (LOpts.FakeAddressSpaceMap) {
346 // The fake address space map must have a distinct entry for each
347 // language-specific address space.
348 static const unsigned FakeAddrSpaceMap[] = {
349 1, // opencl_global
350 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000351 3, // opencl_constant
352 4, // cuda_device
353 5, // cuda_constant
354 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000355 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000356 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000357 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000358 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000359 }
360}
361
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000362ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000363 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000364 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000365 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000366 unsigned size_reserve,
367 bool DelayInitialization)
368 : FunctionProtoTypes(this_()),
369 TemplateSpecializationTypes(this_()),
370 DependentTemplateSpecializationTypes(this_()),
371 SubstTemplateTemplateParmPacks(this_()),
372 GlobalNestedNameSpecifier(0),
373 Int128Decl(0), UInt128Decl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000374 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000375 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000376 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000377 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000378 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
379 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
380 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000381 NullTypeSourceInfo(QualType()),
382 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000383 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000384 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000385 Idents(idents), Selectors(sels),
386 BuiltinInfo(builtins),
387 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000388 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000389 Comments(SM), CommentsLoaded(false),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000390 LastSDM(0, 0),
391 UniqueBlockByRefTypeID(0)
392{
Mike Stump1eb44332009-09-09 15:08:12 +0000393 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000394 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000395
396 if (!DelayInitialization) {
397 assert(t && "No target supplied for ASTContext initialization");
398 InitBuiltinTypes(*t);
399 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000400}
401
Reid Spencer5f016e22007-07-11 17:01:13 +0000402ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000403 // Release the DenseMaps associated with DeclContext objects.
404 // FIXME: Is this the ideal solution?
405 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000406
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000407 // Call all of the deallocation functions.
408 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
409 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000410
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000411 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000412 // because they can contain DenseMaps.
413 for (llvm::DenseMap<const ObjCContainerDecl*,
414 const ASTRecordLayout*>::iterator
415 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
416 // Increment in loop to prevent using deallocated memory.
417 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
418 R->Destroy(*this);
419
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000420 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
421 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
422 // Increment in loop to prevent using deallocated memory.
423 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
424 R->Destroy(*this);
425 }
Douglas Gregor63200642010-08-30 16:49:28 +0000426
427 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
428 AEnd = DeclAttrs.end();
429 A != AEnd; ++A)
430 A->second->~AttrVec();
431}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000432
Douglas Gregor00545312010-05-23 18:26:36 +0000433void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
434 Deallocations.push_back(std::make_pair(Callback, Data));
435}
436
Mike Stump1eb44332009-09-09 15:08:12 +0000437void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000438ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000439 ExternalSource.reset(Source.take());
440}
441
Reid Spencer5f016e22007-07-11 17:01:13 +0000442void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000443 llvm::errs() << "\n*** AST Context Stats:\n";
444 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000445
Douglas Gregordbe833d2009-05-26 14:40:08 +0000446 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000447#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000448#define ABSTRACT_TYPE(Name, Parent)
449#include "clang/AST/TypeNodes.def"
450 0 // Extra
451 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000452
Reid Spencer5f016e22007-07-11 17:01:13 +0000453 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
454 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000455 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000456 }
457
Douglas Gregordbe833d2009-05-26 14:40:08 +0000458 unsigned Idx = 0;
459 unsigned TotalBytes = 0;
460#define TYPE(Name, Parent) \
461 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000462 llvm::errs() << " " << counts[Idx] << " " << #Name \
463 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000464 TotalBytes += counts[Idx] * sizeof(Name##Type); \
465 ++Idx;
466#define ABSTRACT_TYPE(Name, Parent)
467#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Chandler Carruthcd92a652011-07-04 05:32:14 +0000469 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
470
Douglas Gregor4923aa22010-07-02 20:37:36 +0000471 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000472 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
473 << NumImplicitDefaultConstructors
474 << " implicit default constructors created\n";
475 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
476 << NumImplicitCopyConstructors
477 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000478 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000479 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
480 << NumImplicitMoveConstructors
481 << " implicit move constructors created\n";
482 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
483 << NumImplicitCopyAssignmentOperators
484 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000485 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000486 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
487 << NumImplicitMoveAssignmentOperators
488 << " implicit move assignment operators created\n";
489 llvm::errs() << NumImplicitDestructorsDeclared << "/"
490 << NumImplicitDestructors
491 << " implicit destructors created\n";
492
Douglas Gregor2cf26342009-04-09 22:27:44 +0000493 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000494 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000495 ExternalSource->PrintStats();
496 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000497
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000498 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000499}
500
Douglas Gregor772eeae2011-08-12 06:49:56 +0000501TypedefDecl *ASTContext::getInt128Decl() const {
502 if (!Int128Decl) {
503 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
504 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
505 getTranslationUnitDecl(),
506 SourceLocation(),
507 SourceLocation(),
508 &Idents.get("__int128_t"),
509 TInfo);
510 }
511
512 return Int128Decl;
513}
514
515TypedefDecl *ASTContext::getUInt128Decl() const {
516 if (!UInt128Decl) {
517 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
518 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
519 getTranslationUnitDecl(),
520 SourceLocation(),
521 SourceLocation(),
522 &Idents.get("__uint128_t"),
523 TInfo);
524 }
525
526 return UInt128Decl;
527}
Reid Spencer5f016e22007-07-11 17:01:13 +0000528
John McCalle27ec8a2009-10-23 23:03:21 +0000529void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000530 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000531 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000532 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000533}
534
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000535void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
536 assert((!this->Target || this->Target == &Target) &&
537 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000538 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000540 this->Target = &Target;
541
542 ABI.reset(createCXXABI(Target));
543 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
544
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 // C99 6.2.5p19.
546 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Reid Spencer5f016e22007-07-11 17:01:13 +0000548 // C99 6.2.5p2.
549 InitBuiltinType(BoolTy, BuiltinType::Bool);
550 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000551 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000552 InitBuiltinType(CharTy, BuiltinType::Char_S);
553 else
554 InitBuiltinType(CharTy, BuiltinType::Char_U);
555 // C99 6.2.5p4.
556 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
557 InitBuiltinType(ShortTy, BuiltinType::Short);
558 InitBuiltinType(IntTy, BuiltinType::Int);
559 InitBuiltinType(LongTy, BuiltinType::Long);
560 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 // C99 6.2.5p6.
563 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
564 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
565 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
566 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
567 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 // C99 6.2.5p10.
570 InitBuiltinType(FloatTy, BuiltinType::Float);
571 InitBuiltinType(DoubleTy, BuiltinType::Double);
572 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000573
Chris Lattner2df9ced2009-04-30 02:43:43 +0000574 // GNU extension, 128-bit integers.
575 InitBuiltinType(Int128Ty, BuiltinType::Int128);
576 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
577
Chris Lattner3f59c972010-12-25 23:25:43 +0000578 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000579 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000580 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
581 else // -fshort-wchar makes wchar_t be unsigned.
582 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
583 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000584 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000585
James Molloy392da482012-05-04 10:55:22 +0000586 WIntTy = getFromTargetType(Target.getWIntType());
587
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000588 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
589 InitBuiltinType(Char16Ty, BuiltinType::Char16);
590 else // C99
591 Char16Ty = getFromTargetType(Target.getChar16Type());
592
593 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
594 InitBuiltinType(Char32Ty, BuiltinType::Char32);
595 else // C99
596 Char32Ty = getFromTargetType(Target.getChar32Type());
597
Douglas Gregor898574e2008-12-05 23:32:09 +0000598 // Placeholder type for type-dependent expressions whose type is
599 // completely unknown. No code should ever check a type against
600 // DependentTy and users should never see it; however, it is here to
601 // help diagnose failures to properly check for type-dependent
602 // expressions.
603 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000604
John McCall2a984ca2010-10-12 00:20:44 +0000605 // Placeholder type for functions.
606 InitBuiltinType(OverloadTy, BuiltinType::Overload);
607
John McCall864c0412011-04-26 20:42:42 +0000608 // Placeholder type for bound members.
609 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
610
John McCall3c3b7f92011-10-25 17:37:35 +0000611 // Placeholder type for pseudo-objects.
612 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
613
John McCall1de4d4e2011-04-07 08:22:57 +0000614 // "any" type; useful for debugger-like clients.
615 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
616
John McCall0ddaeb92011-10-17 18:09:15 +0000617 // Placeholder type for unbridged ARC casts.
618 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
619
Reid Spencer5f016e22007-07-11 17:01:13 +0000620 // C99 6.2.5p11.
621 FloatComplexTy = getComplexType(FloatTy);
622 DoubleComplexTy = getComplexType(DoubleTy);
623 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000624
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000625 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000626 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
627 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000628 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000629
630 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000631 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
632 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000633
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000634 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000636 // void * type
637 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000638
639 // nullptr type (C++0x 2.14.7)
640 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000641
642 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
643 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +0000644
645 // Builtin type used to help define __builtin_va_list.
646 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000647}
648
David Blaikied6471f72011-09-25 23:23:43 +0000649DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000650 return SourceMgr.getDiagnostics();
651}
652
Douglas Gregor63200642010-08-30 16:49:28 +0000653AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
654 AttrVec *&Result = DeclAttrs[D];
655 if (!Result) {
656 void *Mem = Allocate(sizeof(AttrVec));
657 Result = new (Mem) AttrVec;
658 }
659
660 return *Result;
661}
662
663/// \brief Erase the attributes corresponding to the given declaration.
664void ASTContext::eraseDeclAttrs(const Decl *D) {
665 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
666 if (Pos != DeclAttrs.end()) {
667 Pos->second->~AttrVec();
668 DeclAttrs.erase(Pos);
669 }
670}
671
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000672MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000673ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000674 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000675 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000676 = InstantiatedFromStaticDataMember.find(Var);
677 if (Pos == InstantiatedFromStaticDataMember.end())
678 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Douglas Gregor7caa6822009-07-24 20:34:43 +0000680 return Pos->second;
681}
682
Mike Stump1eb44332009-09-09 15:08:12 +0000683void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000684ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000685 TemplateSpecializationKind TSK,
686 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000687 assert(Inst->isStaticDataMember() && "Not a static data member");
688 assert(Tmpl->isStaticDataMember() && "Not a static data member");
689 assert(!InstantiatedFromStaticDataMember[Inst] &&
690 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000691 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000692 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000693}
694
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000695FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
696 const FunctionDecl *FD){
697 assert(FD && "Specialization is 0");
698 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000699 = ClassScopeSpecializationPattern.find(FD);
700 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000701 return 0;
702
703 return Pos->second;
704}
705
706void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
707 FunctionDecl *Pattern) {
708 assert(FD && "Specialization is 0");
709 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000710 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000711}
712
John McCall7ba107a2009-11-18 02:36:19 +0000713NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000714ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000715 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000716 = InstantiatedFromUsingDecl.find(UUD);
717 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000718 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Anders Carlsson0d8df782009-08-29 19:37:28 +0000720 return Pos->second;
721}
722
723void
John McCalled976492009-12-04 22:46:56 +0000724ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
725 assert((isa<UsingDecl>(Pattern) ||
726 isa<UnresolvedUsingValueDecl>(Pattern) ||
727 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
728 "pattern decl is not a using decl");
729 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
730 InstantiatedFromUsingDecl[Inst] = Pattern;
731}
732
733UsingShadowDecl *
734ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
735 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
736 = InstantiatedFromUsingShadowDecl.find(Inst);
737 if (Pos == InstantiatedFromUsingShadowDecl.end())
738 return 0;
739
740 return Pos->second;
741}
742
743void
744ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
745 UsingShadowDecl *Pattern) {
746 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
747 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000748}
749
Anders Carlssond8b285f2009-09-01 04:26:58 +0000750FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
751 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
752 = InstantiatedFromUnnamedFieldDecl.find(Field);
753 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
754 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Anders Carlssond8b285f2009-09-01 04:26:58 +0000756 return Pos->second;
757}
758
759void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
760 FieldDecl *Tmpl) {
761 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
762 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
763 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
764 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Anders Carlssond8b285f2009-09-01 04:26:58 +0000766 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
767}
768
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000769bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
770 const FieldDecl *LastFD) const {
771 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000772 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000773}
774
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000775bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
776 const FieldDecl *LastFD) const {
777 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000778 FD->getBitWidthValue(*this) == 0 &&
779 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000780}
781
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000782bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
783 const FieldDecl *LastFD) const {
784 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000785 FD->getBitWidthValue(*this) &&
786 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000787}
788
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000789bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000790 const FieldDecl *LastFD) const {
791 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000792 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000793}
794
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000795bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000796 const FieldDecl *LastFD) const {
797 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000798 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000799}
800
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000801ASTContext::overridden_cxx_method_iterator
802ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
803 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
804 = OverriddenMethods.find(Method);
805 if (Pos == OverriddenMethods.end())
806 return 0;
807
808 return Pos->second.begin();
809}
810
811ASTContext::overridden_cxx_method_iterator
812ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
813 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
814 = OverriddenMethods.find(Method);
815 if (Pos == OverriddenMethods.end())
816 return 0;
817
818 return Pos->second.end();
819}
820
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000821unsigned
822ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
823 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
824 = OverriddenMethods.find(Method);
825 if (Pos == OverriddenMethods.end())
826 return 0;
827
828 return Pos->second.size();
829}
830
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000831void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
832 const CXXMethodDecl *Overridden) {
833 OverriddenMethods[Method].push_back(Overridden);
834}
835
Douglas Gregore6649772011-12-03 00:30:27 +0000836void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
837 assert(!Import->NextLocalImport && "Import declaration already in the chain");
838 assert(!Import->isFromASTFile() && "Non-local import declaration");
839 if (!FirstLocalImport) {
840 FirstLocalImport = Import;
841 LastLocalImport = Import;
842 return;
843 }
844
845 LastLocalImport->NextLocalImport = Import;
846 LastLocalImport = Import;
847}
848
Chris Lattner464175b2007-07-18 17:52:12 +0000849//===----------------------------------------------------------------------===//
850// Type Sizing and Analysis
851//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000852
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000853/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
854/// scalar floating point type.
855const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000856 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000857 assert(BT && "Not a floating point type!");
858 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000859 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000860 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000861 case BuiltinType::Float: return Target->getFloatFormat();
862 case BuiltinType::Double: return Target->getDoubleFormat();
863 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000864 }
865}
866
Ken Dyck8b752f12010-01-27 17:10:57 +0000867/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000868/// specified decl. Note that bitfields do not have a valid alignment, so
869/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000870/// If @p RefAsPointee, references are treated like their underlying type
871/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000872CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000873 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +0000874
John McCall4081a5c2010-10-08 18:24:19 +0000875 bool UseAlignAttrOnly = false;
876 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
877 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000878
John McCall4081a5c2010-10-08 18:24:19 +0000879 // __attribute__((aligned)) can increase or decrease alignment
880 // *except* on a struct or struct member, where it only increases
881 // alignment unless 'packed' is also specified.
882 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +0000883 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +0000884 // ignore that possibility; Sema should diagnose it.
885 if (isa<FieldDecl>(D)) {
886 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
887 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
888 } else {
889 UseAlignAttrOnly = true;
890 }
891 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000892 else if (isa<FieldDecl>(D))
893 UseAlignAttrOnly =
894 D->hasAttr<PackedAttr>() ||
895 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000896
John McCallba4f5d52011-01-20 07:57:12 +0000897 // If we're using the align attribute only, just ignore everything
898 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000899 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000900 // do nothing
901
John McCall4081a5c2010-10-08 18:24:19 +0000902 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000903 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000904 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000905 if (RefAsPointee)
906 T = RT->getPointeeType();
907 else
908 T = getPointerType(RT->getPointeeType());
909 }
910 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000911 // Adjust alignments of declarations with array type by the
912 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000913 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000914 const ArrayType *arrayType;
915 if (MinWidth && (arrayType = getAsArrayType(T))) {
916 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000917 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +0000918 else if (isa<ConstantArrayType>(arrayType) &&
919 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000920 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000921
John McCall3b657512011-01-19 10:06:00 +0000922 // Walk through any array types while we're at it.
923 T = getBaseElementType(arrayType);
924 }
Chad Rosier9f1210c2011-07-26 07:03:04 +0000925 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +0000926 }
John McCallba4f5d52011-01-20 07:57:12 +0000927
928 // Fields can be subject to extra alignment constraints, like if
929 // the field is packed, the struct is packed, or the struct has a
930 // a max-field-alignment constraint (#pragma pack). So calculate
931 // the actual alignment of the field within the struct, and then
932 // (as we're expected to) constrain that by the alignment of the type.
933 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
934 // So calculate the alignment of the field.
935 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
936
937 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000938 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000939
940 // Use the GCD of that and the offset within the record.
941 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
942 if (offset > 0) {
943 // Alignment is always a power of 2, so the GCD will be a power of 2,
944 // which means we get to do this crazy thing instead of Euclid's.
945 uint64_t lowBitOfOffset = offset & (~offset + 1);
946 if (lowBitOfOffset < fieldAlign)
947 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
948 }
949
950 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000951 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000952 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000953
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000954 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000955}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000956
John McCallea1471e2010-05-20 01:18:31 +0000957std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000958ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000959 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000960 return std::make_pair(toCharUnitsFromBits(Info.first),
961 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000962}
963
964std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000965ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000966 return getTypeInfoInChars(T.getTypePtr());
967}
968
Daniel Dunbarbc5419a2012-03-09 04:12:54 +0000969std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
970 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
971 if (it != MemoizedTypeInfo.end())
972 return it->second;
973
974 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
975 MemoizedTypeInfo.insert(std::make_pair(T, Info));
976 return Info;
977}
978
979/// getTypeInfoImpl - Return the size of the specified type, in bits. This
980/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000981///
982/// FIXME: Pointers into different addr spaces could have different sizes and
983/// alignment requirements: getPointerInfo should take an AddrSpace, this
984/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000985std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +0000986ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000987 uint64_t Width=0;
988 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000989 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000990#define TYPE(Class, Base)
991#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000992#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000993#define DEPENDENT_TYPE(Class, Base) case Type::Class:
994#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +0000995 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000996
Chris Lattner692233e2007-07-13 22:27:08 +0000997 case Type::FunctionNoProto:
998 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000999 // GCC extension: alignof(function) = 32 bits
1000 Width = 0;
1001 Align = 32;
1002 break;
1003
Douglas Gregor72564e72009-02-26 23:50:07 +00001004 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001005 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001006 Width = 0;
1007 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1008 break;
1009
Steve Narofffb22d962007-08-30 01:06:46 +00001010 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001011 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Chris Lattner98be4942008-03-05 18:54:05 +00001013 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001014 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001015 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1016 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001017 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001018 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001019 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001020 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001021 }
Nate Begeman213541a2008-04-18 23:10:10 +00001022 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001023 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001024 const VectorType *VT = cast<VectorType>(T);
1025 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1026 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001027 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001028 // If the alignment is not a power of 2, round up to the next power of 2.
1029 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001030 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001031 Align = llvm::NextPowerOf2(Align);
1032 Width = llvm::RoundUpToAlignment(Width, Align);
1033 }
Chris Lattner030d8842007-07-19 22:06:24 +00001034 break;
1035 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001036
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001037 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001038 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001039 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001040 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001041 // GCC extension: alignof(void) = 8 bits.
1042 Width = 0;
1043 Align = 8;
1044 break;
1045
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001046 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001047 Width = Target->getBoolWidth();
1048 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001049 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001050 case BuiltinType::Char_S:
1051 case BuiltinType::Char_U:
1052 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001053 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001054 Width = Target->getCharWidth();
1055 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001056 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001057 case BuiltinType::WChar_S:
1058 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001059 Width = Target->getWCharWidth();
1060 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001061 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001062 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001063 Width = Target->getChar16Width();
1064 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001065 break;
1066 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001067 Width = Target->getChar32Width();
1068 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001069 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001070 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001071 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001072 Width = Target->getShortWidth();
1073 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001074 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001075 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001076 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001077 Width = Target->getIntWidth();
1078 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001079 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001080 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001081 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001082 Width = Target->getLongWidth();
1083 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001084 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001085 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001086 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001087 Width = Target->getLongLongWidth();
1088 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001089 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001090 case BuiltinType::Int128:
1091 case BuiltinType::UInt128:
1092 Width = 128;
1093 Align = 128; // int128_t is 128-bit aligned on all targets.
1094 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001095 case BuiltinType::Half:
1096 Width = Target->getHalfWidth();
1097 Align = Target->getHalfAlign();
1098 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001099 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001100 Width = Target->getFloatWidth();
1101 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001102 break;
1103 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001104 Width = Target->getDoubleWidth();
1105 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001106 break;
1107 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001108 Width = Target->getLongDoubleWidth();
1109 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001110 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001111 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001112 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1113 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001114 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001115 case BuiltinType::ObjCId:
1116 case BuiltinType::ObjCClass:
1117 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001118 Width = Target->getPointerWidth(0);
1119 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001120 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001121 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001122 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001123 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001124 Width = Target->getPointerWidth(0);
1125 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001126 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001127 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001128 unsigned AS = getTargetAddressSpace(
1129 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001130 Width = Target->getPointerWidth(AS);
1131 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001132 break;
1133 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001134 case Type::LValueReference:
1135 case Type::RValueReference: {
1136 // alignof and sizeof should never enter this code path here, so we go
1137 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001138 unsigned AS = getTargetAddressSpace(
1139 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001140 Width = Target->getPointerWidth(AS);
1141 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001142 break;
1143 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001144 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001145 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001146 Width = Target->getPointerWidth(AS);
1147 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001148 break;
1149 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001150 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001151 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001152 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001153 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +00001154 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001155 Align = PtrDiffInfo.second;
1156 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001157 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001158 case Type::Complex: {
1159 // Complex types have the same alignment as their elements, but twice the
1160 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001161 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001162 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001163 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001164 Align = EltInfo.second;
1165 break;
1166 }
John McCallc12c5bb2010-05-15 11:32:37 +00001167 case Type::ObjCObject:
1168 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001169 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001170 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001171 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001172 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001173 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001174 break;
1175 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001176 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001177 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001178 const TagType *TT = cast<TagType>(T);
1179
1180 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001181 Width = 8;
1182 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001183 break;
1184 }
Mike Stump1eb44332009-09-09 15:08:12 +00001185
Daniel Dunbar1d751182008-11-08 05:48:37 +00001186 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001187 return getTypeInfo(ET->getDecl()->getIntegerType());
1188
Daniel Dunbar1d751182008-11-08 05:48:37 +00001189 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001190 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001191 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001192 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001193 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001194 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001195
Chris Lattner9fcfe922009-10-22 05:17:15 +00001196 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001197 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1198 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001199
Richard Smith34b41d92011-02-20 03:19:35 +00001200 case Type::Auto: {
1201 const AutoType *A = cast<AutoType>(T);
1202 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001203 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001204 }
1205
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001206 case Type::Paren:
1207 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1208
Douglas Gregor18857642009-04-30 17:32:17 +00001209 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001210 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001211 std::pair<uint64_t, unsigned> Info
1212 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001213 // If the typedef has an aligned attribute on it, it overrides any computed
1214 // alignment we have. This violates the GCC documentation (which says that
1215 // attribute(aligned) can only round up) but matches its implementation.
1216 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1217 Align = AttrAlign;
1218 else
1219 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001220 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001221 break;
Chris Lattner71763312008-04-06 22:05:18 +00001222 }
Douglas Gregor18857642009-04-30 17:32:17 +00001223
1224 case Type::TypeOfExpr:
1225 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1226 .getTypePtr());
1227
1228 case Type::TypeOf:
1229 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1230
Anders Carlsson395b4752009-06-24 19:06:50 +00001231 case Type::Decltype:
1232 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1233 .getTypePtr());
1234
Sean Huntca63c202011-05-24 22:41:36 +00001235 case Type::UnaryTransform:
1236 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1237
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001238 case Type::Elaborated:
1239 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001240
John McCall9d156a72011-01-06 01:58:22 +00001241 case Type::Attributed:
1242 return getTypeInfo(
1243 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1244
Richard Smith3e4c6c42011-05-05 21:57:07 +00001245 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001246 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001247 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001248 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1249 // A type alias template specialization may refer to a typedef with the
1250 // aligned attribute on it.
1251 if (TST->isTypeAlias())
1252 return getTypeInfo(TST->getAliasedType().getTypePtr());
1253 else
1254 return getTypeInfo(getCanonicalType(T));
1255 }
1256
Eli Friedmanb001de72011-10-06 23:00:33 +00001257 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001258 std::pair<uint64_t, unsigned> Info
1259 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1260 Width = Info.first;
1261 Align = Info.second;
1262 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1263 llvm::isPowerOf2_64(Width)) {
1264 // We can potentially perform lock-free atomic operations for this
1265 // type; promote the alignment appropriately.
1266 // FIXME: We could potentially promote the width here as well...
1267 // is that worthwhile? (Non-struct atomic types generally have
1268 // power-of-two size anyway, but structs might not. Requires a bit
1269 // of implementation work to make sure we zero out the extra bits.)
1270 Align = static_cast<unsigned>(Width);
1271 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001272 }
1273
Douglas Gregor18857642009-04-30 17:32:17 +00001274 }
Mike Stump1eb44332009-09-09 15:08:12 +00001275
Eli Friedman2be46072011-10-14 20:59:01 +00001276 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001277 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001278}
1279
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001280/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1281CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1282 return CharUnits::fromQuantity(BitSize / getCharWidth());
1283}
1284
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001285/// toBits - Convert a size in characters to a size in characters.
1286int64_t ASTContext::toBits(CharUnits CharSize) const {
1287 return CharSize.getQuantity() * getCharWidth();
1288}
1289
Ken Dyckbdc601b2009-12-22 14:23:30 +00001290/// getTypeSizeInChars - Return the size of the specified type, in characters.
1291/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001292CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001293 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001294}
Jay Foad4ba2a172011-01-12 09:06:06 +00001295CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001296 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001297}
1298
Ken Dyck16e20cc2010-01-26 17:25:18 +00001299/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001300/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001301CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001302 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001303}
Jay Foad4ba2a172011-01-12 09:06:06 +00001304CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001305 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001306}
1307
Chris Lattner34ebde42009-01-27 18:08:34 +00001308/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1309/// type for the current target in bits. This can be different than the ABI
1310/// alignment in cases where it is beneficial for performance to overalign
1311/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001312unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001313 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001314
1315 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001316 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001317 T = CT->getElementType().getTypePtr();
1318 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001319 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1320 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001321 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1322
Chris Lattner34ebde42009-01-27 18:08:34 +00001323 return ABIAlign;
1324}
1325
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001326/// DeepCollectObjCIvars -
1327/// This routine first collects all declared, but not synthesized, ivars in
1328/// super class and then collects all ivars, including those synthesized for
1329/// current class. This routine is used for implementation of current class
1330/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001331///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001332void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1333 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001334 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001335 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1336 DeepCollectObjCIvars(SuperClass, false, Ivars);
1337 if (!leafClass) {
1338 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1339 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001340 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001341 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001342 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001343 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001344 Iv= Iv->getNextIvar())
1345 Ivars.push_back(Iv);
1346 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001347}
1348
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001349/// CollectInheritedProtocols - Collect all protocols in current class and
1350/// those inherited by it.
1351void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001352 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001353 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001354 // We can use protocol_iterator here instead of
1355 // all_referenced_protocol_iterator since we are walking all categories.
1356 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1357 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001358 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001359 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001360 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001361 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001362 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001363 CollectInheritedProtocols(*P, Protocols);
1364 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001365 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001366
1367 // Categories of this Interface.
1368 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1369 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1370 CollectInheritedProtocols(CDeclChain, Protocols);
1371 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1372 while (SD) {
1373 CollectInheritedProtocols(SD, Protocols);
1374 SD = SD->getSuperClass();
1375 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001376 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001377 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001378 PE = OC->protocol_end(); P != PE; ++P) {
1379 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001380 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001381 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1382 PE = Proto->protocol_end(); P != PE; ++P)
1383 CollectInheritedProtocols(*P, Protocols);
1384 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001385 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001386 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1387 PE = OP->protocol_end(); P != PE; ++P) {
1388 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001389 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001390 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1391 PE = Proto->protocol_end(); P != PE; ++P)
1392 CollectInheritedProtocols(*P, Protocols);
1393 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001394 }
1395}
1396
Jay Foad4ba2a172011-01-12 09:06:06 +00001397unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001398 unsigned count = 0;
1399 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001400 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1401 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001402 count += CDecl->ivar_size();
1403
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001404 // Count ivar defined in this class's implementation. This
1405 // includes synthesized ivars.
1406 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001407 count += ImplDecl->ivar_size();
1408
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001409 return count;
1410}
1411
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001412bool ASTContext::isSentinelNullExpr(const Expr *E) {
1413 if (!E)
1414 return false;
1415
1416 // nullptr_t is always treated as null.
1417 if (E->getType()->isNullPtrType()) return true;
1418
1419 if (E->getType()->isAnyPointerType() &&
1420 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1421 Expr::NPC_ValueDependentIsNull))
1422 return true;
1423
1424 // Unfortunately, __null has type 'int'.
1425 if (isa<GNUNullExpr>(E)) return true;
1426
1427 return false;
1428}
1429
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001430/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1431ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1432 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1433 I = ObjCImpls.find(D);
1434 if (I != ObjCImpls.end())
1435 return cast<ObjCImplementationDecl>(I->second);
1436 return 0;
1437}
1438/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1439ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1440 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1441 I = ObjCImpls.find(D);
1442 if (I != ObjCImpls.end())
1443 return cast<ObjCCategoryImplDecl>(I->second);
1444 return 0;
1445}
1446
1447/// \brief Set the implementation of ObjCInterfaceDecl.
1448void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1449 ObjCImplementationDecl *ImplD) {
1450 assert(IFaceD && ImplD && "Passed null params");
1451 ObjCImpls[IFaceD] = ImplD;
1452}
1453/// \brief Set the implementation of ObjCCategoryDecl.
1454void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1455 ObjCCategoryImplDecl *ImplD) {
1456 assert(CatD && ImplD && "Passed null params");
1457 ObjCImpls[CatD] = ImplD;
1458}
1459
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001460ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1461 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1462 return ID;
1463 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1464 return CD->getClassInterface();
1465 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1466 return IMD->getClassInterface();
1467
1468 return 0;
1469}
1470
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001471/// \brief Get the copy initialization expression of VarDecl,or NULL if
1472/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001473Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001474 assert(VD && "Passed null params");
1475 assert(VD->hasAttr<BlocksAttr>() &&
1476 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001477 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001478 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001479 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1480}
1481
1482/// \brief Set the copy inialization expression of a block var decl.
1483void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1484 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001485 assert(VD->hasAttr<BlocksAttr>() &&
1486 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001487 BlockVarCopyInits[VD] = Init;
1488}
1489
John McCalla93c9342009-12-07 02:54:59 +00001490TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001491 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001492 if (!DataSize)
1493 DataSize = TypeLoc::getFullDataSizeForType(T);
1494 else
1495 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001496 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001497
John McCalla93c9342009-12-07 02:54:59 +00001498 TypeSourceInfo *TInfo =
1499 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1500 new (TInfo) TypeSourceInfo(T);
1501 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001502}
1503
John McCalla93c9342009-12-07 02:54:59 +00001504TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001505 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001506 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001507 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001508 return DI;
1509}
1510
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001511const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001512ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001513 return getObjCLayout(D, 0);
1514}
1515
1516const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001517ASTContext::getASTObjCImplementationLayout(
1518 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001519 return getObjCLayout(D->getClassInterface(), D);
1520}
1521
Chris Lattnera7674d82007-07-13 22:13:22 +00001522//===----------------------------------------------------------------------===//
1523// Type creation/memoization methods
1524//===----------------------------------------------------------------------===//
1525
Jay Foad4ba2a172011-01-12 09:06:06 +00001526QualType
John McCall3b657512011-01-19 10:06:00 +00001527ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1528 unsigned fastQuals = quals.getFastQualifiers();
1529 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001530
1531 // Check if we've already instantiated this type.
1532 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001533 ExtQuals::Profile(ID, baseType, quals);
1534 void *insertPos = 0;
1535 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1536 assert(eq->getQualifiers() == quals);
1537 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001538 }
1539
John McCall3b657512011-01-19 10:06:00 +00001540 // If the base type is not canonical, make the appropriate canonical type.
1541 QualType canon;
1542 if (!baseType->isCanonicalUnqualified()) {
1543 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001544 canonSplit.Quals.addConsistentQualifiers(quals);
1545 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001546
1547 // Re-find the insert position.
1548 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1549 }
1550
1551 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1552 ExtQualNodes.InsertNode(eq, insertPos);
1553 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001554}
1555
Jay Foad4ba2a172011-01-12 09:06:06 +00001556QualType
1557ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001558 QualType CanT = getCanonicalType(T);
1559 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001560 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001561
John McCall0953e762009-09-24 19:53:00 +00001562 // If we are composing extended qualifiers together, merge together
1563 // into one ExtQuals node.
1564 QualifierCollector Quals;
1565 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001566
John McCall0953e762009-09-24 19:53:00 +00001567 // If this type already has an address space specified, it cannot get
1568 // another one.
1569 assert(!Quals.hasAddressSpace() &&
1570 "Type cannot be in multiple addr spaces!");
1571 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001572
John McCall0953e762009-09-24 19:53:00 +00001573 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001574}
1575
Chris Lattnerb7d25532009-02-18 22:53:11 +00001576QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001577 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001578 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001579 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001580 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001581
John McCall7f040a92010-12-24 02:08:15 +00001582 if (const PointerType *ptr = T->getAs<PointerType>()) {
1583 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001584 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001585 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1586 return getPointerType(ResultType);
1587 }
1588 }
Mike Stump1eb44332009-09-09 15:08:12 +00001589
John McCall0953e762009-09-24 19:53:00 +00001590 // If we are composing extended qualifiers together, merge together
1591 // into one ExtQuals node.
1592 QualifierCollector Quals;
1593 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001594
John McCall0953e762009-09-24 19:53:00 +00001595 // If this type already has an ObjCGC specified, it cannot get
1596 // another one.
1597 assert(!Quals.hasObjCGCAttr() &&
1598 "Type cannot have multiple ObjCGCs!");
1599 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001600
John McCall0953e762009-09-24 19:53:00 +00001601 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001602}
Chris Lattnera7674d82007-07-13 22:13:22 +00001603
John McCalle6a365d2010-12-19 02:44:49 +00001604const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1605 FunctionType::ExtInfo Info) {
1606 if (T->getExtInfo() == Info)
1607 return T;
1608
1609 QualType Result;
1610 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1611 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1612 } else {
1613 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1614 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1615 EPI.ExtInfo = Info;
1616 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1617 FPT->getNumArgs(), EPI);
1618 }
1619
1620 return cast<FunctionType>(Result.getTypePtr());
1621}
1622
Reid Spencer5f016e22007-07-11 17:01:13 +00001623/// getComplexType - Return the uniqued reference to the type for a complex
1624/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001625QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 // Unique pointers, to guarantee there is only one pointer of a particular
1627 // structure.
1628 llvm::FoldingSetNodeID ID;
1629 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Reid Spencer5f016e22007-07-11 17:01:13 +00001631 void *InsertPos = 0;
1632 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1633 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 // If the pointee type isn't canonical, this won't be a canonical type either,
1636 // so fill in the canonical type field.
1637 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001638 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001639 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 // Get the new insert position for the node we care about.
1642 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001643 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001644 }
John McCall6b304a02009-09-24 23:30:46 +00001645 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 Types.push_back(New);
1647 ComplexTypes.InsertNode(New, InsertPos);
1648 return QualType(New, 0);
1649}
1650
Reid Spencer5f016e22007-07-11 17:01:13 +00001651/// getPointerType - Return the uniqued reference to the type for a pointer to
1652/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001653QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001654 // Unique pointers, to guarantee there is only one pointer of a particular
1655 // structure.
1656 llvm::FoldingSetNodeID ID;
1657 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Reid Spencer5f016e22007-07-11 17:01:13 +00001659 void *InsertPos = 0;
1660 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1661 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 // If the pointee type isn't canonical, this won't be a canonical type either,
1664 // so fill in the canonical type field.
1665 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001666 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001667 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 // Get the new insert position for the node we care about.
1670 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001671 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 }
John McCall6b304a02009-09-24 23:30:46 +00001673 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001674 Types.push_back(New);
1675 PointerTypes.InsertNode(New, InsertPos);
1676 return QualType(New, 0);
1677}
1678
Mike Stump1eb44332009-09-09 15:08:12 +00001679/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001680/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001681QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001682 assert(T->isFunctionType() && "block of function types only");
1683 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001684 // structure.
1685 llvm::FoldingSetNodeID ID;
1686 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Steve Naroff5618bd42008-08-27 16:04:49 +00001688 void *InsertPos = 0;
1689 if (BlockPointerType *PT =
1690 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1691 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001692
1693 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001694 // type either so fill in the canonical type field.
1695 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001696 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001697 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Steve Naroff5618bd42008-08-27 16:04:49 +00001699 // Get the new insert position for the node we care about.
1700 BlockPointerType *NewIP =
1701 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001702 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001703 }
John McCall6b304a02009-09-24 23:30:46 +00001704 BlockPointerType *New
1705 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001706 Types.push_back(New);
1707 BlockPointerTypes.InsertNode(New, InsertPos);
1708 return QualType(New, 0);
1709}
1710
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001711/// getLValueReferenceType - Return the uniqued reference to the type for an
1712/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001713QualType
1714ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001715 assert(getCanonicalType(T) != OverloadTy &&
1716 "Unresolved overloaded function type");
1717
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 // Unique pointers, to guarantee there is only one pointer of a particular
1719 // structure.
1720 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001721 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001722
1723 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001724 if (LValueReferenceType *RT =
1725 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001726 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001727
John McCall54e14c42009-10-22 22:37:11 +00001728 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1729
Reid Spencer5f016e22007-07-11 17:01:13 +00001730 // If the referencee type isn't canonical, this won't be a canonical type
1731 // either, so fill in the canonical type field.
1732 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001733 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1734 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1735 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001736
Reid Spencer5f016e22007-07-11 17:01:13 +00001737 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001738 LValueReferenceType *NewIP =
1739 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001740 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001741 }
1742
John McCall6b304a02009-09-24 23:30:46 +00001743 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001744 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1745 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001746 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001747 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001748
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001749 return QualType(New, 0);
1750}
1751
1752/// getRValueReferenceType - Return the uniqued reference to the type for an
1753/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001754QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001755 // Unique pointers, to guarantee there is only one pointer of a particular
1756 // structure.
1757 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001758 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001759
1760 void *InsertPos = 0;
1761 if (RValueReferenceType *RT =
1762 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1763 return QualType(RT, 0);
1764
John McCall54e14c42009-10-22 22:37:11 +00001765 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1766
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001767 // If the referencee type isn't canonical, this won't be a canonical type
1768 // either, so fill in the canonical type field.
1769 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001770 if (InnerRef || !T.isCanonical()) {
1771 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1772 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001773
1774 // Get the new insert position for the node we care about.
1775 RValueReferenceType *NewIP =
1776 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001777 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001778 }
1779
John McCall6b304a02009-09-24 23:30:46 +00001780 RValueReferenceType *New
1781 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001782 Types.push_back(New);
1783 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001784 return QualType(New, 0);
1785}
1786
Sebastian Redlf30208a2009-01-24 21:16:55 +00001787/// getMemberPointerType - Return the uniqued reference to the type for a
1788/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001789QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001790 // Unique pointers, to guarantee there is only one pointer of a particular
1791 // structure.
1792 llvm::FoldingSetNodeID ID;
1793 MemberPointerType::Profile(ID, T, Cls);
1794
1795 void *InsertPos = 0;
1796 if (MemberPointerType *PT =
1797 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1798 return QualType(PT, 0);
1799
1800 // If the pointee or class type isn't canonical, this won't be a canonical
1801 // type either, so fill in the canonical type field.
1802 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001803 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001804 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1805
1806 // Get the new insert position for the node we care about.
1807 MemberPointerType *NewIP =
1808 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001809 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001810 }
John McCall6b304a02009-09-24 23:30:46 +00001811 MemberPointerType *New
1812 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001813 Types.push_back(New);
1814 MemberPointerTypes.InsertNode(New, InsertPos);
1815 return QualType(New, 0);
1816}
1817
Mike Stump1eb44332009-09-09 15:08:12 +00001818/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001819/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001820QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001821 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001822 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001823 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001824 assert((EltTy->isDependentType() ||
1825 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001826 "Constant array of VLAs is illegal!");
1827
Chris Lattner38aeec72009-05-13 04:12:56 +00001828 // Convert the array size into a canonical width matching the pointer size for
1829 // the target.
1830 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001831 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001832 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Reid Spencer5f016e22007-07-11 17:01:13 +00001834 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001835 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001836
Reid Spencer5f016e22007-07-11 17:01:13 +00001837 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001838 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001839 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001840 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001841
John McCall3b657512011-01-19 10:06:00 +00001842 // If the element type isn't canonical or has qualifiers, this won't
1843 // be a canonical type either, so fill in the canonical type field.
1844 QualType Canon;
1845 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1846 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00001847 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001848 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00001849 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001850
Reid Spencer5f016e22007-07-11 17:01:13 +00001851 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001852 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001853 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001854 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001855 }
Mike Stump1eb44332009-09-09 15:08:12 +00001856
John McCall6b304a02009-09-24 23:30:46 +00001857 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001858 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001859 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001860 Types.push_back(New);
1861 return QualType(New, 0);
1862}
1863
John McCallce889032011-01-18 08:40:38 +00001864/// getVariableArrayDecayedType - Turns the given type, which may be
1865/// variably-modified, into the corresponding type with all the known
1866/// sizes replaced with [*].
1867QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1868 // Vastly most common case.
1869 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001870
John McCallce889032011-01-18 08:40:38 +00001871 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001872
John McCallce889032011-01-18 08:40:38 +00001873 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00001874 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00001875 switch (ty->getTypeClass()) {
1876#define TYPE(Class, Base)
1877#define ABSTRACT_TYPE(Class, Base)
1878#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1879#include "clang/AST/TypeNodes.def"
1880 llvm_unreachable("didn't desugar past all non-canonical types?");
1881
1882 // These types should never be variably-modified.
1883 case Type::Builtin:
1884 case Type::Complex:
1885 case Type::Vector:
1886 case Type::ExtVector:
1887 case Type::DependentSizedExtVector:
1888 case Type::ObjCObject:
1889 case Type::ObjCInterface:
1890 case Type::ObjCObjectPointer:
1891 case Type::Record:
1892 case Type::Enum:
1893 case Type::UnresolvedUsing:
1894 case Type::TypeOfExpr:
1895 case Type::TypeOf:
1896 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001897 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001898 case Type::DependentName:
1899 case Type::InjectedClassName:
1900 case Type::TemplateSpecialization:
1901 case Type::DependentTemplateSpecialization:
1902 case Type::TemplateTypeParm:
1903 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001904 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001905 case Type::PackExpansion:
1906 llvm_unreachable("type should never be variably-modified");
1907
1908 // These types can be variably-modified but should never need to
1909 // further decay.
1910 case Type::FunctionNoProto:
1911 case Type::FunctionProto:
1912 case Type::BlockPointer:
1913 case Type::MemberPointer:
1914 return type;
1915
1916 // These types can be variably-modified. All these modifications
1917 // preserve structure except as noted by comments.
1918 // TODO: if we ever care about optimizing VLAs, there are no-op
1919 // optimizations available here.
1920 case Type::Pointer:
1921 result = getPointerType(getVariableArrayDecayedType(
1922 cast<PointerType>(ty)->getPointeeType()));
1923 break;
1924
1925 case Type::LValueReference: {
1926 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1927 result = getLValueReferenceType(
1928 getVariableArrayDecayedType(lv->getPointeeType()),
1929 lv->isSpelledAsLValue());
1930 break;
1931 }
1932
1933 case Type::RValueReference: {
1934 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1935 result = getRValueReferenceType(
1936 getVariableArrayDecayedType(lv->getPointeeType()));
1937 break;
1938 }
1939
Eli Friedmanb001de72011-10-06 23:00:33 +00001940 case Type::Atomic: {
1941 const AtomicType *at = cast<AtomicType>(ty);
1942 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1943 break;
1944 }
1945
John McCallce889032011-01-18 08:40:38 +00001946 case Type::ConstantArray: {
1947 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1948 result = getConstantArrayType(
1949 getVariableArrayDecayedType(cat->getElementType()),
1950 cat->getSize(),
1951 cat->getSizeModifier(),
1952 cat->getIndexTypeCVRQualifiers());
1953 break;
1954 }
1955
1956 case Type::DependentSizedArray: {
1957 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1958 result = getDependentSizedArrayType(
1959 getVariableArrayDecayedType(dat->getElementType()),
1960 dat->getSizeExpr(),
1961 dat->getSizeModifier(),
1962 dat->getIndexTypeCVRQualifiers(),
1963 dat->getBracketsRange());
1964 break;
1965 }
1966
1967 // Turn incomplete types into [*] types.
1968 case Type::IncompleteArray: {
1969 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1970 result = getVariableArrayType(
1971 getVariableArrayDecayedType(iat->getElementType()),
1972 /*size*/ 0,
1973 ArrayType::Normal,
1974 iat->getIndexTypeCVRQualifiers(),
1975 SourceRange());
1976 break;
1977 }
1978
1979 // Turn VLA types into [*] types.
1980 case Type::VariableArray: {
1981 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1982 result = getVariableArrayType(
1983 getVariableArrayDecayedType(vat->getElementType()),
1984 /*size*/ 0,
1985 ArrayType::Star,
1986 vat->getIndexTypeCVRQualifiers(),
1987 vat->getBracketsRange());
1988 break;
1989 }
1990 }
1991
1992 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00001993 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00001994}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001995
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001996/// getVariableArrayType - Returns a non-unique reference to the type for a
1997/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001998QualType ASTContext::getVariableArrayType(QualType EltTy,
1999 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002000 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002001 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002002 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002003 // Since we don't unique expressions, it isn't possible to unique VLA's
2004 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002005 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002006
John McCall3b657512011-01-19 10:06:00 +00002007 // Be sure to pull qualifiers off the element type.
2008 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2009 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002010 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002011 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002012 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002013 }
2014
John McCall6b304a02009-09-24 23:30:46 +00002015 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002016 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002017
2018 VariableArrayTypes.push_back(New);
2019 Types.push_back(New);
2020 return QualType(New, 0);
2021}
2022
Douglas Gregor898574e2008-12-05 23:32:09 +00002023/// getDependentSizedArrayType - Returns a non-unique reference to
2024/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002025/// type.
John McCall3b657512011-01-19 10:06:00 +00002026QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2027 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002028 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002029 unsigned elementTypeQuals,
2030 SourceRange brackets) const {
2031 assert((!numElements || numElements->isTypeDependent() ||
2032 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002033 "Size must be type- or value-dependent!");
2034
John McCall3b657512011-01-19 10:06:00 +00002035 // Dependently-sized array types that do not have a specified number
2036 // of elements will have their sizes deduced from a dependent
2037 // initializer. We do no canonicalization here at all, which is okay
2038 // because they can't be used in most locations.
2039 if (!numElements) {
2040 DependentSizedArrayType *newType
2041 = new (*this, TypeAlignment)
2042 DependentSizedArrayType(*this, elementType, QualType(),
2043 numElements, ASM, elementTypeQuals,
2044 brackets);
2045 Types.push_back(newType);
2046 return QualType(newType, 0);
2047 }
2048
2049 // Otherwise, we actually build a new type every time, but we
2050 // also build a canonical type.
2051
2052 SplitQualType canonElementType = getCanonicalType(elementType).split();
2053
2054 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002055 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002056 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002057 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002058 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002059
John McCall3b657512011-01-19 10:06:00 +00002060 // Look for an existing type with these properties.
2061 DependentSizedArrayType *canonTy =
2062 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002063
John McCall3b657512011-01-19 10:06:00 +00002064 // If we don't have one, build one.
2065 if (!canonTy) {
2066 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002067 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002068 QualType(), numElements, ASM, elementTypeQuals,
2069 brackets);
2070 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2071 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002072 }
2073
John McCall3b657512011-01-19 10:06:00 +00002074 // Apply qualifiers from the element type to the array.
2075 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002076 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002077
John McCall3b657512011-01-19 10:06:00 +00002078 // If we didn't need extra canonicalization for the element type,
2079 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002080 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002081 return canon;
2082
2083 // Otherwise, we need to build a type which follows the spelling
2084 // of the element type.
2085 DependentSizedArrayType *sugaredType
2086 = new (*this, TypeAlignment)
2087 DependentSizedArrayType(*this, elementType, canon, numElements,
2088 ASM, elementTypeQuals, brackets);
2089 Types.push_back(sugaredType);
2090 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002091}
2092
John McCall3b657512011-01-19 10:06:00 +00002093QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002094 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002095 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002096 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002097 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002098
John McCall3b657512011-01-19 10:06:00 +00002099 void *insertPos = 0;
2100 if (IncompleteArrayType *iat =
2101 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2102 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002103
2104 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002105 // either, so fill in the canonical type field. We also have to pull
2106 // qualifiers off the element type.
2107 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002108
John McCall3b657512011-01-19 10:06:00 +00002109 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2110 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002111 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002112 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002113 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002114
2115 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002116 IncompleteArrayType *existing =
2117 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2118 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002119 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002120
John McCall3b657512011-01-19 10:06:00 +00002121 IncompleteArrayType *newType = new (*this, TypeAlignment)
2122 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002123
John McCall3b657512011-01-19 10:06:00 +00002124 IncompleteArrayTypes.InsertNode(newType, insertPos);
2125 Types.push_back(newType);
2126 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002127}
2128
Steve Naroff73322922007-07-18 18:00:27 +00002129/// getVectorType - Return the unique reference to a vector type of
2130/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002131QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002132 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002133 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Reid Spencer5f016e22007-07-11 17:01:13 +00002135 // Check if we've already instantiated a vector of this type.
2136 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002137 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002138
Reid Spencer5f016e22007-07-11 17:01:13 +00002139 void *InsertPos = 0;
2140 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2141 return QualType(VTP, 0);
2142
2143 // If the element type isn't canonical, this won't be a canonical type either,
2144 // so fill in the canonical type field.
2145 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002146 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002147 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Reid Spencer5f016e22007-07-11 17:01:13 +00002149 // Get the new insert position for the node we care about.
2150 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002151 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002152 }
John McCall6b304a02009-09-24 23:30:46 +00002153 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002154 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002155 VectorTypes.InsertNode(New, InsertPos);
2156 Types.push_back(New);
2157 return QualType(New, 0);
2158}
2159
Nate Begeman213541a2008-04-18 23:10:10 +00002160/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002161/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002162QualType
2163ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002164 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Steve Naroff73322922007-07-18 18:00:27 +00002166 // Check if we've already instantiated a vector of this type.
2167 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002168 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002169 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002170 void *InsertPos = 0;
2171 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2172 return QualType(VTP, 0);
2173
2174 // If the element type isn't canonical, this won't be a canonical type either,
2175 // so fill in the canonical type field.
2176 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002177 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002178 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002179
Steve Naroff73322922007-07-18 18:00:27 +00002180 // Get the new insert position for the node we care about.
2181 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002182 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002183 }
John McCall6b304a02009-09-24 23:30:46 +00002184 ExtVectorType *New = new (*this, TypeAlignment)
2185 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002186 VectorTypes.InsertNode(New, InsertPos);
2187 Types.push_back(New);
2188 return QualType(New, 0);
2189}
2190
Jay Foad4ba2a172011-01-12 09:06:06 +00002191QualType
2192ASTContext::getDependentSizedExtVectorType(QualType vecType,
2193 Expr *SizeExpr,
2194 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002195 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002196 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002197 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002198
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002199 void *InsertPos = 0;
2200 DependentSizedExtVectorType *Canon
2201 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2202 DependentSizedExtVectorType *New;
2203 if (Canon) {
2204 // We already have a canonical version of this array type; use it as
2205 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002206 New = new (*this, TypeAlignment)
2207 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2208 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002209 } else {
2210 QualType CanonVecTy = getCanonicalType(vecType);
2211 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002212 New = new (*this, TypeAlignment)
2213 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2214 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002215
2216 DependentSizedExtVectorType *CanonCheck
2217 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2218 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2219 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002220 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2221 } else {
2222 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2223 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002224 New = new (*this, TypeAlignment)
2225 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002226 }
2227 }
Mike Stump1eb44332009-09-09 15:08:12 +00002228
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002229 Types.push_back(New);
2230 return QualType(New, 0);
2231}
2232
Douglas Gregor72564e72009-02-26 23:50:07 +00002233/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002234///
Jay Foad4ba2a172011-01-12 09:06:06 +00002235QualType
2236ASTContext::getFunctionNoProtoType(QualType ResultTy,
2237 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002238 const CallingConv DefaultCC = Info.getCC();
2239 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2240 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002241 // Unique functions, to guarantee there is only one function of a particular
2242 // structure.
2243 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002244 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Reid Spencer5f016e22007-07-11 17:01:13 +00002246 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002247 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002248 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002249 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002250
Reid Spencer5f016e22007-07-11 17:01:13 +00002251 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002252 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002253 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002254 Canonical =
2255 getFunctionNoProtoType(getCanonicalType(ResultTy),
2256 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002257
Reid Spencer5f016e22007-07-11 17:01:13 +00002258 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002259 FunctionNoProtoType *NewIP =
2260 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002261 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002262 }
Mike Stump1eb44332009-09-09 15:08:12 +00002263
Roman Divackycfe9af22011-03-01 17:40:53 +00002264 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002265 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002266 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002267 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002268 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002269 return QualType(New, 0);
2270}
2271
2272/// getFunctionType - Return a normal function type with a typed argument
2273/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002274QualType
2275ASTContext::getFunctionType(QualType ResultTy,
2276 const QualType *ArgArray, unsigned NumArgs,
2277 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002278 // Unique functions, to guarantee there is only one function of a particular
2279 // structure.
2280 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002281 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002282
2283 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002284 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002285 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002286 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002287
2288 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002289 bool isCanonical =
2290 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2291 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002292 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002293 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002294 isCanonical = false;
2295
Roman Divackycfe9af22011-03-01 17:40:53 +00002296 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2297 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2298 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002299
Reid Spencer5f016e22007-07-11 17:01:13 +00002300 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002301 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002302 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002303 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002304 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002305 CanonicalArgs.reserve(NumArgs);
2306 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002307 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002308
John McCalle23cf432010-12-14 08:05:40 +00002309 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002310 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002311 CanonicalEPI.ExceptionSpecType = EST_None;
2312 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002313 CanonicalEPI.ExtInfo
2314 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2315
Chris Lattnerf52ab252008-04-06 22:59:24 +00002316 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002317 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002318 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002319
Reid Spencer5f016e22007-07-11 17:01:13 +00002320 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002321 FunctionProtoType *NewIP =
2322 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002323 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002324 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002325
John McCallf85e1932011-06-15 23:02:42 +00002326 // FunctionProtoType objects are allocated with extra bytes after
2327 // them for three variable size arrays at the end:
2328 // - parameter types
2329 // - exception types
2330 // - consumed-arguments flags
2331 // Instead of the exception types, there could be a noexcept
2332 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002333 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002334 NumArgs * sizeof(QualType);
2335 if (EPI.ExceptionSpecType == EST_Dynamic)
2336 Size += EPI.NumExceptions * sizeof(QualType);
2337 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002338 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002339 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002340 Size += 2 * sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002341 }
John McCallf85e1932011-06-15 23:02:42 +00002342 if (EPI.ConsumedArguments)
2343 Size += NumArgs * sizeof(bool);
2344
John McCalle23cf432010-12-14 08:05:40 +00002345 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002346 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2347 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002348 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002349 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002350 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002351 return QualType(FTP, 0);
2352}
2353
John McCall3cb0ebd2010-03-10 03:28:59 +00002354#ifndef NDEBUG
2355static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2356 if (!isa<CXXRecordDecl>(D)) return false;
2357 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2358 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2359 return true;
2360 if (RD->getDescribedClassTemplate() &&
2361 !isa<ClassTemplateSpecializationDecl>(RD))
2362 return true;
2363 return false;
2364}
2365#endif
2366
2367/// getInjectedClassNameType - Return the unique reference to the
2368/// injected class name type for the specified templated declaration.
2369QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002370 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002371 assert(NeedsInjectedClassNameType(Decl));
2372 if (Decl->TypeForDecl) {
2373 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002374 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002375 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2376 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2377 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2378 } else {
John McCallf4c73712011-01-19 06:33:43 +00002379 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002380 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002381 Decl->TypeForDecl = newType;
2382 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002383 }
2384 return QualType(Decl->TypeForDecl, 0);
2385}
2386
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002387/// getTypeDeclType - Return the unique reference to the type for the
2388/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002389QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002390 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002391 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002392
Richard Smith162e1c12011-04-15 14:24:37 +00002393 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002394 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002395
John McCallbecb8d52010-03-10 06:48:02 +00002396 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2397 "Template type parameter types are always available.");
2398
John McCall19c85762010-02-16 03:57:14 +00002399 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002400 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002401 "struct/union has previous declaration");
2402 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002403 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002404 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002405 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002406 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002407 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002408 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002409 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002410 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2411 Decl->TypeForDecl = newType;
2412 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002413 } else
John McCallbecb8d52010-03-10 06:48:02 +00002414 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002415
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002416 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002417}
2418
Reid Spencer5f016e22007-07-11 17:01:13 +00002419/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002420/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002421QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002422ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2423 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002424 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002425
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002426 if (Canonical.isNull())
2427 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002428 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002429 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002430 Decl->TypeForDecl = newType;
2431 Types.push_back(newType);
2432 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002433}
2434
Jay Foad4ba2a172011-01-12 09:06:06 +00002435QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002436 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2437
Douglas Gregoref96ee02012-01-14 16:38:05 +00002438 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002439 if (PrevDecl->TypeForDecl)
2440 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2441
John McCallf4c73712011-01-19 06:33:43 +00002442 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2443 Decl->TypeForDecl = newType;
2444 Types.push_back(newType);
2445 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002446}
2447
Jay Foad4ba2a172011-01-12 09:06:06 +00002448QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002449 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2450
Douglas Gregoref96ee02012-01-14 16:38:05 +00002451 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002452 if (PrevDecl->TypeForDecl)
2453 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2454
John McCallf4c73712011-01-19 06:33:43 +00002455 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2456 Decl->TypeForDecl = newType;
2457 Types.push_back(newType);
2458 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002459}
2460
John McCall9d156a72011-01-06 01:58:22 +00002461QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2462 QualType modifiedType,
2463 QualType equivalentType) {
2464 llvm::FoldingSetNodeID id;
2465 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2466
2467 void *insertPos = 0;
2468 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2469 if (type) return QualType(type, 0);
2470
2471 QualType canon = getCanonicalType(equivalentType);
2472 type = new (*this, TypeAlignment)
2473 AttributedType(canon, attrKind, modifiedType, equivalentType);
2474
2475 Types.push_back(type);
2476 AttributedTypes.InsertNode(type, insertPos);
2477
2478 return QualType(type, 0);
2479}
2480
2481
John McCall49a832b2009-10-18 09:09:24 +00002482/// \brief Retrieve a substitution-result type.
2483QualType
2484ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002485 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002486 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002487 && "replacement types must always be canonical");
2488
2489 llvm::FoldingSetNodeID ID;
2490 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2491 void *InsertPos = 0;
2492 SubstTemplateTypeParmType *SubstParm
2493 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2494
2495 if (!SubstParm) {
2496 SubstParm = new (*this, TypeAlignment)
2497 SubstTemplateTypeParmType(Parm, Replacement);
2498 Types.push_back(SubstParm);
2499 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2500 }
2501
2502 return QualType(SubstParm, 0);
2503}
2504
Douglas Gregorc3069d62011-01-14 02:55:32 +00002505/// \brief Retrieve a
2506QualType ASTContext::getSubstTemplateTypeParmPackType(
2507 const TemplateTypeParmType *Parm,
2508 const TemplateArgument &ArgPack) {
2509#ifndef NDEBUG
2510 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2511 PEnd = ArgPack.pack_end();
2512 P != PEnd; ++P) {
2513 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2514 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2515 }
2516#endif
2517
2518 llvm::FoldingSetNodeID ID;
2519 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2520 void *InsertPos = 0;
2521 if (SubstTemplateTypeParmPackType *SubstParm
2522 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2523 return QualType(SubstParm, 0);
2524
2525 QualType Canon;
2526 if (!Parm->isCanonicalUnqualified()) {
2527 Canon = getCanonicalType(QualType(Parm, 0));
2528 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2529 ArgPack);
2530 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2531 }
2532
2533 SubstTemplateTypeParmPackType *SubstParm
2534 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2535 ArgPack);
2536 Types.push_back(SubstParm);
2537 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2538 return QualType(SubstParm, 0);
2539}
2540
Douglas Gregorfab9d672009-02-05 23:33:38 +00002541/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002542/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002543/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002544QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002545 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002546 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002547 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002548 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002549 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002550 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002551 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2552
2553 if (TypeParm)
2554 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002555
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002556 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002557 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002558 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002559
2560 TemplateTypeParmType *TypeCheck
2561 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2562 assert(!TypeCheck && "Template type parameter canonical type broken");
2563 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002564 } else
John McCall6b304a02009-09-24 23:30:46 +00002565 TypeParm = new (*this, TypeAlignment)
2566 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002567
2568 Types.push_back(TypeParm);
2569 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2570
2571 return QualType(TypeParm, 0);
2572}
2573
John McCall3cb0ebd2010-03-10 03:28:59 +00002574TypeSourceInfo *
2575ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2576 SourceLocation NameLoc,
2577 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002578 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002579 assert(!Name.getAsDependentTemplateName() &&
2580 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002581 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002582
2583 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2584 TemplateSpecializationTypeLoc TL
2585 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002586 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002587 TL.setTemplateNameLoc(NameLoc);
2588 TL.setLAngleLoc(Args.getLAngleLoc());
2589 TL.setRAngleLoc(Args.getRAngleLoc());
2590 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2591 TL.setArgLocInfo(i, Args[i].getLocInfo());
2592 return DI;
2593}
2594
Mike Stump1eb44332009-09-09 15:08:12 +00002595QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002596ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002597 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002598 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002599 assert(!Template.getAsDependentTemplateName() &&
2600 "No dependent template names here!");
2601
John McCalld5532b62009-11-23 01:53:49 +00002602 unsigned NumArgs = Args.size();
2603
Chris Lattner5f9e2722011-07-23 10:55:15 +00002604 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002605 ArgVec.reserve(NumArgs);
2606 for (unsigned i = 0; i != NumArgs; ++i)
2607 ArgVec.push_back(Args[i].getArgument());
2608
John McCall31f17ec2010-04-27 00:57:59 +00002609 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002610 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002611}
2612
Douglas Gregorb70126a2012-02-03 17:16:23 +00002613#ifndef NDEBUG
2614static bool hasAnyPackExpansions(const TemplateArgument *Args,
2615 unsigned NumArgs) {
2616 for (unsigned I = 0; I != NumArgs; ++I)
2617 if (Args[I].isPackExpansion())
2618 return true;
2619
2620 return true;
2621}
2622#endif
2623
John McCall833ca992009-10-29 08:12:44 +00002624QualType
2625ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002626 const TemplateArgument *Args,
2627 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002628 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002629 assert(!Template.getAsDependentTemplateName() &&
2630 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002631 // Look through qualified template names.
2632 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2633 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002634
Douglas Gregorb70126a2012-02-03 17:16:23 +00002635 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00002636 Template.getAsTemplateDecl() &&
2637 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00002638 QualType CanonType;
2639 if (!Underlying.isNull())
2640 CanonType = getCanonicalType(Underlying);
2641 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00002642 // We can get here with an alias template when the specialization contains
2643 // a pack expansion that does not match up with a parameter pack.
2644 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2645 "Caller must compute aliased type");
2646 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00002647 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2648 NumArgs);
2649 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002650
Douglas Gregor1275ae02009-07-28 23:00:59 +00002651 // Allocate the (non-canonical) template specialization type, but don't
2652 // try to unique it: these types typically have location information that
2653 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002654 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2655 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00002656 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002657 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002658 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00002659 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2660 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002661
Douglas Gregor55f6b142009-02-09 18:46:07 +00002662 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002663 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002664}
2665
Mike Stump1eb44332009-09-09 15:08:12 +00002666QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002667ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2668 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002669 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002670 assert(!Template.getAsDependentTemplateName() &&
2671 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002672
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
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002677 // Build the canonical template specialization type.
2678 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002679 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002680 CanonArgs.reserve(NumArgs);
2681 for (unsigned I = 0; I != NumArgs; ++I)
2682 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2683
2684 // Determine whether this canonical template specialization type already
2685 // exists.
2686 llvm::FoldingSetNodeID ID;
2687 TemplateSpecializationType::Profile(ID, CanonTemplate,
2688 CanonArgs.data(), NumArgs, *this);
2689
2690 void *InsertPos = 0;
2691 TemplateSpecializationType *Spec
2692 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2693
2694 if (!Spec) {
2695 // Allocate a new canonical template specialization type.
2696 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2697 sizeof(TemplateArgument) * NumArgs),
2698 TypeAlignment);
2699 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2700 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002701 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002702 Types.push_back(Spec);
2703 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2704 }
2705
2706 assert(Spec->isDependentType() &&
2707 "Non-dependent template-id type must have a canonical type");
2708 return QualType(Spec, 0);
2709}
2710
2711QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002712ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2713 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002714 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002715 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002716 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002717
2718 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002719 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002720 if (T)
2721 return QualType(T, 0);
2722
Douglas Gregor789b1f62010-02-04 18:10:26 +00002723 QualType Canon = NamedType;
2724 if (!Canon.isCanonical()) {
2725 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002726 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2727 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002728 (void)CheckT;
2729 }
2730
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002731 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002732 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002733 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002734 return QualType(T, 0);
2735}
2736
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002737QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002738ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002739 llvm::FoldingSetNodeID ID;
2740 ParenType::Profile(ID, InnerType);
2741
2742 void *InsertPos = 0;
2743 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2744 if (T)
2745 return QualType(T, 0);
2746
2747 QualType Canon = InnerType;
2748 if (!Canon.isCanonical()) {
2749 Canon = getCanonicalType(InnerType);
2750 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2751 assert(!CheckT && "Paren canonical type broken");
2752 (void)CheckT;
2753 }
2754
2755 T = new (*this) ParenType(InnerType, Canon);
2756 Types.push_back(T);
2757 ParenTypes.InsertNode(T, InsertPos);
2758 return QualType(T, 0);
2759}
2760
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002761QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2762 NestedNameSpecifier *NNS,
2763 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002764 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002765 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2766
2767 if (Canon.isNull()) {
2768 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002769 ElaboratedTypeKeyword CanonKeyword = Keyword;
2770 if (Keyword == ETK_None)
2771 CanonKeyword = ETK_Typename;
2772
2773 if (CanonNNS != NNS || CanonKeyword != Keyword)
2774 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002775 }
2776
2777 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002778 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002779
2780 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002781 DependentNameType *T
2782 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002783 if (T)
2784 return QualType(T, 0);
2785
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002786 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002787 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002788 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002789 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002790}
2791
Mike Stump1eb44332009-09-09 15:08:12 +00002792QualType
John McCall33500952010-06-11 00:33:02 +00002793ASTContext::getDependentTemplateSpecializationType(
2794 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002795 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002796 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002797 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002798 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002799 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002800 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2801 ArgCopy.push_back(Args[I].getArgument());
2802 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2803 ArgCopy.size(),
2804 ArgCopy.data());
2805}
2806
2807QualType
2808ASTContext::getDependentTemplateSpecializationType(
2809 ElaboratedTypeKeyword Keyword,
2810 NestedNameSpecifier *NNS,
2811 const IdentifierInfo *Name,
2812 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002813 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002814 assert((!NNS || NNS->isDependent()) &&
2815 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002816
Douglas Gregor789b1f62010-02-04 18:10:26 +00002817 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002818 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2819 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002820
2821 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002822 DependentTemplateSpecializationType *T
2823 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002824 if (T)
2825 return QualType(T, 0);
2826
John McCall33500952010-06-11 00:33:02 +00002827 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002828
John McCall33500952010-06-11 00:33:02 +00002829 ElaboratedTypeKeyword CanonKeyword = Keyword;
2830 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2831
2832 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002833 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002834 for (unsigned I = 0; I != NumArgs; ++I) {
2835 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2836 if (!CanonArgs[I].structurallyEquals(Args[I]))
2837 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002838 }
2839
John McCall33500952010-06-11 00:33:02 +00002840 QualType Canon;
2841 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2842 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2843 Name, NumArgs,
2844 CanonArgs.data());
2845
2846 // Find the insert position again.
2847 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2848 }
2849
2850 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2851 sizeof(TemplateArgument) * NumArgs),
2852 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002853 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002854 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002855 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002856 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002857 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002858}
2859
Douglas Gregorcded4f62011-01-14 17:04:44 +00002860QualType ASTContext::getPackExpansionType(QualType Pattern,
2861 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002862 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002863 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002864
2865 assert(Pattern->containsUnexpandedParameterPack() &&
2866 "Pack expansions must expand one or more parameter packs");
2867 void *InsertPos = 0;
2868 PackExpansionType *T
2869 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2870 if (T)
2871 return QualType(T, 0);
2872
2873 QualType Canon;
2874 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002875 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002876
2877 // Find the insert position again.
2878 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2879 }
2880
Douglas Gregorcded4f62011-01-14 17:04:44 +00002881 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002882 Types.push_back(T);
2883 PackExpansionTypes.InsertNode(T, InsertPos);
2884 return QualType(T, 0);
2885}
2886
Chris Lattner88cb27a2008-04-07 04:56:42 +00002887/// CmpProtocolNames - Comparison predicate for sorting protocols
2888/// alphabetically.
2889static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2890 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002891 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002892}
2893
John McCallc12c5bb2010-05-15 11:32:37 +00002894static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002895 unsigned NumProtocols) {
2896 if (NumProtocols == 0) return true;
2897
Douglas Gregor61cc2962012-01-02 02:00:30 +00002898 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2899 return false;
2900
John McCall54e14c42009-10-22 22:37:11 +00002901 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00002902 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2903 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00002904 return false;
2905 return true;
2906}
2907
2908static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002909 unsigned &NumProtocols) {
2910 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002911
Chris Lattner88cb27a2008-04-07 04:56:42 +00002912 // Sort protocols, keyed by name.
2913 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2914
Douglas Gregor61cc2962012-01-02 02:00:30 +00002915 // Canonicalize.
2916 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2917 Protocols[I] = Protocols[I]->getCanonicalDecl();
2918
Chris Lattner88cb27a2008-04-07 04:56:42 +00002919 // Remove duplicates.
2920 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2921 NumProtocols = ProtocolsEnd-Protocols;
2922}
2923
John McCallc12c5bb2010-05-15 11:32:37 +00002924QualType ASTContext::getObjCObjectType(QualType BaseType,
2925 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002926 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002927 // If the base type is an interface and there aren't any protocols
2928 // to add, then the interface type will do just fine.
2929 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2930 return BaseType;
2931
2932 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002933 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002934 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002935 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002936 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2937 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002938
John McCallc12c5bb2010-05-15 11:32:37 +00002939 // Build the canonical type, which has the canonical base type and
2940 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002941 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002942 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2943 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2944 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002945 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002946 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002947 unsigned UniqueCount = NumProtocols;
2948
John McCall54e14c42009-10-22 22:37:11 +00002949 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002950 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2951 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002952 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002953 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2954 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002955 }
2956
2957 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002958 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2959 }
2960
2961 unsigned Size = sizeof(ObjCObjectTypeImpl);
2962 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2963 void *Mem = Allocate(Size, TypeAlignment);
2964 ObjCObjectTypeImpl *T =
2965 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2966
2967 Types.push_back(T);
2968 ObjCObjectTypes.InsertNode(T, InsertPos);
2969 return QualType(T, 0);
2970}
2971
2972/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2973/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002974QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002975 llvm::FoldingSetNodeID ID;
2976 ObjCObjectPointerType::Profile(ID, ObjectT);
2977
2978 void *InsertPos = 0;
2979 if (ObjCObjectPointerType *QT =
2980 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2981 return QualType(QT, 0);
2982
2983 // Find the canonical object type.
2984 QualType Canonical;
2985 if (!ObjectT.isCanonical()) {
2986 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2987
2988 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002989 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2990 }
2991
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002992 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002993 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2994 ObjCObjectPointerType *QType =
2995 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002996
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002997 Types.push_back(QType);
2998 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002999 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003000}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003001
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003002/// getObjCInterfaceType - Return the unique reference to the type for the
3003/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003004QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3005 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003006 if (Decl->TypeForDecl)
3007 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003008
Douglas Gregor0af55012011-12-16 03:12:41 +00003009 if (PrevDecl) {
3010 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3011 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3012 return QualType(PrevDecl->TypeForDecl, 0);
3013 }
3014
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003015 // Prefer the definition, if there is one.
3016 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3017 Decl = Def;
3018
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003019 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3020 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3021 Decl->TypeForDecl = T;
3022 Types.push_back(T);
3023 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003024}
3025
Douglas Gregor72564e72009-02-26 23:50:07 +00003026/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3027/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003028/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003029/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003030/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003031QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003032 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003033 if (tofExpr->isTypeDependent()) {
3034 llvm::FoldingSetNodeID ID;
3035 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003036
Douglas Gregorb1975722009-07-30 23:18:24 +00003037 void *InsertPos = 0;
3038 DependentTypeOfExprType *Canon
3039 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3040 if (Canon) {
3041 // We already have a "canonical" version of an identical, dependent
3042 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003043 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003044 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003045 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003046 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003047 Canon
3048 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003049 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3050 toe = Canon;
3051 }
3052 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003053 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003054 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003055 }
Steve Naroff9752f252007-08-01 18:02:17 +00003056 Types.push_back(toe);
3057 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003058}
3059
Steve Naroff9752f252007-08-01 18:02:17 +00003060/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3061/// TypeOfType AST's. The only motivation to unique these nodes would be
3062/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003063/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003064/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003065QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003066 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003067 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003068 Types.push_back(tot);
3069 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003070}
3071
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003072
Anders Carlsson395b4752009-06-24 19:06:50 +00003073/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3074/// DecltypeType AST's. The only motivation to unique these nodes would be
3075/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003076/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003077/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003078QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003079 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003080
3081 // C++0x [temp.type]p2:
3082 // If an expression e involves a template parameter, decltype(e) denotes a
3083 // unique dependent type. Two such decltype-specifiers refer to the same
3084 // type only if their expressions are equivalent (14.5.6.1).
3085 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003086 llvm::FoldingSetNodeID ID;
3087 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003088
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003089 void *InsertPos = 0;
3090 DependentDecltypeType *Canon
3091 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3092 if (Canon) {
3093 // We already have a "canonical" version of an equivalent, dependent
3094 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003095 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003096 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003097 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003098 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003099 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003100 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3101 dt = Canon;
3102 }
3103 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003104 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3105 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003106 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003107 Types.push_back(dt);
3108 return QualType(dt, 0);
3109}
3110
Sean Huntca63c202011-05-24 22:41:36 +00003111/// getUnaryTransformationType - We don't unique these, since the memory
3112/// savings are minimal and these are rare.
3113QualType ASTContext::getUnaryTransformType(QualType BaseType,
3114 QualType UnderlyingType,
3115 UnaryTransformType::UTTKind Kind)
3116 const {
3117 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003118 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3119 Kind,
3120 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003121 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003122 Types.push_back(Ty);
3123 return QualType(Ty, 0);
3124}
3125
Richard Smith483b9f32011-02-21 20:05:19 +00003126/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00003127QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00003128 void *InsertPos = 0;
3129 if (!DeducedType.isNull()) {
3130 // Look in the folding set for an existing type.
3131 llvm::FoldingSetNodeID ID;
3132 AutoType::Profile(ID, DeducedType);
3133 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3134 return QualType(AT, 0);
3135 }
3136
3137 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3138 Types.push_back(AT);
3139 if (InsertPos)
3140 AutoTypes.InsertNode(AT, InsertPos);
3141 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003142}
3143
Eli Friedmanb001de72011-10-06 23:00:33 +00003144/// getAtomicType - Return the uniqued reference to the atomic type for
3145/// the given value type.
3146QualType ASTContext::getAtomicType(QualType T) const {
3147 // Unique pointers, to guarantee there is only one pointer of a particular
3148 // structure.
3149 llvm::FoldingSetNodeID ID;
3150 AtomicType::Profile(ID, T);
3151
3152 void *InsertPos = 0;
3153 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3154 return QualType(AT, 0);
3155
3156 // If the atomic value type isn't canonical, this won't be a canonical type
3157 // either, so fill in the canonical type field.
3158 QualType Canonical;
3159 if (!T.isCanonical()) {
3160 Canonical = getAtomicType(getCanonicalType(T));
3161
3162 // Get the new insert position for the node we care about.
3163 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3164 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3165 }
3166 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3167 Types.push_back(New);
3168 AtomicTypes.InsertNode(New, InsertPos);
3169 return QualType(New, 0);
3170}
3171
Richard Smithad762fc2011-04-14 22:09:26 +00003172/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3173QualType ASTContext::getAutoDeductType() const {
3174 if (AutoDeductTy.isNull())
3175 AutoDeductTy = getAutoType(QualType());
3176 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3177 return AutoDeductTy;
3178}
3179
3180/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3181QualType ASTContext::getAutoRRefDeductType() const {
3182 if (AutoRRefDeductTy.isNull())
3183 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3184 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3185 return AutoRRefDeductTy;
3186}
3187
Reid Spencer5f016e22007-07-11 17:01:13 +00003188/// getTagDeclType - Return the unique reference to the type for the
3189/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003190QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003191 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003192 // FIXME: What is the design on getTagDeclType when it requires casting
3193 // away const? mutable?
3194 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003195}
3196
Mike Stump1eb44332009-09-09 15:08:12 +00003197/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3198/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3199/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003200CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003201 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003202}
3203
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003204/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3205CanQualType ASTContext::getIntMaxType() const {
3206 return getFromTargetType(Target->getIntMaxType());
3207}
3208
3209/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3210CanQualType ASTContext::getUIntMaxType() const {
3211 return getFromTargetType(Target->getUIntMaxType());
3212}
3213
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003214/// getSignedWCharType - Return the type of "signed wchar_t".
3215/// Used when in C++, as a GCC extension.
3216QualType ASTContext::getSignedWCharType() const {
3217 // FIXME: derive from "Target" ?
3218 return WCharTy;
3219}
3220
3221/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3222/// Used when in C++, as a GCC extension.
3223QualType ASTContext::getUnsignedWCharType() const {
3224 // FIXME: derive from "Target" ?
3225 return UnsignedIntTy;
3226}
3227
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003228/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003229/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3230QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003231 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003232}
3233
Chris Lattnere6327742008-04-02 05:18:44 +00003234//===----------------------------------------------------------------------===//
3235// Type Operators
3236//===----------------------------------------------------------------------===//
3237
Jay Foad4ba2a172011-01-12 09:06:06 +00003238CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003239 // Push qualifiers into arrays, and then discard any remaining
3240 // qualifiers.
3241 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003242 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003243 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003244 QualType Result;
3245 if (isa<ArrayType>(Ty)) {
3246 Result = getArrayDecayedType(QualType(Ty,0));
3247 } else if (isa<FunctionType>(Ty)) {
3248 Result = getPointerType(QualType(Ty, 0));
3249 } else {
3250 Result = QualType(Ty, 0);
3251 }
3252
3253 return CanQualType::CreateUnsafe(Result);
3254}
3255
John McCall62c28c82011-01-18 07:41:22 +00003256QualType ASTContext::getUnqualifiedArrayType(QualType type,
3257 Qualifiers &quals) {
3258 SplitQualType splitType = type.getSplitUnqualifiedType();
3259
3260 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3261 // the unqualified desugared type and then drops it on the floor.
3262 // We then have to strip that sugar back off with
3263 // getUnqualifiedDesugaredType(), which is silly.
3264 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003265 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003266
3267 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003268 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003269 quals = splitType.Quals;
3270 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003271 }
3272
John McCall62c28c82011-01-18 07:41:22 +00003273 // Otherwise, recurse on the array's element type.
3274 QualType elementType = AT->getElementType();
3275 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3276
3277 // If that didn't change the element type, AT has no qualifiers, so we
3278 // can just use the results in splitType.
3279 if (elementType == unqualElementType) {
3280 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003281 quals = splitType.Quals;
3282 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003283 }
3284
3285 // Otherwise, add in the qualifiers from the outermost type, then
3286 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003287 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003288
Douglas Gregor9dadd942010-05-17 18:45:21 +00003289 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003290 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003291 CAT->getSizeModifier(), 0);
3292 }
3293
Douglas Gregor9dadd942010-05-17 18:45:21 +00003294 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003295 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003296 }
3297
Douglas Gregor9dadd942010-05-17 18:45:21 +00003298 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003299 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003300 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003301 VAT->getSizeModifier(),
3302 VAT->getIndexTypeCVRQualifiers(),
3303 VAT->getBracketsRange());
3304 }
3305
3306 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003307 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003308 DSAT->getSizeModifier(), 0,
3309 SourceRange());
3310}
3311
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003312/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3313/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3314/// they point to and return true. If T1 and T2 aren't pointer types
3315/// or pointer-to-member types, or if they are not similar at this
3316/// level, returns false and leaves T1 and T2 unchanged. Top-level
3317/// qualifiers on T1 and T2 are ignored. This function will typically
3318/// be called in a loop that successively "unwraps" pointer and
3319/// pointer-to-member types to compare them at each level.
3320bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3321 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3322 *T2PtrType = T2->getAs<PointerType>();
3323 if (T1PtrType && T2PtrType) {
3324 T1 = T1PtrType->getPointeeType();
3325 T2 = T2PtrType->getPointeeType();
3326 return true;
3327 }
3328
3329 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3330 *T2MPType = T2->getAs<MemberPointerType>();
3331 if (T1MPType && T2MPType &&
3332 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3333 QualType(T2MPType->getClass(), 0))) {
3334 T1 = T1MPType->getPointeeType();
3335 T2 = T2MPType->getPointeeType();
3336 return true;
3337 }
3338
David Blaikie4e4d0842012-03-11 07:00:24 +00003339 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003340 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3341 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3342 if (T1OPType && T2OPType) {
3343 T1 = T1OPType->getPointeeType();
3344 T2 = T2OPType->getPointeeType();
3345 return true;
3346 }
3347 }
3348
3349 // FIXME: Block pointers, too?
3350
3351 return false;
3352}
3353
Jay Foad4ba2a172011-01-12 09:06:06 +00003354DeclarationNameInfo
3355ASTContext::getNameForTemplate(TemplateName Name,
3356 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003357 switch (Name.getKind()) {
3358 case TemplateName::QualifiedTemplate:
3359 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003360 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003361 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3362 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003363
John McCall14606042011-06-30 08:33:18 +00003364 case TemplateName::OverloadedTemplate: {
3365 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3366 // DNInfo work in progress: CHECKME: what about DNLoc?
3367 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3368 }
3369
3370 case TemplateName::DependentTemplate: {
3371 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003372 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003373 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003374 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3375 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003376 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003377 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3378 // DNInfo work in progress: FIXME: source locations?
3379 DeclarationNameLoc DNLoc;
3380 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3381 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3382 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003383 }
3384 }
3385
John McCall14606042011-06-30 08:33:18 +00003386 case TemplateName::SubstTemplateTemplateParm: {
3387 SubstTemplateTemplateParmStorage *subst
3388 = Name.getAsSubstTemplateTemplateParm();
3389 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3390 NameLoc);
3391 }
3392
3393 case TemplateName::SubstTemplateTemplateParmPack: {
3394 SubstTemplateTemplateParmPackStorage *subst
3395 = Name.getAsSubstTemplateTemplateParmPack();
3396 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3397 NameLoc);
3398 }
3399 }
3400
3401 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003402}
3403
Jay Foad4ba2a172011-01-12 09:06:06 +00003404TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003405 switch (Name.getKind()) {
3406 case TemplateName::QualifiedTemplate:
3407 case TemplateName::Template: {
3408 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003409 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003410 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003411 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3412
3413 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003414 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003415 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003416
John McCall14606042011-06-30 08:33:18 +00003417 case TemplateName::OverloadedTemplate:
3418 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003419
John McCall14606042011-06-30 08:33:18 +00003420 case TemplateName::DependentTemplate: {
3421 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3422 assert(DTN && "Non-dependent template names must refer to template decls.");
3423 return DTN->CanonicalTemplateName;
3424 }
3425
3426 case TemplateName::SubstTemplateTemplateParm: {
3427 SubstTemplateTemplateParmStorage *subst
3428 = Name.getAsSubstTemplateTemplateParm();
3429 return getCanonicalTemplateName(subst->getReplacement());
3430 }
3431
3432 case TemplateName::SubstTemplateTemplateParmPack: {
3433 SubstTemplateTemplateParmPackStorage *subst
3434 = Name.getAsSubstTemplateTemplateParmPack();
3435 TemplateTemplateParmDecl *canonParameter
3436 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3437 TemplateArgument canonArgPack
3438 = getCanonicalTemplateArgument(subst->getArgumentPack());
3439 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3440 }
3441 }
3442
3443 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003444}
3445
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003446bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3447 X = getCanonicalTemplateName(X);
3448 Y = getCanonicalTemplateName(Y);
3449 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3450}
3451
Mike Stump1eb44332009-09-09 15:08:12 +00003452TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003453ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003454 switch (Arg.getKind()) {
3455 case TemplateArgument::Null:
3456 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003457
Douglas Gregor1275ae02009-07-28 23:00:59 +00003458 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003459 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003460
Douglas Gregord2008e22012-04-06 22:40:38 +00003461 case TemplateArgument::Declaration: {
3462 if (Decl *D = Arg.getAsDecl())
3463 return TemplateArgument(D->getCanonicalDecl());
3464 return TemplateArgument((Decl*)0);
3465 }
Mike Stump1eb44332009-09-09 15:08:12 +00003466
Douglas Gregor788cd062009-11-11 01:00:40 +00003467 case TemplateArgument::Template:
3468 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003469
3470 case TemplateArgument::TemplateExpansion:
3471 return TemplateArgument(getCanonicalTemplateName(
3472 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003473 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003474
Douglas Gregor1275ae02009-07-28 23:00:59 +00003475 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00003476 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003477
Douglas Gregor1275ae02009-07-28 23:00:59 +00003478 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003479 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003480
Douglas Gregor1275ae02009-07-28 23:00:59 +00003481 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003482 if (Arg.pack_size() == 0)
3483 return Arg;
3484
Douglas Gregor910f8002010-11-07 23:05:16 +00003485 TemplateArgument *CanonArgs
3486 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003487 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003488 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003489 AEnd = Arg.pack_end();
3490 A != AEnd; (void)++A, ++Idx)
3491 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003492
Douglas Gregor910f8002010-11-07 23:05:16 +00003493 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003494 }
3495 }
3496
3497 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003498 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003499}
3500
Douglas Gregord57959a2009-03-27 23:10:48 +00003501NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003502ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003503 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003504 return 0;
3505
3506 switch (NNS->getKind()) {
3507 case NestedNameSpecifier::Identifier:
3508 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003509 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003510 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3511 NNS->getAsIdentifier());
3512
3513 case NestedNameSpecifier::Namespace:
3514 // A namespace is canonical; build a nested-name-specifier with
3515 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003516 return NestedNameSpecifier::Create(*this, 0,
3517 NNS->getAsNamespace()->getOriginalNamespace());
3518
3519 case NestedNameSpecifier::NamespaceAlias:
3520 // A namespace is canonical; build a nested-name-specifier with
3521 // this namespace and no prefix.
3522 return NestedNameSpecifier::Create(*this, 0,
3523 NNS->getAsNamespaceAlias()->getNamespace()
3524 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003525
3526 case NestedNameSpecifier::TypeSpec:
3527 case NestedNameSpecifier::TypeSpecWithTemplate: {
3528 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003529
3530 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3531 // break it apart into its prefix and identifier, then reconsititute those
3532 // as the canonical nested-name-specifier. This is required to canonicalize
3533 // a dependent nested-name-specifier involving typedefs of dependent-name
3534 // types, e.g.,
3535 // typedef typename T::type T1;
3536 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00003537 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3538 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00003539 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00003540
Eli Friedman16412ef2012-03-03 04:09:56 +00003541 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3542 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3543 // first place?
John McCall3b657512011-01-19 10:06:00 +00003544 return NestedNameSpecifier::Create(*this, 0, false,
3545 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003546 }
3547
3548 case NestedNameSpecifier::Global:
3549 // The global specifier is canonical and unique.
3550 return NNS;
3551 }
3552
David Blaikie7530c032012-01-17 06:56:22 +00003553 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003554}
3555
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003556
Jay Foad4ba2a172011-01-12 09:06:06 +00003557const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003558 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003559 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003560 // Handle the common positive case fast.
3561 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3562 return AT;
3563 }
Mike Stump1eb44332009-09-09 15:08:12 +00003564
John McCall0953e762009-09-24 19:53:00 +00003565 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003566 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003567 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003568
John McCall0953e762009-09-24 19:53:00 +00003569 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003570 // implements C99 6.7.3p8: "If the specification of an array type includes
3571 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003572
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003573 // If we get here, we either have type qualifiers on the type, or we have
3574 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003575 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003576
John McCall3b657512011-01-19 10:06:00 +00003577 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003578 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00003579
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003580 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00003581 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00003582 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003583 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003584
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003585 // Otherwise, we have an array and we have qualifiers on it. Push the
3586 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003587 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003588
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003589 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3590 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3591 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003592 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003593 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3594 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3595 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003596 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003597
Mike Stump1eb44332009-09-09 15:08:12 +00003598 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003599 = dyn_cast<DependentSizedArrayType>(ATy))
3600 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003601 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003602 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003603 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003604 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003605 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003606
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003607 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003608 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003609 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003610 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003611 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003612 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003613}
3614
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003615QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003616 // C99 6.7.5.3p7:
3617 // A declaration of a parameter as "array of type" shall be
3618 // adjusted to "qualified pointer to type", where the type
3619 // qualifiers (if any) are those specified within the [ and ] of
3620 // the array type derivation.
3621 if (T->isArrayType())
3622 return getArrayDecayedType(T);
3623
3624 // C99 6.7.5.3p8:
3625 // A declaration of a parameter as "function returning type"
3626 // shall be adjusted to "pointer to function returning type", as
3627 // in 6.3.2.1.
3628 if (T->isFunctionType())
3629 return getPointerType(T);
3630
3631 return T;
3632}
3633
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003634QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003635 T = getVariableArrayDecayedType(T);
3636 T = getAdjustedParameterType(T);
3637 return T.getUnqualifiedType();
3638}
3639
Chris Lattnere6327742008-04-02 05:18:44 +00003640/// getArrayDecayedType - Return the properly qualified result of decaying the
3641/// specified array type to a pointer. This operation is non-trivial when
3642/// handling typedefs etc. The canonical type of "T" must be an array type,
3643/// this returns a pointer to a properly qualified element of the array.
3644///
3645/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003646QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003647 // Get the element type with 'getAsArrayType' so that we don't lose any
3648 // typedefs in the element type of the array. This also handles propagation
3649 // of type qualifiers from the array type into the element type if present
3650 // (C99 6.7.3p8).
3651 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3652 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003653
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003654 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003655
3656 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003657 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003658}
3659
John McCall3b657512011-01-19 10:06:00 +00003660QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3661 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003662}
3663
John McCall3b657512011-01-19 10:06:00 +00003664QualType ASTContext::getBaseElementType(QualType type) const {
3665 Qualifiers qs;
3666 while (true) {
3667 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003668 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00003669 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003670
John McCall3b657512011-01-19 10:06:00 +00003671 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00003672 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00003673 }
Mike Stump1eb44332009-09-09 15:08:12 +00003674
John McCall3b657512011-01-19 10:06:00 +00003675 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003676}
3677
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003678/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003679uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003680ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3681 uint64_t ElementCount = 1;
3682 do {
3683 ElementCount *= CA->getSize().getZExtValue();
3684 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3685 } while (CA);
3686 return ElementCount;
3687}
3688
Reid Spencer5f016e22007-07-11 17:01:13 +00003689/// getFloatingRank - Return a relative rank for floating point types.
3690/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003691static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003692 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003693 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003694
John McCall183700f2009-09-21 23:43:11 +00003695 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3696 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003697 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003698 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003699 case BuiltinType::Float: return FloatRank;
3700 case BuiltinType::Double: return DoubleRank;
3701 case BuiltinType::LongDouble: return LongDoubleRank;
3702 }
3703}
3704
Mike Stump1eb44332009-09-09 15:08:12 +00003705/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3706/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003707/// 'typeDomain' is a real floating point or complex type.
3708/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003709QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3710 QualType Domain) const {
3711 FloatingRank EltRank = getFloatingRank(Size);
3712 if (Domain->isComplexType()) {
3713 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003714 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00003715 case FloatRank: return FloatComplexTy;
3716 case DoubleRank: return DoubleComplexTy;
3717 case LongDoubleRank: return LongDoubleComplexTy;
3718 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003719 }
Chris Lattner1361b112008-04-06 23:58:54 +00003720
3721 assert(Domain->isRealFloatingType() && "Unknown domain!");
3722 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003723 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattner1361b112008-04-06 23:58:54 +00003724 case FloatRank: return FloatTy;
3725 case DoubleRank: return DoubleTy;
3726 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003727 }
David Blaikie561d3ab2012-01-17 02:30:50 +00003728 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00003729}
3730
Chris Lattner7cfeb082008-04-06 23:55:33 +00003731/// getFloatingTypeOrder - Compare the rank of the two specified floating
3732/// point types, ignoring the domain of the type (i.e. 'double' ==
3733/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003734/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003735int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003736 FloatingRank LHSR = getFloatingRank(LHS);
3737 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003738
Chris Lattnera75cea32008-04-06 23:38:49 +00003739 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003740 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003741 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003742 return 1;
3743 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003744}
3745
Chris Lattnerf52ab252008-04-06 22:59:24 +00003746/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3747/// routine will assert if passed a built-in type that isn't an integer or enum,
3748/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003749unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003750 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003751
Chris Lattnerf52ab252008-04-06 22:59:24 +00003752 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003753 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003754 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003755 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003756 case BuiltinType::Char_S:
3757 case BuiltinType::Char_U:
3758 case BuiltinType::SChar:
3759 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003760 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003761 case BuiltinType::Short:
3762 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003763 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003764 case BuiltinType::Int:
3765 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003766 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003767 case BuiltinType::Long:
3768 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003769 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003770 case BuiltinType::LongLong:
3771 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003772 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003773 case BuiltinType::Int128:
3774 case BuiltinType::UInt128:
3775 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003776 }
3777}
3778
Eli Friedman04e83572009-08-20 04:21:42 +00003779/// \brief Whether this is a promotable bitfield reference according
3780/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3781///
3782/// \returns the type this bit-field will promote to, or NULL if no
3783/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003784QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003785 if (E->isTypeDependent() || E->isValueDependent())
3786 return QualType();
3787
Eli Friedman04e83572009-08-20 04:21:42 +00003788 FieldDecl *Field = E->getBitField();
3789 if (!Field)
3790 return QualType();
3791
3792 QualType FT = Field->getType();
3793
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003794 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00003795 uint64_t IntSize = getTypeSize(IntTy);
3796 // GCC extension compatibility: if the bit-field size is less than or equal
3797 // to the size of int, it gets promoted no matter what its type is.
3798 // For instance, unsigned long bf : 4 gets promoted to signed int.
3799 if (BitWidth < IntSize)
3800 return IntTy;
3801
3802 if (BitWidth == IntSize)
3803 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3804
3805 // Types bigger than int are not subject to promotions, and therefore act
3806 // like the base type.
3807 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3808 // is ridiculous.
3809 return QualType();
3810}
3811
Eli Friedmana95d7572009-08-19 07:44:53 +00003812/// getPromotedIntegerType - Returns the type that Promotable will
3813/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3814/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003815QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003816 assert(!Promotable.isNull());
3817 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003818 if (const EnumType *ET = Promotable->getAs<EnumType>())
3819 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00003820
3821 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3822 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3823 // (3.9.1) can be converted to a prvalue of the first of the following
3824 // types that can represent all the values of its underlying type:
3825 // int, unsigned int, long int, unsigned long int, long long int, or
3826 // unsigned long long int [...]
3827 // FIXME: Is there some better way to compute this?
3828 if (BT->getKind() == BuiltinType::WChar_S ||
3829 BT->getKind() == BuiltinType::WChar_U ||
3830 BT->getKind() == BuiltinType::Char16 ||
3831 BT->getKind() == BuiltinType::Char32) {
3832 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3833 uint64_t FromSize = getTypeSize(BT);
3834 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3835 LongLongTy, UnsignedLongLongTy };
3836 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3837 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3838 if (FromSize < ToSize ||
3839 (FromSize == ToSize &&
3840 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3841 return PromoteTypes[Idx];
3842 }
3843 llvm_unreachable("char type should fit into long long");
3844 }
3845 }
3846
3847 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00003848 if (Promotable->isSignedIntegerType())
3849 return IntTy;
3850 uint64_t PromotableSize = getTypeSize(Promotable);
3851 uint64_t IntSize = getTypeSize(IntTy);
3852 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3853 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3854}
3855
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003856/// \brief Recurses in pointer/array types until it finds an objc retainable
3857/// type and returns its ownership.
3858Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3859 while (!T.isNull()) {
3860 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3861 return T.getObjCLifetime();
3862 if (T->isArrayType())
3863 T = getBaseElementType(T);
3864 else if (const PointerType *PT = T->getAs<PointerType>())
3865 T = PT->getPointeeType();
3866 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003867 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003868 else
3869 break;
3870 }
3871
3872 return Qualifiers::OCL_None;
3873}
3874
Mike Stump1eb44332009-09-09 15:08:12 +00003875/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003876/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003877/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003878int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003879 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3880 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003881 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003882
Chris Lattnerf52ab252008-04-06 22:59:24 +00003883 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3884 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003885
Chris Lattner7cfeb082008-04-06 23:55:33 +00003886 unsigned LHSRank = getIntegerRank(LHSC);
3887 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003888
Chris Lattner7cfeb082008-04-06 23:55:33 +00003889 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3890 if (LHSRank == RHSRank) return 0;
3891 return LHSRank > RHSRank ? 1 : -1;
3892 }
Mike Stump1eb44332009-09-09 15:08:12 +00003893
Chris Lattner7cfeb082008-04-06 23:55:33 +00003894 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3895 if (LHSUnsigned) {
3896 // If the unsigned [LHS] type is larger, return it.
3897 if (LHSRank >= RHSRank)
3898 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003899
Chris Lattner7cfeb082008-04-06 23:55:33 +00003900 // If the signed type can represent all values of the unsigned type, it
3901 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003902 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003903 return -1;
3904 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003905
Chris Lattner7cfeb082008-04-06 23:55:33 +00003906 // If the unsigned [RHS] type is larger, return it.
3907 if (RHSRank >= LHSRank)
3908 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003909
Chris Lattner7cfeb082008-04-06 23:55:33 +00003910 // If the signed type can represent all values of the unsigned type, it
3911 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003912 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003913 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003914}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003915
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003916static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003917CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3918 DeclContext *DC, IdentifierInfo *Id) {
3919 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00003920 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003921 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003922 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003923 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003924}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003925
Mike Stump1eb44332009-09-09 15:08:12 +00003926// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003927QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003928 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003929 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003930 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003931 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003932 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003933
Anders Carlssonf06273f2007-11-19 00:25:30 +00003934 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003935
Anders Carlsson71993dd2007-08-17 05:31:46 +00003936 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003937 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003938 // int flags;
3939 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003940 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003941 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003942 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003943 FieldTypes[3] = LongTy;
3944
Anders Carlsson71993dd2007-08-17 05:31:46 +00003945 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003946 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003947 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003948 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003949 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003950 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003951 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003952 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003953 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00003954 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003955 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003956 }
3957
Douglas Gregor838db382010-02-11 01:19:42 +00003958 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003959 }
Mike Stump1eb44332009-09-09 15:08:12 +00003960
Anders Carlsson71993dd2007-08-17 05:31:46 +00003961 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003962}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003963
Douglas Gregor319ac892009-04-23 22:29:11 +00003964void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003965 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003966 assert(Rec && "Invalid CFConstantStringType");
3967 CFConstantStringTypeDecl = Rec->getDecl();
3968}
3969
Jay Foad4ba2a172011-01-12 09:06:06 +00003970QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003971 if (BlockDescriptorType)
3972 return getTagDeclType(BlockDescriptorType);
3973
3974 RecordDecl *T;
3975 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003976 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003977 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003978 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003979
3980 QualType FieldTypes[] = {
3981 UnsignedLongTy,
3982 UnsignedLongTy,
3983 };
3984
3985 const char *FieldNames[] = {
3986 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003987 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003988 };
3989
3990 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003991 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003992 SourceLocation(),
3993 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003994 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003995 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003996 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003997 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00003998 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003999 T->addDecl(Field);
4000 }
4001
Douglas Gregor838db382010-02-11 01:19:42 +00004002 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004003
4004 BlockDescriptorType = T;
4005
4006 return getTagDeclType(BlockDescriptorType);
4007}
4008
Jay Foad4ba2a172011-01-12 09:06:06 +00004009QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004010 if (BlockDescriptorExtendedType)
4011 return getTagDeclType(BlockDescriptorExtendedType);
4012
4013 RecordDecl *T;
4014 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004015 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004016 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004017 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004018
4019 QualType FieldTypes[] = {
4020 UnsignedLongTy,
4021 UnsignedLongTy,
4022 getPointerType(VoidPtrTy),
4023 getPointerType(VoidPtrTy)
4024 };
4025
4026 const char *FieldNames[] = {
4027 "reserved",
4028 "Size",
4029 "CopyFuncPtr",
4030 "DestroyFuncPtr"
4031 };
4032
4033 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004034 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004035 SourceLocation(),
4036 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004037 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004038 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004039 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004040 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004041 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004042 T->addDecl(Field);
4043 }
4044
Douglas Gregor838db382010-02-11 01:19:42 +00004045 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004046
4047 BlockDescriptorExtendedType = T;
4048
4049 return getTagDeclType(BlockDescriptorExtendedType);
4050}
4051
Jay Foad4ba2a172011-01-12 09:06:06 +00004052bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00004053 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004054 return true;
David Blaikie4e4d0842012-03-11 07:00:24 +00004055 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004056 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4057 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00004058 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004059
4060 }
4061 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004062 return false;
4063}
4064
Jay Foad4ba2a172011-01-12 09:06:06 +00004065QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00004066ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004067 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00004068 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004069 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00004070 // unsigned int __flags;
4071 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00004072 // void *__copy_helper; // as needed
4073 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004074 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00004075 // } *
4076
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004077 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4078
4079 // FIXME: Move up
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00004080 SmallString<36> Name;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00004081 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4082 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004083 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004084 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004085 T->startDefinition();
4086 QualType Int32Ty = IntTy;
4087 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4088 QualType FieldTypes[] = {
4089 getPointerType(VoidPtrTy),
4090 getPointerType(getTagDeclType(T)),
4091 Int32Ty,
4092 Int32Ty,
4093 getPointerType(VoidPtrTy),
4094 getPointerType(VoidPtrTy),
4095 Ty
4096 };
4097
Chris Lattner5f9e2722011-07-23 10:55:15 +00004098 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004099 "__isa",
4100 "__forwarding",
4101 "__flags",
4102 "__size",
4103 "__copy_helper",
4104 "__destroy_helper",
4105 DeclName,
4106 };
4107
4108 for (size_t i = 0; i < 7; ++i) {
4109 if (!HasCopyAndDispose && i >=4 && i <= 5)
4110 continue;
4111 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004112 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004113 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004114 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004115 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004116 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004117 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004118 T->addDecl(Field);
4119 }
4120
Douglas Gregor838db382010-02-11 01:19:42 +00004121 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004122
4123 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00004124}
4125
Douglas Gregore97179c2011-09-08 01:46:34 +00004126TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4127 if (!ObjCInstanceTypeDecl)
4128 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4129 getTranslationUnitDecl(),
4130 SourceLocation(),
4131 SourceLocation(),
4132 &Idents.get("instancetype"),
4133 getTrivialTypeSourceInfo(getObjCIdType()));
4134 return ObjCInstanceTypeDecl;
4135}
4136
Anders Carlssone8c49532007-10-29 06:33:42 +00004137// This returns true if a type has been typedefed to BOOL:
4138// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004139static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004140 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004141 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4142 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004143
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004144 return false;
4145}
4146
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004147/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004148/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004149CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004150 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4151 return CharUnits::Zero();
4152
Ken Dyck199c3d62010-01-11 17:06:35 +00004153 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004154
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004155 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004156 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004157 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004158 // Treat arrays as pointers, since that's how they're passed in.
4159 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004160 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004161 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004162}
4163
4164static inline
4165std::string charUnitsToString(const CharUnits &CU) {
4166 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004167}
4168
John McCall6b5a61b2011-02-07 10:33:21 +00004169/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004170/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004171std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4172 std::string S;
4173
David Chisnall5e530af2009-11-17 19:33:30 +00004174 const BlockDecl *Decl = Expr->getBlockDecl();
4175 QualType BlockTy =
4176 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4177 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004178 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004179 // Compute size of all parameters.
4180 // Start with computing size of a pointer in number of bytes.
4181 // FIXME: There might(should) be a better way of doing this computation!
4182 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004183 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4184 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004185 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004186 E = Decl->param_end(); PI != E; ++PI) {
4187 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004188 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004189 if (sz.isZero())
4190 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004191 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004192 ParmOffset += sz;
4193 }
4194 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004195 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004196 // Block pointer and offset.
4197 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004198
4199 // Argument types.
4200 ParmOffset = PtrSize;
4201 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4202 Decl->param_end(); PI != E; ++PI) {
4203 ParmVarDecl *PVDecl = *PI;
4204 QualType PType = PVDecl->getOriginalType();
4205 if (const ArrayType *AT =
4206 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4207 // Use array's original type only if it has known number of
4208 // elements.
4209 if (!isa<ConstantArrayType>(AT))
4210 PType = PVDecl->getType();
4211 } else if (PType->isFunctionType())
4212 PType = PVDecl->getType();
4213 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004214 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004215 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004216 }
John McCall6b5a61b2011-02-07 10:33:21 +00004217
4218 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004219}
4220
Douglas Gregorf968d832011-05-27 01:19:52 +00004221bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004222 std::string& S) {
4223 // Encode result type.
4224 getObjCEncodingForType(Decl->getResultType(), S);
4225 CharUnits ParmOffset;
4226 // Compute size of all parameters.
4227 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4228 E = Decl->param_end(); PI != E; ++PI) {
4229 QualType PType = (*PI)->getType();
4230 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004231 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004232 continue;
4233
David Chisnall5389f482010-12-30 14:05:53 +00004234 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004235 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004236 ParmOffset += sz;
4237 }
4238 S += charUnitsToString(ParmOffset);
4239 ParmOffset = CharUnits::Zero();
4240
4241 // Argument types.
4242 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4243 E = Decl->param_end(); PI != E; ++PI) {
4244 ParmVarDecl *PVDecl = *PI;
4245 QualType PType = PVDecl->getOriginalType();
4246 if (const ArrayType *AT =
4247 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4248 // Use array's original type only if it has known number of
4249 // elements.
4250 if (!isa<ConstantArrayType>(AT))
4251 PType = PVDecl->getType();
4252 } else if (PType->isFunctionType())
4253 PType = PVDecl->getType();
4254 getObjCEncodingForType(PType, S);
4255 S += charUnitsToString(ParmOffset);
4256 ParmOffset += getObjCEncodingTypeSize(PType);
4257 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004258
4259 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004260}
4261
Bob Wilsondc8dab62011-11-30 01:57:58 +00004262/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4263/// method parameter or return type. If Extended, include class names and
4264/// block object types.
4265void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4266 QualType T, std::string& S,
4267 bool Extended) const {
4268 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4269 getObjCEncodingForTypeQualifier(QT, S);
4270 // Encode parameter type.
4271 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4272 true /*OutermostType*/,
4273 false /*EncodingProperty*/,
4274 false /*StructField*/,
4275 Extended /*EncodeBlockParameters*/,
4276 Extended /*EncodeClassNames*/);
4277}
4278
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004279/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004280/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004281bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004282 std::string& S,
4283 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004284 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004285 // Encode return type.
4286 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4287 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004288 // Compute size of all parameters.
4289 // Start with computing size of a pointer in number of bytes.
4290 // FIXME: There might(should) be a better way of doing this computation!
4291 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004292 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004293 // The first two arguments (self and _cmd) are pointers; account for
4294 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004295 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004296 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004297 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004298 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004299 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004300 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004301 continue;
4302
Ken Dyck199c3d62010-01-11 17:06:35 +00004303 assert (sz.isPositive() &&
4304 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004305 ParmOffset += sz;
4306 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004307 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004308 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004309 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004310
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004311 // Argument types.
4312 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004313 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004314 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004315 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004316 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004317 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004318 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4319 // Use array's original type only if it has known number of
4320 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004321 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004322 PType = PVDecl->getType();
4323 } else if (PType->isFunctionType())
4324 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004325 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4326 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004327 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004328 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004329 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004330
4331 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004332}
4333
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004334/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004335/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004336/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4337/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004338/// Property attributes are stored as a comma-delimited C string. The simple
4339/// attributes readonly and bycopy are encoded as single characters. The
4340/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4341/// encoded as single characters, followed by an identifier. Property types
4342/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004343/// these attributes are defined by the following enumeration:
4344/// @code
4345/// enum PropertyAttributes {
4346/// kPropertyReadOnly = 'R', // property is read-only.
4347/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4348/// kPropertyByref = '&', // property is a reference to the value last assigned
4349/// kPropertyDynamic = 'D', // property is dynamic
4350/// kPropertyGetter = 'G', // followed by getter selector name
4351/// kPropertySetter = 'S', // followed by setter selector name
4352/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004353/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004354/// kPropertyWeak = 'W' // 'weak' property
4355/// kPropertyStrong = 'P' // property GC'able
4356/// kPropertyNonAtomic = 'N' // property non-atomic
4357/// };
4358/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004359void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004360 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004361 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004362 // Collect information from the property implementation decl(s).
4363 bool Dynamic = false;
4364 ObjCPropertyImplDecl *SynthesizePID = 0;
4365
4366 // FIXME: Duplicated code due to poor abstraction.
4367 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004368 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004369 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4370 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004371 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004372 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004373 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004374 if (PID->getPropertyDecl() == PD) {
4375 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4376 Dynamic = true;
4377 } else {
4378 SynthesizePID = PID;
4379 }
4380 }
4381 }
4382 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004383 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004384 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004385 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004386 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004387 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004388 if (PID->getPropertyDecl() == PD) {
4389 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4390 Dynamic = true;
4391 } else {
4392 SynthesizePID = PID;
4393 }
4394 }
Mike Stump1eb44332009-09-09 15:08:12 +00004395 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004396 }
4397 }
4398
4399 // FIXME: This is not very efficient.
4400 S = "T";
4401
4402 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004403 // GCC has some special rules regarding encoding of properties which
4404 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004405 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004406 true /* outermost type */,
4407 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004408
4409 if (PD->isReadOnly()) {
4410 S += ",R";
4411 } else {
4412 switch (PD->getSetterKind()) {
4413 case ObjCPropertyDecl::Assign: break;
4414 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004415 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004416 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004417 }
4418 }
4419
4420 // It really isn't clear at all what this means, since properties
4421 // are "dynamic by default".
4422 if (Dynamic)
4423 S += ",D";
4424
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004425 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4426 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004427
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004428 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4429 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004430 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004431 }
4432
4433 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4434 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004435 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004436 }
4437
4438 if (SynthesizePID) {
4439 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4440 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004441 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004442 }
4443
4444 // FIXME: OBJCGC: weak & strong
4445}
4446
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004447/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004448/// Another legacy compatibility encoding: 32-bit longs are encoded as
4449/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004450/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4451///
4452void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004453 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004454 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004455 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004456 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004457 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004458 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004459 PointeeTy = IntTy;
4460 }
4461 }
4462}
4463
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004464void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004465 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004466 // We follow the behavior of gcc, expanding structures which are
4467 // directly pointed to, and expanding embedded structures. Note that
4468 // these rules are sufficient to prevent recursive encoding of the
4469 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004470 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004471 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004472}
4473
David Chisnall64fd7e82010-06-04 01:10:52 +00004474static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4475 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004476 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004477 case BuiltinType::Void: return 'v';
4478 case BuiltinType::Bool: return 'B';
4479 case BuiltinType::Char_U:
4480 case BuiltinType::UChar: return 'C';
4481 case BuiltinType::UShort: return 'S';
4482 case BuiltinType::UInt: return 'I';
4483 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004484 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004485 case BuiltinType::UInt128: return 'T';
4486 case BuiltinType::ULongLong: return 'Q';
4487 case BuiltinType::Char_S:
4488 case BuiltinType::SChar: return 'c';
4489 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004490 case BuiltinType::WChar_S:
4491 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004492 case BuiltinType::Int: return 'i';
4493 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004494 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004495 case BuiltinType::LongLong: return 'q';
4496 case BuiltinType::Int128: return 't';
4497 case BuiltinType::Float: return 'f';
4498 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004499 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004500 }
4501}
4502
Douglas Gregor5471bc82011-09-08 17:18:35 +00004503static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4504 EnumDecl *Enum = ET->getDecl();
4505
4506 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4507 if (!Enum->isFixed())
4508 return 'i';
4509
4510 // The encoding of a fixed enum type matches its fixed underlying type.
4511 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4512}
4513
Jay Foad4ba2a172011-01-12 09:06:06 +00004514static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004515 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004516 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004517 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004518 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4519 // The GNU runtime requires more information; bitfields are encoded as b,
4520 // then the offset (in bits) of the first element, then the type of the
4521 // bitfield, then the size in bits. For example, in this structure:
4522 //
4523 // struct
4524 // {
4525 // int integer;
4526 // int flags:2;
4527 // };
4528 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4529 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4530 // information is not especially sensible, but we're stuck with it for
4531 // compatibility with GCC, although providing it breaks anything that
4532 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00004533 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004534 const RecordDecl *RD = FD->getParent();
4535 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004536 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004537 if (const EnumType *ET = T->getAs<EnumType>())
4538 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004539 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004540 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004541 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004542 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004543}
4544
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004545// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004546void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4547 bool ExpandPointedToStructures,
4548 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004549 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004550 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004551 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004552 bool StructField,
4553 bool EncodeBlockParameters,
4554 bool EncodeClassNames) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004555 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004556 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004557 return EncodeBitField(this, S, T, FD);
4558 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004559 return;
4560 }
Mike Stump1eb44332009-09-09 15:08:12 +00004561
John McCall183700f2009-09-21 23:43:11 +00004562 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004563 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004564 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004565 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004566 return;
4567 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004568
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004569 // encoding for pointer or r3eference types.
4570 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004571 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004572 if (PT->isObjCSelType()) {
4573 S += ':';
4574 return;
4575 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004576 PointeeTy = PT->getPointeeType();
4577 }
4578 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4579 PointeeTy = RT->getPointeeType();
4580 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004581 bool isReadOnly = false;
4582 // For historical/compatibility reasons, the read-only qualifier of the
4583 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4584 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004585 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004586 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004587 if (OutermostType && T.isConstQualified()) {
4588 isReadOnly = true;
4589 S += 'r';
4590 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004591 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004592 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004593 while (P->getAs<PointerType>())
4594 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004595 if (P.isConstQualified()) {
4596 isReadOnly = true;
4597 S += 'r';
4598 }
4599 }
4600 if (isReadOnly) {
4601 // Another legacy compatibility encoding. Some ObjC qualifier and type
4602 // combinations need to be rearranged.
4603 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004604 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004605 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004606 }
Mike Stump1eb44332009-09-09 15:08:12 +00004607
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004608 if (PointeeTy->isCharType()) {
4609 // char pointer types should be encoded as '*' unless it is a
4610 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004611 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004612 S += '*';
4613 return;
4614 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004615 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004616 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4617 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4618 S += '#';
4619 return;
4620 }
4621 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4622 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4623 S += '@';
4624 return;
4625 }
4626 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004627 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004628 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004629 getLegacyIntegralTypeEncoding(PointeeTy);
4630
Mike Stump1eb44332009-09-09 15:08:12 +00004631 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004632 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004633 return;
4634 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004635
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004636 if (const ArrayType *AT =
4637 // Ignore type qualifiers etc.
4638 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004639 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004640 // Incomplete arrays are encoded as a pointer to the array element.
4641 S += '^';
4642
Mike Stump1eb44332009-09-09 15:08:12 +00004643 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004644 false, ExpandStructures, FD);
4645 } else {
4646 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004647
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004648 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4649 if (getTypeSize(CAT->getElementType()) == 0)
4650 S += '0';
4651 else
4652 S += llvm::utostr(CAT->getSize().getZExtValue());
4653 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004654 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004655 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4656 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004657 S += '0';
4658 }
Mike Stump1eb44332009-09-09 15:08:12 +00004659
4660 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004661 false, ExpandStructures, FD);
4662 S += ']';
4663 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004664 return;
4665 }
Mike Stump1eb44332009-09-09 15:08:12 +00004666
John McCall183700f2009-09-21 23:43:11 +00004667 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004668 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004669 return;
4670 }
Mike Stump1eb44332009-09-09 15:08:12 +00004671
Ted Kremenek6217b802009-07-29 21:53:49 +00004672 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004673 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004674 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004675 // Anonymous structures print as '?'
4676 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4677 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004678 if (ClassTemplateSpecializationDecl *Spec
4679 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4680 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4681 std::string TemplateArgsStr
4682 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004683 TemplateArgs.data(),
4684 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004685 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004686
4687 S += TemplateArgsStr;
4688 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004689 } else {
4690 S += '?';
4691 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004692 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004693 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004694 if (!RDecl->isUnion()) {
4695 getObjCEncodingForStructureImpl(RDecl, S, FD);
4696 } else {
4697 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4698 FieldEnd = RDecl->field_end();
4699 Field != FieldEnd; ++Field) {
4700 if (FD) {
4701 S += '"';
4702 S += Field->getNameAsString();
4703 S += '"';
4704 }
Mike Stump1eb44332009-09-09 15:08:12 +00004705
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004706 // Special case bit-fields.
4707 if (Field->isBitField()) {
4708 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00004709 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004710 } else {
4711 QualType qt = Field->getType();
4712 getLegacyIntegralTypeEncoding(qt);
4713 getObjCEncodingForTypeImpl(qt, S, false, true,
4714 FD, /*OutermostType*/false,
4715 /*EncodingProperty*/false,
4716 /*StructField*/true);
4717 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004718 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004719 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004720 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004721 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004722 return;
4723 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004724
Douglas Gregor5471bc82011-09-08 17:18:35 +00004725 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004726 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004727 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004728 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004729 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004730 return;
4731 }
Mike Stump1eb44332009-09-09 15:08:12 +00004732
Bob Wilsondc8dab62011-11-30 01:57:58 +00004733 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004734 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00004735 if (EncodeBlockParameters) {
4736 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4737
4738 S += '<';
4739 // Block return type
4740 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4741 ExpandPointedToStructures, ExpandStructures,
4742 FD,
4743 false /* OutermostType */,
4744 EncodingProperty,
4745 false /* StructField */,
4746 EncodeBlockParameters,
4747 EncodeClassNames);
4748 // Block self
4749 S += "@?";
4750 // Block parameters
4751 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4752 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4753 E = FPT->arg_type_end(); I && (I != E); ++I) {
4754 getObjCEncodingForTypeImpl(*I, S,
4755 ExpandPointedToStructures,
4756 ExpandStructures,
4757 FD,
4758 false /* OutermostType */,
4759 EncodingProperty,
4760 false /* StructField */,
4761 EncodeBlockParameters,
4762 EncodeClassNames);
4763 }
4764 }
4765 S += '>';
4766 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004767 return;
4768 }
Mike Stump1eb44332009-09-09 15:08:12 +00004769
John McCallc12c5bb2010-05-15 11:32:37 +00004770 // Ignore protocol qualifiers when mangling at this level.
4771 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4772 T = OT->getBaseType();
4773
John McCall0953e762009-09-24 19:53:00 +00004774 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004775 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004776 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004777 S += '{';
4778 const IdentifierInfo *II = OI->getIdentifier();
4779 S += II->getName();
4780 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004781 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004782 DeepCollectObjCIvars(OI, true, Ivars);
4783 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004784 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004785 if (Field->isBitField())
4786 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004787 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004788 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004789 }
4790 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004791 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004792 }
Mike Stump1eb44332009-09-09 15:08:12 +00004793
John McCall183700f2009-09-21 23:43:11 +00004794 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004795 if (OPT->isObjCIdType()) {
4796 S += '@';
4797 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004798 }
Mike Stump1eb44332009-09-09 15:08:12 +00004799
Steve Naroff27d20a22009-10-28 22:03:49 +00004800 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4801 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4802 // Since this is a binary compatibility issue, need to consult with runtime
4803 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004804 S += '#';
4805 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004806 }
Mike Stump1eb44332009-09-09 15:08:12 +00004807
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004808 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004809 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004810 ExpandPointedToStructures,
4811 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00004812 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00004813 // Note that we do extended encoding of protocol qualifer list
4814 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004815 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004816 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4817 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004818 S += '<';
4819 S += (*I)->getNameAsString();
4820 S += '>';
4821 }
4822 S += '"';
4823 }
4824 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004825 }
Mike Stump1eb44332009-09-09 15:08:12 +00004826
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004827 QualType PointeeTy = OPT->getPointeeType();
4828 if (!EncodingProperty &&
4829 isa<TypedefType>(PointeeTy.getTypePtr())) {
4830 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004831 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004832 // {...};
4833 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004834 getObjCEncodingForTypeImpl(PointeeTy, S,
4835 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004836 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004837 return;
4838 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004839
4840 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00004841 if (OPT->getInterfaceDecl() &&
4842 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004843 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004844 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004845 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4846 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004847 S += '<';
4848 S += (*I)->getNameAsString();
4849 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004850 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004851 S += '"';
4852 }
4853 return;
4854 }
Mike Stump1eb44332009-09-09 15:08:12 +00004855
John McCall532ec7b2010-05-17 23:56:34 +00004856 // gcc just blithely ignores member pointers.
4857 // TODO: maybe there should be a mangling for these
4858 if (T->getAs<MemberPointerType>())
4859 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004860
4861 if (T->isVectorType()) {
4862 // This matches gcc's encoding, even though technically it is
4863 // insufficient.
4864 // FIXME. We should do a better job than gcc.
4865 return;
4866 }
4867
David Blaikieb219cfc2011-09-23 05:06:16 +00004868 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004869}
4870
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004871void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4872 std::string &S,
4873 const FieldDecl *FD,
4874 bool includeVBases) const {
4875 assert(RDecl && "Expected non-null RecordDecl");
4876 assert(!RDecl->isUnion() && "Should not be called for unions");
4877 if (!RDecl->getDefinition())
4878 return;
4879
4880 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4881 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4882 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4883
4884 if (CXXRec) {
4885 for (CXXRecordDecl::base_class_iterator
4886 BI = CXXRec->bases_begin(),
4887 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4888 if (!BI->isVirtual()) {
4889 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004890 if (base->isEmpty())
4891 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00004892 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004893 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4894 std::make_pair(offs, base));
4895 }
4896 }
4897 }
4898
4899 unsigned i = 0;
4900 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4901 FieldEnd = RDecl->field_end();
4902 Field != FieldEnd; ++Field, ++i) {
4903 uint64_t offs = layout.getFieldOffset(i);
4904 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00004905 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004906 }
4907
4908 if (CXXRec && includeVBases) {
4909 for (CXXRecordDecl::base_class_iterator
4910 BI = CXXRec->vbases_begin(),
4911 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4912 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004913 if (base->isEmpty())
4914 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00004915 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00004916 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4917 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4918 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004919 }
4920 }
4921
4922 CharUnits size;
4923 if (CXXRec) {
4924 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4925 } else {
4926 size = layout.getSize();
4927 }
4928
4929 uint64_t CurOffs = 0;
4930 std::multimap<uint64_t, NamedDecl *>::iterator
4931 CurLayObj = FieldOrBaseOffsets.begin();
4932
Douglas Gregor58db7a52012-04-27 22:30:01 +00004933 if (CXXRec && CXXRec->isDynamicClass() &&
4934 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004935 if (FD) {
4936 S += "\"_vptr$";
4937 std::string recname = CXXRec->getNameAsString();
4938 if (recname.empty()) recname = "?";
4939 S += recname;
4940 S += '"';
4941 }
4942 S += "^^?";
4943 CurOffs += getTypeSize(VoidPtrTy);
4944 }
4945
4946 if (!RDecl->hasFlexibleArrayMember()) {
4947 // Mark the end of the structure.
4948 uint64_t offs = toBits(size);
4949 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4950 std::make_pair(offs, (NamedDecl*)0));
4951 }
4952
4953 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4954 assert(CurOffs <= CurLayObj->first);
4955
4956 if (CurOffs < CurLayObj->first) {
4957 uint64_t padding = CurLayObj->first - CurOffs;
4958 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4959 // packing/alignment of members is different that normal, in which case
4960 // the encoding will be out-of-sync with the real layout.
4961 // If the runtime switches to just consider the size of types without
4962 // taking into account alignment, we could make padding explicit in the
4963 // encoding (e.g. using arrays of chars). The encoding strings would be
4964 // longer then though.
4965 CurOffs += padding;
4966 }
4967
4968 NamedDecl *dcl = CurLayObj->second;
4969 if (dcl == 0)
4970 break; // reached end of structure.
4971
4972 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4973 // We expand the bases without their virtual bases since those are going
4974 // in the initial structure. Note that this differs from gcc which
4975 // expands virtual bases each time one is encountered in the hierarchy,
4976 // making the encoding type bigger than it really is.
4977 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004978 assert(!base->isEmpty());
4979 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004980 } else {
4981 FieldDecl *field = cast<FieldDecl>(dcl);
4982 if (FD) {
4983 S += '"';
4984 S += field->getNameAsString();
4985 S += '"';
4986 }
4987
4988 if (field->isBitField()) {
4989 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004990 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004991 } else {
4992 QualType qt = field->getType();
4993 getLegacyIntegralTypeEncoding(qt);
4994 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4995 /*OutermostType*/false,
4996 /*EncodingProperty*/false,
4997 /*StructField*/true);
4998 CurOffs += getTypeSize(field->getType());
4999 }
5000 }
5001 }
5002}
5003
Mike Stump1eb44332009-09-09 15:08:12 +00005004void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005005 std::string& S) const {
5006 if (QT & Decl::OBJC_TQ_In)
5007 S += 'n';
5008 if (QT & Decl::OBJC_TQ_Inout)
5009 S += 'N';
5010 if (QT & Decl::OBJC_TQ_Out)
5011 S += 'o';
5012 if (QT & Decl::OBJC_TQ_Bycopy)
5013 S += 'O';
5014 if (QT & Decl::OBJC_TQ_Byref)
5015 S += 'R';
5016 if (QT & Decl::OBJC_TQ_Oneway)
5017 S += 'V';
5018}
5019
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005020TypedefDecl *ASTContext::getObjCIdDecl() const {
5021 if (!ObjCIdDecl) {
5022 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5023 T = getObjCObjectPointerType(T);
5024 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5025 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5026 getTranslationUnitDecl(),
5027 SourceLocation(), SourceLocation(),
5028 &Idents.get("id"), IdInfo);
5029 }
5030
5031 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005032}
5033
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005034TypedefDecl *ASTContext::getObjCSelDecl() const {
5035 if (!ObjCSelDecl) {
5036 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5037 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5038 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5039 getTranslationUnitDecl(),
5040 SourceLocation(), SourceLocation(),
5041 &Idents.get("SEL"), SelInfo);
5042 }
5043 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005044}
5045
Douglas Gregor79d67262011-08-12 05:59:41 +00005046TypedefDecl *ASTContext::getObjCClassDecl() const {
5047 if (!ObjCClassDecl) {
5048 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5049 T = getObjCObjectPointerType(T);
5050 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5051 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5052 getTranslationUnitDecl(),
5053 SourceLocation(), SourceLocation(),
5054 &Idents.get("Class"), ClassInfo);
5055 }
5056
5057 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005058}
5059
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005060ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5061 if (!ObjCProtocolClassDecl) {
5062 ObjCProtocolClassDecl
5063 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5064 SourceLocation(),
5065 &Idents.get("Protocol"),
5066 /*PrevDecl=*/0,
5067 SourceLocation(), true);
5068 }
5069
5070 return ObjCProtocolClassDecl;
5071}
5072
Meador Ingec5613b22012-06-16 03:34:49 +00005073//===----------------------------------------------------------------------===//
5074// __builtin_va_list Construction Functions
5075//===----------------------------------------------------------------------===//
5076
5077static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5078 // typedef char* __builtin_va_list;
5079 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5080 TypeSourceInfo *TInfo
5081 = Context->getTrivialTypeSourceInfo(CharPtrType);
5082
5083 TypedefDecl *VaListTypeDecl
5084 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5085 Context->getTranslationUnitDecl(),
5086 SourceLocation(), SourceLocation(),
5087 &Context->Idents.get("__builtin_va_list"),
5088 TInfo);
5089 return VaListTypeDecl;
5090}
5091
5092static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5093 // typedef void* __builtin_va_list;
5094 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5095 TypeSourceInfo *TInfo
5096 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5097
5098 TypedefDecl *VaListTypeDecl
5099 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5100 Context->getTranslationUnitDecl(),
5101 SourceLocation(), SourceLocation(),
5102 &Context->Idents.get("__builtin_va_list"),
5103 TInfo);
5104 return VaListTypeDecl;
5105}
5106
5107static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5108 // typedef struct __va_list_tag {
5109 RecordDecl *VaListTagDecl;
5110
5111 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5112 Context->getTranslationUnitDecl(),
5113 &Context->Idents.get("__va_list_tag"));
5114 VaListTagDecl->startDefinition();
5115
5116 const size_t NumFields = 5;
5117 QualType FieldTypes[NumFields];
5118 const char *FieldNames[NumFields];
5119
5120 // unsigned char gpr;
5121 FieldTypes[0] = Context->UnsignedCharTy;
5122 FieldNames[0] = "gpr";
5123
5124 // unsigned char fpr;
5125 FieldTypes[1] = Context->UnsignedCharTy;
5126 FieldNames[1] = "fpr";
5127
5128 // unsigned short reserved;
5129 FieldTypes[2] = Context->UnsignedShortTy;
5130 FieldNames[2] = "reserved";
5131
5132 // void* overflow_arg_area;
5133 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5134 FieldNames[3] = "overflow_arg_area";
5135
5136 // void* reg_save_area;
5137 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5138 FieldNames[4] = "reg_save_area";
5139
5140 // Create fields
5141 for (unsigned i = 0; i < NumFields; ++i) {
5142 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5143 SourceLocation(),
5144 SourceLocation(),
5145 &Context->Idents.get(FieldNames[i]),
5146 FieldTypes[i], /*TInfo=*/0,
5147 /*BitWidth=*/0,
5148 /*Mutable=*/false,
5149 ICIS_NoInit);
5150 Field->setAccess(AS_public);
5151 VaListTagDecl->addDecl(Field);
5152 }
5153 VaListTagDecl->completeDefinition();
5154 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005155 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005156
5157 // } __va_list_tag;
5158 TypedefDecl *VaListTagTypedefDecl
5159 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5160 Context->getTranslationUnitDecl(),
5161 SourceLocation(), SourceLocation(),
5162 &Context->Idents.get("__va_list_tag"),
5163 Context->getTrivialTypeSourceInfo(VaListTagType));
5164 QualType VaListTagTypedefType =
5165 Context->getTypedefType(VaListTagTypedefDecl);
5166
5167 // typedef __va_list_tag __builtin_va_list[1];
5168 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5169 QualType VaListTagArrayType
5170 = Context->getConstantArrayType(VaListTagTypedefType,
5171 Size, ArrayType::Normal, 0);
5172 TypeSourceInfo *TInfo
5173 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5174 TypedefDecl *VaListTypedefDecl
5175 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5176 Context->getTranslationUnitDecl(),
5177 SourceLocation(), SourceLocation(),
5178 &Context->Idents.get("__builtin_va_list"),
5179 TInfo);
5180
5181 return VaListTypedefDecl;
5182}
5183
5184static TypedefDecl *
5185CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5186 // typedef struct __va_list_tag {
5187 RecordDecl *VaListTagDecl;
5188 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5189 Context->getTranslationUnitDecl(),
5190 &Context->Idents.get("__va_list_tag"));
5191 VaListTagDecl->startDefinition();
5192
5193 const size_t NumFields = 4;
5194 QualType FieldTypes[NumFields];
5195 const char *FieldNames[NumFields];
5196
5197 // unsigned gp_offset;
5198 FieldTypes[0] = Context->UnsignedIntTy;
5199 FieldNames[0] = "gp_offset";
5200
5201 // unsigned fp_offset;
5202 FieldTypes[1] = Context->UnsignedIntTy;
5203 FieldNames[1] = "fp_offset";
5204
5205 // void* overflow_arg_area;
5206 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5207 FieldNames[2] = "overflow_arg_area";
5208
5209 // void* reg_save_area;
5210 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5211 FieldNames[3] = "reg_save_area";
5212
5213 // Create fields
5214 for (unsigned i = 0; i < NumFields; ++i) {
5215 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5216 VaListTagDecl,
5217 SourceLocation(),
5218 SourceLocation(),
5219 &Context->Idents.get(FieldNames[i]),
5220 FieldTypes[i], /*TInfo=*/0,
5221 /*BitWidth=*/0,
5222 /*Mutable=*/false,
5223 ICIS_NoInit);
5224 Field->setAccess(AS_public);
5225 VaListTagDecl->addDecl(Field);
5226 }
5227 VaListTagDecl->completeDefinition();
5228 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005229 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005230
5231 // } __va_list_tag;
5232 TypedefDecl *VaListTagTypedefDecl
5233 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5234 Context->getTranslationUnitDecl(),
5235 SourceLocation(), SourceLocation(),
5236 &Context->Idents.get("__va_list_tag"),
5237 Context->getTrivialTypeSourceInfo(VaListTagType));
5238 QualType VaListTagTypedefType =
5239 Context->getTypedefType(VaListTagTypedefDecl);
5240
5241 // typedef __va_list_tag __builtin_va_list[1];
5242 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5243 QualType VaListTagArrayType
5244 = Context->getConstantArrayType(VaListTagTypedefType,
5245 Size, ArrayType::Normal,0);
5246 TypeSourceInfo *TInfo
5247 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5248 TypedefDecl *VaListTypedefDecl
5249 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5250 Context->getTranslationUnitDecl(),
5251 SourceLocation(), SourceLocation(),
5252 &Context->Idents.get("__builtin_va_list"),
5253 TInfo);
5254
5255 return VaListTypedefDecl;
5256}
5257
5258static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5259 // typedef int __builtin_va_list[4];
5260 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5261 QualType IntArrayType
5262 = Context->getConstantArrayType(Context->IntTy,
5263 Size, ArrayType::Normal, 0);
5264 TypedefDecl *VaListTypedefDecl
5265 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5266 Context->getTranslationUnitDecl(),
5267 SourceLocation(), SourceLocation(),
5268 &Context->Idents.get("__builtin_va_list"),
5269 Context->getTrivialTypeSourceInfo(IntArrayType));
5270
5271 return VaListTypedefDecl;
5272}
5273
5274static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5275 TargetInfo::BuiltinVaListKind Kind) {
5276 switch (Kind) {
5277 case TargetInfo::CharPtrBuiltinVaList:
5278 return CreateCharPtrBuiltinVaListDecl(Context);
5279 case TargetInfo::VoidPtrBuiltinVaList:
5280 return CreateVoidPtrBuiltinVaListDecl(Context);
5281 case TargetInfo::PowerABIBuiltinVaList:
5282 return CreatePowerABIBuiltinVaListDecl(Context);
5283 case TargetInfo::X86_64ABIBuiltinVaList:
5284 return CreateX86_64ABIBuiltinVaListDecl(Context);
5285 case TargetInfo::PNaClABIBuiltinVaList:
5286 return CreatePNaClABIBuiltinVaListDecl(Context);
5287 }
5288
5289 llvm_unreachable("Unhandled __builtin_va_list type kind");
5290}
5291
5292TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5293 if (!BuiltinVaListDecl)
5294 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5295
5296 return BuiltinVaListDecl;
5297}
5298
Meador Ingefb40e3f2012-07-01 15:57:25 +00005299QualType ASTContext::getVaListTagType() const {
5300 // Force the creation of VaListTagTy by building the __builtin_va_list
5301 // declaration.
5302 if (VaListTagTy.isNull())
5303 (void) getBuiltinVaListDecl();
5304
5305 return VaListTagTy;
5306}
5307
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005308void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00005309 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00005310 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00005311
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005312 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00005313}
5314
John McCall0bd6feb2009-12-02 08:04:21 +00005315/// \brief Retrieve the template name that corresponds to a non-empty
5316/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00005317TemplateName
5318ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5319 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00005320 unsigned size = End - Begin;
5321 assert(size > 1 && "set is not overloaded!");
5322
5323 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5324 size * sizeof(FunctionTemplateDecl*));
5325 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5326
5327 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00005328 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00005329 NamedDecl *D = *I;
5330 assert(isa<FunctionTemplateDecl>(D) ||
5331 (isa<UsingShadowDecl>(D) &&
5332 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5333 *Storage++ = D;
5334 }
5335
5336 return TemplateName(OT);
5337}
5338
Douglas Gregor7532dc62009-03-30 22:58:21 +00005339/// \brief Retrieve the template name that represents a qualified
5340/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00005341TemplateName
5342ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5343 bool TemplateKeyword,
5344 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00005345 assert(NNS && "Missing nested-name-specifier in qualified template name");
5346
Douglas Gregor789b1f62010-02-04 18:10:26 +00005347 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00005348 llvm::FoldingSetNodeID ID;
5349 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5350
5351 void *InsertPos = 0;
5352 QualifiedTemplateName *QTN =
5353 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5354 if (!QTN) {
5355 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5356 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5357 }
5358
5359 return TemplateName(QTN);
5360}
5361
5362/// \brief Retrieve the template name that represents a dependent
5363/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00005364TemplateName
5365ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5366 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00005367 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00005368 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00005369
5370 llvm::FoldingSetNodeID ID;
5371 DependentTemplateName::Profile(ID, NNS, Name);
5372
5373 void *InsertPos = 0;
5374 DependentTemplateName *QTN =
5375 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5376
5377 if (QTN)
5378 return TemplateName(QTN);
5379
5380 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5381 if (CanonNNS == NNS) {
5382 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5383 } else {
5384 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5385 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005386 DependentTemplateName *CheckQTN =
5387 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5388 assert(!CheckQTN && "Dependent type name canonicalization broken");
5389 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005390 }
5391
5392 DependentTemplateNames.InsertNode(QTN, InsertPos);
5393 return TemplateName(QTN);
5394}
5395
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005396/// \brief Retrieve the template name that represents a dependent
5397/// template name such as \c MetaFun::template operator+.
5398TemplateName
5399ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005400 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005401 assert((!NNS || NNS->isDependent()) &&
5402 "Nested name specifier must be dependent");
5403
5404 llvm::FoldingSetNodeID ID;
5405 DependentTemplateName::Profile(ID, NNS, Operator);
5406
5407 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005408 DependentTemplateName *QTN
5409 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005410
5411 if (QTN)
5412 return TemplateName(QTN);
5413
5414 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5415 if (CanonNNS == NNS) {
5416 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5417 } else {
5418 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5419 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005420
5421 DependentTemplateName *CheckQTN
5422 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5423 assert(!CheckQTN && "Dependent template name canonicalization broken");
5424 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005425 }
5426
5427 DependentTemplateNames.InsertNode(QTN, InsertPos);
5428 return TemplateName(QTN);
5429}
5430
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005431TemplateName
John McCall14606042011-06-30 08:33:18 +00005432ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5433 TemplateName replacement) const {
5434 llvm::FoldingSetNodeID ID;
5435 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5436
5437 void *insertPos = 0;
5438 SubstTemplateTemplateParmStorage *subst
5439 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5440
5441 if (!subst) {
5442 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5443 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5444 }
5445
5446 return TemplateName(subst);
5447}
5448
5449TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005450ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5451 const TemplateArgument &ArgPack) const {
5452 ASTContext &Self = const_cast<ASTContext &>(*this);
5453 llvm::FoldingSetNodeID ID;
5454 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5455
5456 void *InsertPos = 0;
5457 SubstTemplateTemplateParmPackStorage *Subst
5458 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5459
5460 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005461 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005462 ArgPack.pack_size(),
5463 ArgPack.pack_begin());
5464 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5465 }
5466
5467 return TemplateName(Subst);
5468}
5469
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005470/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005471/// TargetInfo, produce the corresponding type. The unsigned @p Type
5472/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005473CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005474 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005475 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005476 case TargetInfo::SignedShort: return ShortTy;
5477 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5478 case TargetInfo::SignedInt: return IntTy;
5479 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5480 case TargetInfo::SignedLong: return LongTy;
5481 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5482 case TargetInfo::SignedLongLong: return LongLongTy;
5483 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5484 }
5485
David Blaikieb219cfc2011-09-23 05:06:16 +00005486 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005487}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005488
5489//===----------------------------------------------------------------------===//
5490// Type Predicates.
5491//===----------------------------------------------------------------------===//
5492
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005493/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5494/// garbage collection attribute.
5495///
John McCallae278a32011-01-12 00:34:59 +00005496Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00005497 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005498 return Qualifiers::GCNone;
5499
David Blaikie4e4d0842012-03-11 07:00:24 +00005500 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00005501 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5502
5503 // Default behaviour under objective-C's gc is for ObjC pointers
5504 // (or pointers to them) be treated as though they were declared
5505 // as __strong.
5506 if (GCAttrs == Qualifiers::GCNone) {
5507 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5508 return Qualifiers::Strong;
5509 else if (Ty->isPointerType())
5510 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5511 } else {
5512 // It's not valid to set GC attributes on anything that isn't a
5513 // pointer.
5514#ifndef NDEBUG
5515 QualType CT = Ty->getCanonicalTypeInternal();
5516 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5517 CT = AT->getElementType();
5518 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5519#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005520 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005521 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005522}
5523
Chris Lattner6ac46a42008-04-07 06:51:04 +00005524//===----------------------------------------------------------------------===//
5525// Type Compatibility Testing
5526//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005527
Mike Stump1eb44332009-09-09 15:08:12 +00005528/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005529/// compatible.
5530static bool areCompatVectorTypes(const VectorType *LHS,
5531 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005532 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005533 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005534 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005535}
5536
Douglas Gregor255210e2010-08-06 10:14:59 +00005537bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5538 QualType SecondVec) {
5539 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5540 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5541
5542 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5543 return true;
5544
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005545 // Treat Neon vector types and most AltiVec vector types as if they are the
5546 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005547 const VectorType *First = FirstVec->getAs<VectorType>();
5548 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005549 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005550 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005551 First->getVectorKind() != VectorType::AltiVecPixel &&
5552 First->getVectorKind() != VectorType::AltiVecBool &&
5553 Second->getVectorKind() != VectorType::AltiVecPixel &&
5554 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005555 return true;
5556
5557 return false;
5558}
5559
Steve Naroff4084c302009-07-23 01:01:38 +00005560//===----------------------------------------------------------------------===//
5561// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5562//===----------------------------------------------------------------------===//
5563
5564/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5565/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005566bool
5567ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5568 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005569 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00005570 return true;
5571 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5572 E = rProto->protocol_end(); PI != E; ++PI)
5573 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5574 return true;
5575 return false;
5576}
5577
Steve Naroff4084c302009-07-23 01:01:38 +00005578/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5579/// return true if lhs's protocols conform to rhs's protocol; false
5580/// otherwise.
5581bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5582 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5583 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5584 return false;
5585}
5586
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005587/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5588/// Class<p1, ...>.
5589bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5590 QualType rhs) {
5591 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5592 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5593 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5594
5595 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5596 E = lhsQID->qual_end(); I != E; ++I) {
5597 bool match = false;
5598 ObjCProtocolDecl *lhsProto = *I;
5599 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5600 E = rhsOPT->qual_end(); J != E; ++J) {
5601 ObjCProtocolDecl *rhsProto = *J;
5602 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5603 match = true;
5604 break;
5605 }
5606 }
5607 if (!match)
5608 return false;
5609 }
5610 return true;
5611}
5612
Steve Naroff4084c302009-07-23 01:01:38 +00005613/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5614/// ObjCQualifiedIDType.
5615bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5616 bool compare) {
5617 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005618 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005619 lhs->isObjCIdType() || lhs->isObjCClassType())
5620 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005621 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005622 rhs->isObjCIdType() || rhs->isObjCClassType())
5623 return true;
5624
5625 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005626 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005627
Steve Naroff4084c302009-07-23 01:01:38 +00005628 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005629
Steve Naroff4084c302009-07-23 01:01:38 +00005630 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005631 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005632 // make sure we check the class hierarchy.
5633 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5634 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5635 E = lhsQID->qual_end(); I != E; ++I) {
5636 // when comparing an id<P> on lhs with a static type on rhs,
5637 // see if static class implements all of id's protocols, directly or
5638 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005639 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005640 return false;
5641 }
5642 }
5643 // If there are no qualifiers and no interface, we have an 'id'.
5644 return true;
5645 }
Mike Stump1eb44332009-09-09 15:08:12 +00005646 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005647 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5648 E = lhsQID->qual_end(); I != E; ++I) {
5649 ObjCProtocolDecl *lhsProto = *I;
5650 bool match = false;
5651
5652 // when comparing an id<P> on lhs with a static type on rhs,
5653 // see if static class implements all of id's protocols, directly or
5654 // through its super class and categories.
5655 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5656 E = rhsOPT->qual_end(); J != E; ++J) {
5657 ObjCProtocolDecl *rhsProto = *J;
5658 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5659 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5660 match = true;
5661 break;
5662 }
5663 }
Mike Stump1eb44332009-09-09 15:08:12 +00005664 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005665 // make sure we check the class hierarchy.
5666 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5667 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5668 E = lhsQID->qual_end(); I != E; ++I) {
5669 // when comparing an id<P> on lhs with a static type on rhs,
5670 // see if static class implements all of id's protocols, directly or
5671 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005672 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005673 match = true;
5674 break;
5675 }
5676 }
5677 }
5678 if (!match)
5679 return false;
5680 }
Mike Stump1eb44332009-09-09 15:08:12 +00005681
Steve Naroff4084c302009-07-23 01:01:38 +00005682 return true;
5683 }
Mike Stump1eb44332009-09-09 15:08:12 +00005684
Steve Naroff4084c302009-07-23 01:01:38 +00005685 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5686 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5687
Mike Stump1eb44332009-09-09 15:08:12 +00005688 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005689 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005690 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005691 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5692 E = lhsOPT->qual_end(); I != E; ++I) {
5693 ObjCProtocolDecl *lhsProto = *I;
5694 bool match = false;
5695
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005696 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005697 // see if static class implements all of id's protocols, directly or
5698 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005699 // First, lhs protocols in the qualifier list must be found, direct
5700 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005701 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5702 E = rhsQID->qual_end(); J != E; ++J) {
5703 ObjCProtocolDecl *rhsProto = *J;
5704 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5705 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5706 match = true;
5707 break;
5708 }
5709 }
5710 if (!match)
5711 return false;
5712 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005713
5714 // Static class's protocols, or its super class or category protocols
5715 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5716 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5717 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5718 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5719 // This is rather dubious but matches gcc's behavior. If lhs has
5720 // no type qualifier and its class has no static protocol(s)
5721 // assume that it is mismatch.
5722 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5723 return false;
5724 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5725 LHSInheritedProtocols.begin(),
5726 E = LHSInheritedProtocols.end(); I != E; ++I) {
5727 bool match = false;
5728 ObjCProtocolDecl *lhsProto = (*I);
5729 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5730 E = rhsQID->qual_end(); J != E; ++J) {
5731 ObjCProtocolDecl *rhsProto = *J;
5732 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5733 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5734 match = true;
5735 break;
5736 }
5737 }
5738 if (!match)
5739 return false;
5740 }
5741 }
Steve Naroff4084c302009-07-23 01:01:38 +00005742 return true;
5743 }
5744 return false;
5745}
5746
Eli Friedman3d815e72008-08-22 00:56:42 +00005747/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005748/// compatible for assignment from RHS to LHS. This handles validation of any
5749/// protocol qualifiers on the LHS or RHS.
5750///
Steve Naroff14108da2009-07-10 23:34:53 +00005751bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5752 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005753 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5754 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5755
Steve Naroffde2e22d2009-07-15 18:40:39 +00005756 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005757 if (LHS->isObjCUnqualifiedIdOrClass() ||
5758 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005759 return true;
5760
John McCallc12c5bb2010-05-15 11:32:37 +00005761 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005762 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5763 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005764 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005765
5766 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5767 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5768 QualType(RHSOPT,0));
5769
John McCallc12c5bb2010-05-15 11:32:37 +00005770 // If we have 2 user-defined types, fall into that path.
5771 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005772 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005773
Steve Naroff4084c302009-07-23 01:01:38 +00005774 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005775}
5776
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005777/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005778/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005779/// arguments in block literals. When passed as arguments, passing 'A*' where
5780/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5781/// not OK. For the return type, the opposite is not OK.
5782bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5783 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005784 const ObjCObjectPointerType *RHSOPT,
5785 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005786 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005787 return true;
5788
5789 if (LHSOPT->isObjCBuiltinType()) {
5790 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5791 }
5792
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005793 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005794 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5795 QualType(RHSOPT,0),
5796 false);
5797
5798 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5799 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5800 if (LHS && RHS) { // We have 2 user-defined types.
5801 if (LHS != RHS) {
5802 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005803 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005804 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005805 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005806 }
5807 else
5808 return true;
5809 }
5810 return false;
5811}
5812
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005813/// getIntersectionOfProtocols - This routine finds the intersection of set
5814/// of protocols inherited from two distinct objective-c pointer objects.
5815/// It is used to build composite qualifier list of the composite type of
5816/// the conditional expression involving two objective-c pointer objects.
5817static
5818void getIntersectionOfProtocols(ASTContext &Context,
5819 const ObjCObjectPointerType *LHSOPT,
5820 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005821 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005822
John McCallc12c5bb2010-05-15 11:32:37 +00005823 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5824 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5825 assert(LHS->getInterface() && "LHS must have an interface base");
5826 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005827
5828 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5829 unsigned LHSNumProtocols = LHS->getNumProtocols();
5830 if (LHSNumProtocols > 0)
5831 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5832 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005833 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005834 Context.CollectInheritedProtocols(LHS->getInterface(),
5835 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005836 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5837 LHSInheritedProtocols.end());
5838 }
5839
5840 unsigned RHSNumProtocols = RHS->getNumProtocols();
5841 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005842 ObjCProtocolDecl **RHSProtocols =
5843 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005844 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5845 if (InheritedProtocolSet.count(RHSProtocols[i]))
5846 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00005847 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005848 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005849 Context.CollectInheritedProtocols(RHS->getInterface(),
5850 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005851 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5852 RHSInheritedProtocols.begin(),
5853 E = RHSInheritedProtocols.end(); I != E; ++I)
5854 if (InheritedProtocolSet.count((*I)))
5855 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005856 }
5857}
5858
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005859/// areCommonBaseCompatible - Returns common base class of the two classes if
5860/// one found. Note that this is O'2 algorithm. But it will be called as the
5861/// last type comparison in a ?-exp of ObjC pointer types before a
5862/// warning is issued. So, its invokation is extremely rare.
5863QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005864 const ObjCObjectPointerType *Lptr,
5865 const ObjCObjectPointerType *Rptr) {
5866 const ObjCObjectType *LHS = Lptr->getObjectType();
5867 const ObjCObjectType *RHS = Rptr->getObjectType();
5868 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5869 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00005870 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005871 return QualType();
5872
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005873 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005874 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005875 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005876 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005877 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5878
5879 QualType Result = QualType(LHS, 0);
5880 if (!Protocols.empty())
5881 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5882 Result = getObjCObjectPointerType(Result);
5883 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005884 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005885 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005886
5887 return QualType();
5888}
5889
John McCallc12c5bb2010-05-15 11:32:37 +00005890bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5891 const ObjCObjectType *RHS) {
5892 assert(LHS->getInterface() && "LHS is not an interface type");
5893 assert(RHS->getInterface() && "RHS is not an interface type");
5894
Chris Lattner6ac46a42008-04-07 06:51:04 +00005895 // Verify that the base decls are compatible: the RHS must be a subclass of
5896 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005897 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005898 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005899
Chris Lattner6ac46a42008-04-07 06:51:04 +00005900 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5901 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005902 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005903 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005904
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005905 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5906 // more detailed analysis is required.
5907 if (RHS->getNumProtocols() == 0) {
5908 // OK, if LHS is a superclass of RHS *and*
5909 // this superclass is assignment compatible with LHS.
5910 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005911 bool IsSuperClass =
5912 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5913 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005914 // OK if conversion of LHS to SuperClass results in narrowing of types
5915 // ; i.e., SuperClass may implement at least one of the protocols
5916 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5917 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5918 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005919 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005920 // If super class has no protocols, it is not a match.
5921 if (SuperClassInheritedProtocols.empty())
5922 return false;
5923
5924 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5925 LHSPE = LHS->qual_end();
5926 LHSPI != LHSPE; LHSPI++) {
5927 bool SuperImplementsProtocol = false;
5928 ObjCProtocolDecl *LHSProto = (*LHSPI);
5929
5930 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5931 SuperClassInheritedProtocols.begin(),
5932 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5933 ObjCProtocolDecl *SuperClassProto = (*I);
5934 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5935 SuperImplementsProtocol = true;
5936 break;
5937 }
5938 }
5939 if (!SuperImplementsProtocol)
5940 return false;
5941 }
5942 return true;
5943 }
5944 return false;
5945 }
Mike Stump1eb44332009-09-09 15:08:12 +00005946
John McCallc12c5bb2010-05-15 11:32:37 +00005947 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5948 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005949 LHSPI != LHSPE; LHSPI++) {
5950 bool RHSImplementsProtocol = false;
5951
5952 // If the RHS doesn't implement the protocol on the left, the types
5953 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005954 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5955 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005956 RHSPI != RHSPE; RHSPI++) {
5957 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005958 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005959 break;
5960 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005961 }
5962 // FIXME: For better diagnostics, consider passing back the protocol name.
5963 if (!RHSImplementsProtocol)
5964 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005965 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005966 // The RHS implements all protocols listed on the LHS.
5967 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005968}
5969
Steve Naroff389bf462009-02-12 17:52:19 +00005970bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5971 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005972 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5973 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005974
Steve Naroff14108da2009-07-10 23:34:53 +00005975 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005976 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005977
5978 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5979 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005980}
5981
Douglas Gregor569c3162010-08-07 11:51:51 +00005982bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5983 return canAssignObjCInterfaces(
5984 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5985 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5986}
5987
Mike Stump1eb44332009-09-09 15:08:12 +00005988/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005989/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005990/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005991/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005992bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5993 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005994 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005995 return hasSameType(LHS, RHS);
5996
Douglas Gregor447234d2010-07-29 15:18:02 +00005997 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005998}
5999
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006000bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006001 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006002}
6003
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006004bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6005 return !mergeTypes(LHS, RHS, true).isNull();
6006}
6007
Peter Collingbourne48466752010-10-24 18:30:18 +00006008/// mergeTransparentUnionType - if T is a transparent union type and a member
6009/// of T is compatible with SubType, return the merged type, else return
6010/// QualType()
6011QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6012 bool OfBlockPointer,
6013 bool Unqualified) {
6014 if (const RecordType *UT = T->getAsUnionType()) {
6015 RecordDecl *UD = UT->getDecl();
6016 if (UD->hasAttr<TransparentUnionAttr>()) {
6017 for (RecordDecl::field_iterator it = UD->field_begin(),
6018 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006019 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006020 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6021 if (!MT.isNull())
6022 return MT;
6023 }
6024 }
6025 }
6026
6027 return QualType();
6028}
6029
6030/// mergeFunctionArgumentTypes - merge two types which appear as function
6031/// argument types
6032QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6033 bool OfBlockPointer,
6034 bool Unqualified) {
6035 // GNU extension: two types are compatible if they appear as a function
6036 // argument, one of the types is a transparent union type and the other
6037 // type is compatible with a union member
6038 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6039 Unqualified);
6040 if (!lmerge.isNull())
6041 return lmerge;
6042
6043 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6044 Unqualified);
6045 if (!rmerge.isNull())
6046 return rmerge;
6047
6048 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6049}
6050
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006051QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006052 bool OfBlockPointer,
6053 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006054 const FunctionType *lbase = lhs->getAs<FunctionType>();
6055 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006056 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6057 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006058 bool allLTypes = true;
6059 bool allRTypes = true;
6060
6061 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006062 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006063 if (OfBlockPointer) {
6064 QualType RHS = rbase->getResultType();
6065 QualType LHS = lbase->getResultType();
6066 bool UnqualifiedResult = Unqualified;
6067 if (!UnqualifiedResult)
6068 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006069 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006070 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006071 else
John McCall8cc246c2010-12-15 01:06:38 +00006072 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6073 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006074 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006075
6076 if (Unqualified)
6077 retType = retType.getUnqualifiedType();
6078
6079 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6080 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6081 if (Unqualified) {
6082 LRetType = LRetType.getUnqualifiedType();
6083 RRetType = RRetType.getUnqualifiedType();
6084 }
6085
6086 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006087 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006088 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006089 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006090
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006091 // FIXME: double check this
6092 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6093 // rbase->getRegParmAttr() != 0 &&
6094 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006095 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6096 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006097
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006098 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006099 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006100 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006101
John McCall8cc246c2010-12-15 01:06:38 +00006102 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006103 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6104 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006105 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6106 return QualType();
6107
John McCallf85e1932011-06-15 23:02:42 +00006108 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6109 return QualType();
6110
Fariborz Jahanian53c81672011-10-05 00:05:34 +00006111 // functypes which return are preferred over those that do not.
6112 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6113 allLTypes = false;
6114 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6115 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006116 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6117 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006118
John McCallf85e1932011-06-15 23:02:42 +00006119 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006120
Eli Friedman3d815e72008-08-22 00:56:42 +00006121 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006122 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6123 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006124 unsigned lproto_nargs = lproto->getNumArgs();
6125 unsigned rproto_nargs = rproto->getNumArgs();
6126
6127 // Compatible functions must have the same number of arguments
6128 if (lproto_nargs != rproto_nargs)
6129 return QualType();
6130
6131 // Variadic and non-variadic functions aren't compatible
6132 if (lproto->isVariadic() != rproto->isVariadic())
6133 return QualType();
6134
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006135 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6136 return QualType();
6137
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006138 if (LangOpts.ObjCAutoRefCount &&
6139 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6140 return QualType();
6141
Eli Friedman3d815e72008-08-22 00:56:42 +00006142 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006143 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006144 for (unsigned i = 0; i < lproto_nargs; i++) {
6145 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6146 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006147 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6148 OfBlockPointer,
6149 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006150 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006151
6152 if (Unqualified)
6153 argtype = argtype.getUnqualifiedType();
6154
Eli Friedman3d815e72008-08-22 00:56:42 +00006155 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006156 if (Unqualified) {
6157 largtype = largtype.getUnqualifiedType();
6158 rargtype = rargtype.getUnqualifiedType();
6159 }
6160
Chris Lattner61710852008-10-05 17:34:18 +00006161 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6162 allLTypes = false;
6163 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6164 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006165 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006166
Eli Friedman3d815e72008-08-22 00:56:42 +00006167 if (allLTypes) return lhs;
6168 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006169
6170 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6171 EPI.ExtInfo = einfo;
6172 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006173 }
6174
6175 if (lproto) allRTypes = false;
6176 if (rproto) allLTypes = false;
6177
Douglas Gregor72564e72009-02-26 23:50:07 +00006178 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00006179 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00006180 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006181 if (proto->isVariadic()) return QualType();
6182 // Check that the types are compatible with the types that
6183 // would result from default argument promotions (C99 6.7.5.3p15).
6184 // The only types actually affected are promotable integer
6185 // types and floats, which would be passed as a different
6186 // type depending on whether the prototype is visible.
6187 unsigned proto_nargs = proto->getNumArgs();
6188 for (unsigned i = 0; i < proto_nargs; ++i) {
6189 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006190
6191 // Look at the promotion type of enum types, since that is the type used
6192 // to pass enum values.
6193 if (const EnumType *Enum = argTy->getAs<EnumType>())
6194 argTy = Enum->getDecl()->getPromotionType();
6195
Eli Friedman3d815e72008-08-22 00:56:42 +00006196 if (argTy->isPromotableIntegerType() ||
6197 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6198 return QualType();
6199 }
6200
6201 if (allLTypes) return lhs;
6202 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006203
6204 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6205 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00006206 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006207 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006208 }
6209
6210 if (allLTypes) return lhs;
6211 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00006212 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00006213}
6214
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006215QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00006216 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006217 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00006218 // C++ [expr]: If an expression initially has the type "reference to T", the
6219 // type is adjusted to "T" prior to any further analysis, the expression
6220 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006221 // expression is an lvalue unless the reference is an rvalue reference and
6222 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006223 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6224 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00006225
6226 if (Unqualified) {
6227 LHS = LHS.getUnqualifiedType();
6228 RHS = RHS.getUnqualifiedType();
6229 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006230
Eli Friedman3d815e72008-08-22 00:56:42 +00006231 QualType LHSCan = getCanonicalType(LHS),
6232 RHSCan = getCanonicalType(RHS);
6233
6234 // If two types are identical, they are compatible.
6235 if (LHSCan == RHSCan)
6236 return LHS;
6237
John McCall0953e762009-09-24 19:53:00 +00006238 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006239 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6240 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00006241 if (LQuals != RQuals) {
6242 // If any of these qualifiers are different, we have a type
6243 // mismatch.
6244 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00006245 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6246 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00006247 return QualType();
6248
6249 // Exactly one GC qualifier difference is allowed: __strong is
6250 // okay if the other type has no GC qualifier but is an Objective
6251 // C object pointer (i.e. implicitly strong by default). We fix
6252 // this by pretending that the unqualified type was actually
6253 // qualified __strong.
6254 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6255 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6256 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6257
6258 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6259 return QualType();
6260
6261 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6262 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6263 }
6264 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6265 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6266 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006267 return QualType();
John McCall0953e762009-09-24 19:53:00 +00006268 }
6269
6270 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00006271
Eli Friedman852d63b2009-06-01 01:22:52 +00006272 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6273 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00006274
Chris Lattner1adb8832008-01-14 05:45:46 +00006275 // We want to consider the two function types to be the same for these
6276 // comparisons, just force one to the other.
6277 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6278 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00006279
6280 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00006281 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6282 LHSClass = Type::ConstantArray;
6283 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6284 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00006285
John McCallc12c5bb2010-05-15 11:32:37 +00006286 // ObjCInterfaces are just specialized ObjCObjects.
6287 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6288 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6289
Nate Begeman213541a2008-04-18 23:10:10 +00006290 // Canonicalize ExtVector -> Vector.
6291 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6292 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00006293
Chris Lattnera36a61f2008-04-07 05:43:21 +00006294 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006295 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00006296 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00006297 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00006298 // Compatibility is based on the underlying type, not the promotion
6299 // type.
John McCall183700f2009-09-21 23:43:11 +00006300 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006301 QualType TINT = ETy->getDecl()->getIntegerType();
6302 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006303 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006304 }
John McCall183700f2009-09-21 23:43:11 +00006305 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006306 QualType TINT = ETy->getDecl()->getIntegerType();
6307 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006308 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006309 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006310 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00006311 if (OfBlockPointer && !BlockReturnType) {
6312 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6313 return LHS;
6314 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6315 return RHS;
6316 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006317
Eli Friedman3d815e72008-08-22 00:56:42 +00006318 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00006319 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006320
Steve Naroff4a746782008-01-09 22:43:08 +00006321 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006322 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00006323#define TYPE(Class, Base)
6324#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00006325#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00006326#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6327#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6328#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00006329 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00006330
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006331 case Type::LValueReference:
6332 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00006333 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00006334 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00006335
John McCallc12c5bb2010-05-15 11:32:37 +00006336 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00006337 case Type::IncompleteArray:
6338 case Type::VariableArray:
6339 case Type::FunctionProto:
6340 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00006341 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00006342
Chris Lattner1adb8832008-01-14 05:45:46 +00006343 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00006344 {
6345 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006346 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6347 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006348 if (Unqualified) {
6349 LHSPointee = LHSPointee.getUnqualifiedType();
6350 RHSPointee = RHSPointee.getUnqualifiedType();
6351 }
6352 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6353 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006354 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00006355 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006356 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00006357 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006358 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006359 return getPointerType(ResultType);
6360 }
Steve Naroffc0febd52008-12-10 17:49:55 +00006361 case Type::BlockPointer:
6362 {
6363 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006364 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6365 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006366 if (Unqualified) {
6367 LHSPointee = LHSPointee.getUnqualifiedType();
6368 RHSPointee = RHSPointee.getUnqualifiedType();
6369 }
6370 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6371 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00006372 if (ResultType.isNull()) return QualType();
6373 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6374 return LHS;
6375 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6376 return RHS;
6377 return getBlockPointerType(ResultType);
6378 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006379 case Type::Atomic:
6380 {
6381 // Merge two pointer types, while trying to preserve typedef info
6382 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6383 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6384 if (Unqualified) {
6385 LHSValue = LHSValue.getUnqualifiedType();
6386 RHSValue = RHSValue.getUnqualifiedType();
6387 }
6388 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6389 Unqualified);
6390 if (ResultType.isNull()) return QualType();
6391 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6392 return LHS;
6393 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6394 return RHS;
6395 return getAtomicType(ResultType);
6396 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006397 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006398 {
6399 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6400 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6401 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6402 return QualType();
6403
6404 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6405 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006406 if (Unqualified) {
6407 LHSElem = LHSElem.getUnqualifiedType();
6408 RHSElem = RHSElem.getUnqualifiedType();
6409 }
6410
6411 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006412 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006413 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6414 return LHS;
6415 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6416 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006417 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6418 ArrayType::ArraySizeModifier(), 0);
6419 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6420 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006421 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6422 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006423 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6424 return LHS;
6425 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6426 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006427 if (LVAT) {
6428 // FIXME: This isn't correct! But tricky to implement because
6429 // the array's size has to be the size of LHS, but the type
6430 // has to be different.
6431 return LHS;
6432 }
6433 if (RVAT) {
6434 // FIXME: This isn't correct! But tricky to implement because
6435 // the array's size has to be the size of RHS, but the type
6436 // has to be different.
6437 return RHS;
6438 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006439 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6440 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006441 return getIncompleteArrayType(ResultType,
6442 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006443 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006444 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006445 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006446 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006447 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006448 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006449 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006450 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006451 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006452 case Type::Complex:
6453 // Distinct complex types are incompatible.
6454 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006455 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006456 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006457 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6458 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006459 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006460 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006461 case Type::ObjCObject: {
6462 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006463 // FIXME: This should be type compatibility, e.g. whether
6464 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006465 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6466 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6467 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006468 return LHS;
6469
Eli Friedman3d815e72008-08-22 00:56:42 +00006470 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006471 }
Steve Naroff14108da2009-07-10 23:34:53 +00006472 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006473 if (OfBlockPointer) {
6474 if (canAssignObjCInterfacesInBlockPointer(
6475 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006476 RHS->getAs<ObjCObjectPointerType>(),
6477 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00006478 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006479 return QualType();
6480 }
John McCall183700f2009-09-21 23:43:11 +00006481 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6482 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006483 return LHS;
6484
Steve Naroffbc76dd02008-12-10 22:14:21 +00006485 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00006486 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006487 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006488
David Blaikie7530c032012-01-17 06:56:22 +00006489 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00006490}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006491
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006492bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6493 const FunctionProtoType *FromFunctionType,
6494 const FunctionProtoType *ToFunctionType) {
6495 if (FromFunctionType->hasAnyConsumedArgs() !=
6496 ToFunctionType->hasAnyConsumedArgs())
6497 return false;
6498 FunctionProtoType::ExtProtoInfo FromEPI =
6499 FromFunctionType->getExtProtoInfo();
6500 FunctionProtoType::ExtProtoInfo ToEPI =
6501 ToFunctionType->getExtProtoInfo();
6502 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6503 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6504 ArgIdx != NumArgs; ++ArgIdx) {
6505 if (FromEPI.ConsumedArguments[ArgIdx] !=
6506 ToEPI.ConsumedArguments[ArgIdx])
6507 return false;
6508 }
6509 return true;
6510}
6511
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006512/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6513/// 'RHS' attributes and returns the merged version; including for function
6514/// return types.
6515QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6516 QualType LHSCan = getCanonicalType(LHS),
6517 RHSCan = getCanonicalType(RHS);
6518 // If two types are identical, they are compatible.
6519 if (LHSCan == RHSCan)
6520 return LHS;
6521 if (RHSCan->isFunctionType()) {
6522 if (!LHSCan->isFunctionType())
6523 return QualType();
6524 QualType OldReturnType =
6525 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6526 QualType NewReturnType =
6527 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6528 QualType ResReturnType =
6529 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6530 if (ResReturnType.isNull())
6531 return QualType();
6532 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6533 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6534 // In either case, use OldReturnType to build the new function type.
6535 const FunctionType *F = LHS->getAs<FunctionType>();
6536 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006537 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6538 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006539 QualType ResultType
6540 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006541 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006542 return ResultType;
6543 }
6544 }
6545 return QualType();
6546 }
6547
6548 // If the qualifiers are different, the types can still be merged.
6549 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6550 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6551 if (LQuals != RQuals) {
6552 // If any of these qualifiers are different, we have a type mismatch.
6553 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6554 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6555 return QualType();
6556
6557 // Exactly one GC qualifier difference is allowed: __strong is
6558 // okay if the other type has no GC qualifier but is an Objective
6559 // C object pointer (i.e. implicitly strong by default). We fix
6560 // this by pretending that the unqualified type was actually
6561 // qualified __strong.
6562 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6563 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6564 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6565
6566 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6567 return QualType();
6568
6569 if (GC_L == Qualifiers::Strong)
6570 return LHS;
6571 if (GC_R == Qualifiers::Strong)
6572 return RHS;
6573 return QualType();
6574 }
6575
6576 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6577 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6578 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6579 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6580 if (ResQT == LHSBaseQT)
6581 return LHS;
6582 if (ResQT == RHSBaseQT)
6583 return RHS;
6584 }
6585 return QualType();
6586}
6587
Chris Lattner5426bf62008-04-07 07:01:58 +00006588//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006589// Integer Predicates
6590//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006591
Jay Foad4ba2a172011-01-12 09:06:06 +00006592unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006593 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006594 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006595 if (T->isBooleanType())
6596 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006597 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006598 return (unsigned)getTypeSize(T);
6599}
6600
6601QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006602 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006603
6604 // Turn <4 x signed int> -> <4 x unsigned int>
6605 if (const VectorType *VTy = T->getAs<VectorType>())
6606 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006607 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006608
6609 // For enums, we return the unsigned version of the base type.
6610 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006611 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006612
6613 const BuiltinType *BTy = T->getAs<BuiltinType>();
6614 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006615 switch (BTy->getKind()) {
6616 case BuiltinType::Char_S:
6617 case BuiltinType::SChar:
6618 return UnsignedCharTy;
6619 case BuiltinType::Short:
6620 return UnsignedShortTy;
6621 case BuiltinType::Int:
6622 return UnsignedIntTy;
6623 case BuiltinType::Long:
6624 return UnsignedLongTy;
6625 case BuiltinType::LongLong:
6626 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006627 case BuiltinType::Int128:
6628 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006629 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006630 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006631 }
6632}
6633
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006634ASTMutationListener::~ASTMutationListener() { }
6635
Chris Lattner86df27b2009-06-14 00:45:47 +00006636
6637//===----------------------------------------------------------------------===//
6638// Builtin Type Computation
6639//===----------------------------------------------------------------------===//
6640
6641/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006642/// pointer over the consumed characters. This returns the resultant type. If
6643/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6644/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6645/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006646///
6647/// RequiresICE is filled in on return to indicate whether the value is required
6648/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006649static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006650 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006651 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006652 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006653 // Modifiers.
6654 int HowLong = 0;
6655 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006656 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006657
Chris Lattner33daae62010-10-01 22:42:38 +00006658 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006659 bool Done = false;
6660 while (!Done) {
6661 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006662 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006663 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006664 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006665 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006666 case 'S':
6667 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6668 assert(!Signed && "Can't use 'S' modifier multiple times!");
6669 Signed = true;
6670 break;
6671 case 'U':
6672 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6673 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6674 Unsigned = true;
6675 break;
6676 case 'L':
6677 assert(HowLong <= 2 && "Can't have LLLL modifier");
6678 ++HowLong;
6679 break;
6680 }
6681 }
6682
6683 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006684
Chris Lattner86df27b2009-06-14 00:45:47 +00006685 // Read the base type.
6686 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006687 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006688 case 'v':
6689 assert(HowLong == 0 && !Signed && !Unsigned &&
6690 "Bad modifiers used with 'v'!");
6691 Type = Context.VoidTy;
6692 break;
6693 case 'f':
6694 assert(HowLong == 0 && !Signed && !Unsigned &&
6695 "Bad modifiers used with 'f'!");
6696 Type = Context.FloatTy;
6697 break;
6698 case 'd':
6699 assert(HowLong < 2 && !Signed && !Unsigned &&
6700 "Bad modifiers used with 'd'!");
6701 if (HowLong)
6702 Type = Context.LongDoubleTy;
6703 else
6704 Type = Context.DoubleTy;
6705 break;
6706 case 's':
6707 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6708 if (Unsigned)
6709 Type = Context.UnsignedShortTy;
6710 else
6711 Type = Context.ShortTy;
6712 break;
6713 case 'i':
6714 if (HowLong == 3)
6715 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6716 else if (HowLong == 2)
6717 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6718 else if (HowLong == 1)
6719 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6720 else
6721 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6722 break;
6723 case 'c':
6724 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6725 if (Signed)
6726 Type = Context.SignedCharTy;
6727 else if (Unsigned)
6728 Type = Context.UnsignedCharTy;
6729 else
6730 Type = Context.CharTy;
6731 break;
6732 case 'b': // boolean
6733 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6734 Type = Context.BoolTy;
6735 break;
6736 case 'z': // size_t.
6737 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6738 Type = Context.getSizeType();
6739 break;
6740 case 'F':
6741 Type = Context.getCFConstantStringType();
6742 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006743 case 'G':
6744 Type = Context.getObjCIdType();
6745 break;
6746 case 'H':
6747 Type = Context.getObjCSelType();
6748 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006749 case 'a':
6750 Type = Context.getBuiltinVaListType();
6751 assert(!Type.isNull() && "builtin va list type not initialized!");
6752 break;
6753 case 'A':
6754 // This is a "reference" to a va_list; however, what exactly
6755 // this means depends on how va_list is defined. There are two
6756 // different kinds of va_list: ones passed by value, and ones
6757 // passed by reference. An example of a by-value va_list is
6758 // x86, where va_list is a char*. An example of by-ref va_list
6759 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6760 // we want this argument to be a char*&; for x86-64, we want
6761 // it to be a __va_list_tag*.
6762 Type = Context.getBuiltinVaListType();
6763 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006764 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006765 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006766 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006767 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006768 break;
6769 case 'V': {
6770 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006771 unsigned NumElements = strtoul(Str, &End, 10);
6772 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006773 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006774
Chris Lattner14e0e742010-10-01 22:53:11 +00006775 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6776 RequiresICE, false);
6777 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006778
6779 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006780 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006781 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006782 break;
6783 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00006784 case 'E': {
6785 char *End;
6786
6787 unsigned NumElements = strtoul(Str, &End, 10);
6788 assert(End != Str && "Missing vector size");
6789
6790 Str = End;
6791
6792 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6793 false);
6794 Type = Context.getExtVectorType(ElementType, NumElements);
6795 break;
6796 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006797 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006798 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6799 false);
6800 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006801 Type = Context.getComplexType(ElementType);
6802 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00006803 }
6804 case 'Y' : {
6805 Type = Context.getPointerDiffType();
6806 break;
6807 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006808 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006809 Type = Context.getFILEType();
6810 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006811 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006812 return QualType();
6813 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006814 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006815 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006816 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006817 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006818 else
6819 Type = Context.getjmp_bufType();
6820
Mike Stumpfd612db2009-07-28 23:47:15 +00006821 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006822 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006823 return QualType();
6824 }
6825 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00006826 case 'K':
6827 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6828 Type = Context.getucontext_tType();
6829
6830 if (Type.isNull()) {
6831 Error = ASTContext::GE_Missing_ucontext;
6832 return QualType();
6833 }
6834 break;
Mike Stump782fa302009-07-28 02:25:19 +00006835 }
Mike Stump1eb44332009-09-09 15:08:12 +00006836
Chris Lattner33daae62010-10-01 22:42:38 +00006837 // If there are modifiers and if we're allowed to parse them, go for it.
6838 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006839 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006840 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006841 default: Done = true; --Str; break;
6842 case '*':
6843 case '&': {
6844 // Both pointers and references can have their pointee types
6845 // qualified with an address space.
6846 char *End;
6847 unsigned AddrSpace = strtoul(Str, &End, 10);
6848 if (End != Str && AddrSpace != 0) {
6849 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6850 Str = End;
6851 }
6852 if (c == '*')
6853 Type = Context.getPointerType(Type);
6854 else
6855 Type = Context.getLValueReferenceType(Type);
6856 break;
6857 }
6858 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6859 case 'C':
6860 Type = Type.withConst();
6861 break;
6862 case 'D':
6863 Type = Context.getVolatileType(Type);
6864 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00006865 case 'R':
6866 Type = Type.withRestrict();
6867 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006868 }
6869 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006870
Chris Lattner14e0e742010-10-01 22:53:11 +00006871 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006872 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006873
Chris Lattner86df27b2009-06-14 00:45:47 +00006874 return Type;
6875}
6876
6877/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006878QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006879 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006880 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006881 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006882
Chris Lattner5f9e2722011-07-23 10:55:15 +00006883 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006884
Chris Lattner14e0e742010-10-01 22:53:11 +00006885 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006886 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006887 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6888 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006889 if (Error != GE_None)
6890 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006891
6892 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6893
Chris Lattner86df27b2009-06-14 00:45:47 +00006894 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006895 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006896 if (Error != GE_None)
6897 return QualType();
6898
Chris Lattner14e0e742010-10-01 22:53:11 +00006899 // If this argument is required to be an IntegerConstantExpression and the
6900 // caller cares, fill in the bitmask we return.
6901 if (RequiresICE && IntegerConstantArgs)
6902 *IntegerConstantArgs |= 1 << ArgTypes.size();
6903
Chris Lattner86df27b2009-06-14 00:45:47 +00006904 // Do array -> pointer decay. The builtin should use the decayed type.
6905 if (Ty->isArrayType())
6906 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006907
Chris Lattner86df27b2009-06-14 00:45:47 +00006908 ArgTypes.push_back(Ty);
6909 }
6910
6911 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6912 "'.' should only occur at end of builtin type list!");
6913
John McCall00ccbef2010-12-21 00:44:39 +00006914 FunctionType::ExtInfo EI;
6915 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6916
6917 bool Variadic = (TypeStr[0] == '.');
6918
6919 // We really shouldn't be making a no-proto type here, especially in C++.
6920 if (ArgTypes.empty() && Variadic)
6921 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006922
John McCalle23cf432010-12-14 08:05:40 +00006923 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006924 EPI.ExtInfo = EI;
6925 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006926
6927 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006928}
Eli Friedmana95d7572009-08-19 07:44:53 +00006929
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006930GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6931 GVALinkage External = GVA_StrongExternal;
6932
6933 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006934 switch (L) {
6935 case NoLinkage:
6936 case InternalLinkage:
6937 case UniqueExternalLinkage:
6938 return GVA_Internal;
6939
6940 case ExternalLinkage:
6941 switch (FD->getTemplateSpecializationKind()) {
6942 case TSK_Undeclared:
6943 case TSK_ExplicitSpecialization:
6944 External = GVA_StrongExternal;
6945 break;
6946
6947 case TSK_ExplicitInstantiationDefinition:
6948 return GVA_ExplicitTemplateInstantiation;
6949
6950 case TSK_ExplicitInstantiationDeclaration:
6951 case TSK_ImplicitInstantiation:
6952 External = GVA_TemplateInstantiation;
6953 break;
6954 }
6955 }
6956
6957 if (!FD->isInlined())
6958 return External;
6959
David Blaikie4e4d0842012-03-11 07:00:24 +00006960 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006961 // GNU or C99 inline semantics. Determine whether this symbol should be
6962 // externally visible.
6963 if (FD->isInlineDefinitionExternallyVisible())
6964 return External;
6965
6966 // C99 inline semantics, where the symbol is not externally visible.
6967 return GVA_C99Inline;
6968 }
6969
6970 // C++0x [temp.explicit]p9:
6971 // [ Note: The intent is that an inline function that is the subject of
6972 // an explicit instantiation declaration will still be implicitly
6973 // instantiated when used so that the body can be considered for
6974 // inlining, but that no out-of-line copy of the inline function would be
6975 // generated in the translation unit. -- end note ]
6976 if (FD->getTemplateSpecializationKind()
6977 == TSK_ExplicitInstantiationDeclaration)
6978 return GVA_C99Inline;
6979
6980 return GVA_CXXInline;
6981}
6982
6983GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6984 // If this is a static data member, compute the kind of template
6985 // specialization. Otherwise, this variable is not part of a
6986 // template.
6987 TemplateSpecializationKind TSK = TSK_Undeclared;
6988 if (VD->isStaticDataMember())
6989 TSK = VD->getTemplateSpecializationKind();
6990
6991 Linkage L = VD->getLinkage();
David Blaikie4e4d0842012-03-11 07:00:24 +00006992 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006993 VD->getType()->getLinkage() == UniqueExternalLinkage)
6994 L = UniqueExternalLinkage;
6995
6996 switch (L) {
6997 case NoLinkage:
6998 case InternalLinkage:
6999 case UniqueExternalLinkage:
7000 return GVA_Internal;
7001
7002 case ExternalLinkage:
7003 switch (TSK) {
7004 case TSK_Undeclared:
7005 case TSK_ExplicitSpecialization:
7006 return GVA_StrongExternal;
7007
7008 case TSK_ExplicitInstantiationDeclaration:
7009 llvm_unreachable("Variable should not be instantiated");
7010 // Fall through to treat this like any other instantiation.
7011
7012 case TSK_ExplicitInstantiationDefinition:
7013 return GVA_ExplicitTemplateInstantiation;
7014
7015 case TSK_ImplicitInstantiation:
7016 return GVA_TemplateInstantiation;
7017 }
7018 }
7019
David Blaikie7530c032012-01-17 06:56:22 +00007020 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007021}
7022
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007023bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007024 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7025 if (!VD->isFileVarDecl())
7026 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00007027 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007028 return false;
7029
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007030 // Weak references don't produce any output by themselves.
7031 if (D->hasAttr<WeakRefAttr>())
7032 return false;
7033
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007034 // Aliases and used decls are required.
7035 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7036 return true;
7037
7038 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7039 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007040 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007041 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007042
7043 // Constructors and destructors are required.
7044 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7045 return true;
7046
7047 // The key function for a class is required.
7048 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7049 const CXXRecordDecl *RD = MD->getParent();
7050 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7051 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7052 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7053 return true;
7054 }
7055 }
7056
7057 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7058
7059 // static, static inline, always_inline, and extern inline functions can
7060 // always be deferred. Normal inline functions can be deferred in C99/C++.
7061 // Implicit template instantiations can also be deferred in C++.
7062 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007063 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007064 return false;
7065 return true;
7066 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007067
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007068 const VarDecl *VD = cast<VarDecl>(D);
7069 assert(VD->isFileVarDecl() && "Expected file scoped var");
7070
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007071 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7072 return false;
7073
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007074 // Structs that have non-trivial constructors or destructors are required.
7075
7076 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00007077 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007078 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7079 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00007080 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7081 RD->hasTrivialCopyConstructor() &&
7082 RD->hasTrivialMoveConstructor() &&
7083 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007084 return true;
7085 }
7086 }
7087
7088 GVALinkage L = GetGVALinkageForVariable(VD);
7089 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7090 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7091 return false;
7092 }
7093
7094 return true;
7095}
Charles Davis071cc7d2010-08-16 03:33:14 +00007096
Charles Davisee743f92010-11-09 18:04:24 +00007097CallingConv ASTContext::getDefaultMethodCallConv() {
7098 // Pass through to the C++ ABI object
7099 return ABI->getDefaultMethodCallConv();
7100}
7101
Jay Foad4ba2a172011-01-12 09:06:06 +00007102bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007103 // Pass through to the C++ ABI object
7104 return ABI->isNearlyEmpty(RD);
7105}
7106
Peter Collingbourne14110472011-01-13 18:57:25 +00007107MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007108 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00007109 case CXXABI_ARM:
7110 case CXXABI_Itanium:
7111 return createItaniumMangleContext(*this, getDiagnostics());
7112 case CXXABI_Microsoft:
7113 return createMicrosoftMangleContext(*this, getDiagnostics());
7114 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007115 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007116}
7117
Charles Davis071cc7d2010-08-16 03:33:14 +00007118CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007119
7120size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007121 return ASTRecordLayouts.getMemorySize()
7122 + llvm::capacity_in_bytes(ObjCLayouts)
7123 + llvm::capacity_in_bytes(KeyFunctions)
7124 + llvm::capacity_in_bytes(ObjCImpls)
7125 + llvm::capacity_in_bytes(BlockVarCopyInits)
7126 + llvm::capacity_in_bytes(DeclAttrs)
7127 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7128 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7129 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7130 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7131 + llvm::capacity_in_bytes(OverriddenMethods)
7132 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007133 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007134 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007135}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007136
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00007137unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7138 CXXRecordDecl *Lambda = CallOperator->getParent();
7139 return LambdaMangleContexts[Lambda->getDeclContext()]
7140 .getManglingNumber(CallOperator);
7141}
7142
7143
Ted Kremenekd211cb72011-10-06 05:00:56 +00007144void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7145 ParamIndices[D] = index;
7146}
7147
7148unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7149 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7150 assert(I != ParamIndices.end() &&
7151 "ParmIndices lacks entry set by ParmVarDecl");
7152 return I->second;
7153}